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/host_cache.h"
28 #include "net/dns/mock_host_resolver.h"
29 #include "testing/gtest/include/gtest/gtest.h"
35 const size_t kMaxJobs
= 10u;
36 const size_t kMaxRetryAttempts
= 4u;
38 PrioritizedDispatcher::Limits
DefaultLimits() {
39 PrioritizedDispatcher::Limits
limits(NUM_PRIORITIES
, kMaxJobs
);
43 HostResolverImpl::ProcTaskParams
DefaultParams(
44 HostResolverProc
* resolver_proc
) {
45 return HostResolverImpl::ProcTaskParams(resolver_proc
, kMaxRetryAttempts
);
48 // A HostResolverProc that pushes each host mapped into a list and allows
49 // waiting for a specific number of requests. Unlike RuleBasedHostResolverProc
50 // it never calls SystemHostResolverCall. By default resolves all hostnames to
51 // "127.0.0.1". After AddRule(), it resolves only names explicitly specified.
52 class MockHostResolverProc
: public HostResolverProc
{
55 ResolveKey(const std::string
& hostname
, AddressFamily address_family
)
56 : hostname(hostname
), address_family(address_family
) {}
57 bool operator<(const ResolveKey
& other
) const {
58 return address_family
< other
.address_family
||
59 (address_family
== other
.address_family
&& hostname
< other
.hostname
);
62 AddressFamily address_family
;
65 typedef std::vector
<ResolveKey
> CaptureList
;
67 MockHostResolverProc()
68 : HostResolverProc(NULL
),
69 num_requests_waiting_(0),
70 num_slots_available_(0),
71 requests_waiting_(&lock_
),
72 slots_available_(&lock_
) {
75 // Waits until |count| calls to |Resolve| are blocked. Returns false when
77 bool WaitFor(unsigned count
) {
78 base::AutoLock
lock(lock_
);
79 base::Time start_time
= base::Time::Now();
80 while (num_requests_waiting_
< count
) {
81 requests_waiting_
.TimedWait(TestTimeouts::action_timeout());
82 if (base::Time::Now() > start_time
+ TestTimeouts::action_timeout())
88 // Signals |count| waiting calls to |Resolve|. First come first served.
89 void SignalMultiple(unsigned count
) {
90 base::AutoLock
lock(lock_
);
91 num_slots_available_
+= count
;
92 slots_available_
.Broadcast();
95 // Signals all waiting calls to |Resolve|. Beware of races.
97 base::AutoLock
lock(lock_
);
98 num_slots_available_
= num_requests_waiting_
;
99 slots_available_
.Broadcast();
102 void AddRule(const std::string
& hostname
, AddressFamily family
,
103 const AddressList
& result
) {
104 base::AutoLock
lock(lock_
);
105 rules_
[ResolveKey(hostname
, family
)] = result
;
108 void AddRule(const std::string
& hostname
, AddressFamily family
,
109 const std::string
& ip_list
) {
111 int rv
= ParseAddressList(ip_list
, std::string(), &result
);
113 AddRule(hostname
, family
, result
);
116 void AddRuleForAllFamilies(const std::string
& hostname
,
117 const std::string
& ip_list
) {
119 int rv
= ParseAddressList(ip_list
, std::string(), &result
);
121 AddRule(hostname
, ADDRESS_FAMILY_UNSPECIFIED
, result
);
122 AddRule(hostname
, ADDRESS_FAMILY_IPV4
, result
);
123 AddRule(hostname
, ADDRESS_FAMILY_IPV6
, result
);
126 virtual int Resolve(const std::string
& hostname
,
127 AddressFamily address_family
,
128 HostResolverFlags host_resolver_flags
,
129 AddressList
* addrlist
,
130 int* os_error
) OVERRIDE
{
131 base::AutoLock
lock(lock_
);
132 capture_list_
.push_back(ResolveKey(hostname
, address_family
));
133 ++num_requests_waiting_
;
134 requests_waiting_
.Broadcast();
135 while (!num_slots_available_
)
136 slots_available_
.Wait();
137 DCHECK_GT(num_requests_waiting_
, 0u);
138 --num_slots_available_
;
139 --num_requests_waiting_
;
140 if (rules_
.empty()) {
141 int rv
= ParseAddressList("127.0.0.1", std::string(), addrlist
);
145 ResolveKey
key(hostname
, address_family
);
146 if (rules_
.count(key
) == 0)
147 return ERR_NAME_NOT_RESOLVED
;
148 *addrlist
= rules_
[key
];
152 CaptureList
GetCaptureList() const {
155 base::AutoLock
lock(lock_
);
156 copy
= capture_list_
;
161 bool HasBlockedRequests() const {
162 base::AutoLock
lock(lock_
);
163 return num_requests_waiting_
> num_slots_available_
;
167 virtual ~MockHostResolverProc() {}
170 mutable base::Lock lock_
;
171 std::map
<ResolveKey
, AddressList
> rules_
;
172 CaptureList capture_list_
;
173 unsigned num_requests_waiting_
;
174 unsigned num_slots_available_
;
175 base::ConditionVariable requests_waiting_
;
176 base::ConditionVariable slots_available_
;
178 DISALLOW_COPY_AND_ASSIGN(MockHostResolverProc
);
181 bool AddressListContains(const AddressList
& list
, const std::string
& address
,
184 bool rv
= ParseIPLiteralToNumber(address
, &ip
);
186 return std::find(list
.begin(),
188 IPEndPoint(ip
, port
)) != list
.end();
191 // A wrapper for requests to a HostResolver.
194 // Base class of handlers to be executed on completion of requests.
196 virtual ~Handler() {}
197 virtual void Handle(Request
* request
) = 0;
200 Request(const HostResolver::RequestInfo
& info
,
201 RequestPriority priority
,
203 HostResolver
* resolver
,
210 quit_on_complete_(false),
211 result_(ERR_UNEXPECTED
),
217 list_
= AddressList();
218 result_
= resolver_
->Resolve(
222 base::Bind(&Request::OnComplete
, base::Unretained(this)),
226 EXPECT_EQ(OK
, result_
);
230 int ResolveFromCache() {
233 return resolver_
->ResolveFromCache(info_
, &list_
, BoundNetLog());
239 resolver_
->CancelRequest(handle_
);
243 const HostResolver::RequestInfo
& info() const { return info_
; }
244 size_t index() const { return index_
; }
245 const AddressList
& list() const { return list_
; }
246 int result() const { return result_
; }
247 bool completed() const { return result_
!= ERR_IO_PENDING
; }
248 bool pending() const { return handle_
!= NULL
; }
250 bool HasAddress(const std::string
& address
, int port
) const {
251 return AddressListContains(list_
, address
, port
);
254 // Returns the number of addresses in |list_|.
255 unsigned NumberOfAddresses() const {
259 bool HasOneAddress(const std::string
& address
, int port
) const {
260 return HasAddress(address
, port
) && (NumberOfAddresses() == 1u);
263 // Returns ERR_UNEXPECTED if timed out.
264 int WaitForResult() {
267 base::CancelableClosure
closure(base::MessageLoop::QuitClosure());
268 base::MessageLoop::current()->PostDelayedTask(
269 FROM_HERE
, closure
.callback(), TestTimeouts::action_max_timeout());
270 quit_on_complete_
= true;
271 base::MessageLoop::current()->Run();
272 bool did_quit
= !quit_on_complete_
;
273 quit_on_complete_
= false;
278 return ERR_UNEXPECTED
;
282 void OnComplete(int rv
) {
283 EXPECT_TRUE(pending());
284 EXPECT_EQ(ERR_IO_PENDING
, result_
);
285 EXPECT_NE(ERR_IO_PENDING
, rv
);
288 if (!list_
.empty()) {
289 EXPECT_EQ(OK
, result_
);
290 EXPECT_EQ(info_
.port(), list_
.front().port());
293 handler_
->Handle(this);
294 if (quit_on_complete_
) {
295 base::MessageLoop::current()->Quit();
296 quit_on_complete_
= false;
300 HostResolver::RequestInfo info_
;
301 RequestPriority priority_
;
303 HostResolver
* resolver_
;
305 bool quit_on_complete_
;
309 HostResolver::RequestHandle handle_
;
311 DISALLOW_COPY_AND_ASSIGN(Request
);
314 // Using LookupAttemptHostResolverProc simulate very long lookups, and control
315 // which attempt resolves the host.
316 class LookupAttemptHostResolverProc
: public HostResolverProc
{
318 LookupAttemptHostResolverProc(HostResolverProc
* previous
,
319 int attempt_number_to_resolve
,
321 : HostResolverProc(previous
),
322 attempt_number_to_resolve_(attempt_number_to_resolve
),
323 current_attempt_number_(0),
324 total_attempts_(total_attempts
),
325 total_attempts_resolved_(0),
326 resolved_attempt_number_(0),
330 // Test harness will wait for all attempts to finish before checking the
332 void WaitForAllAttemptsToFinish(const base::TimeDelta
& wait_time
) {
333 base::TimeTicks end_time
= base::TimeTicks::Now() + wait_time
;
335 base::AutoLock
auto_lock(lock_
);
336 while (total_attempts_resolved_
!= total_attempts_
&&
337 base::TimeTicks::Now() < end_time
) {
338 all_done_
.TimedWait(end_time
- base::TimeTicks::Now());
343 // All attempts will wait for an attempt to resolve the host.
344 void WaitForAnAttemptToComplete() {
345 base::TimeDelta wait_time
= base::TimeDelta::FromSeconds(60);
346 base::TimeTicks end_time
= base::TimeTicks::Now() + wait_time
;
348 base::AutoLock
auto_lock(lock_
);
349 while (resolved_attempt_number_
== 0 && base::TimeTicks::Now() < end_time
)
350 all_done_
.TimedWait(end_time
- base::TimeTicks::Now());
352 all_done_
.Broadcast(); // Tell all waiting attempts to proceed.
355 // Returns the number of attempts that have finished the Resolve() method.
356 int total_attempts_resolved() { return total_attempts_resolved_
; }
358 // Returns the first attempt that that has resolved the host.
359 int resolved_attempt_number() { return resolved_attempt_number_
; }
361 // HostResolverProc methods.
362 virtual int Resolve(const std::string
& host
,
363 AddressFamily address_family
,
364 HostResolverFlags host_resolver_flags
,
365 AddressList
* addrlist
,
366 int* os_error
) OVERRIDE
{
367 bool wait_for_right_attempt_to_complete
= true;
369 base::AutoLock
auto_lock(lock_
);
370 ++current_attempt_number_
;
371 if (current_attempt_number_
== attempt_number_to_resolve_
) {
372 resolved_attempt_number_
= current_attempt_number_
;
373 wait_for_right_attempt_to_complete
= false;
377 if (wait_for_right_attempt_to_complete
)
378 // Wait for the attempt_number_to_resolve_ attempt to resolve.
379 WaitForAnAttemptToComplete();
381 int result
= ResolveUsingPrevious(host
, address_family
, host_resolver_flags
,
385 base::AutoLock
auto_lock(lock_
);
386 ++total_attempts_resolved_
;
389 all_done_
.Broadcast(); // Tell all attempts to proceed.
391 // Since any negative number is considered a network error, with -1 having
392 // special meaning (ERR_IO_PENDING). We could return the attempt that has
393 // resolved the host as a negative number. For example, if attempt number 3
394 // resolves the host, then this method returns -4.
396 return -1 - resolved_attempt_number_
;
402 virtual ~LookupAttemptHostResolverProc() {}
405 int attempt_number_to_resolve_
;
406 int current_attempt_number_
; // Incremented whenever Resolve is called.
408 int total_attempts_resolved_
;
409 int resolved_attempt_number_
;
411 // All attempts wait for right attempt to be resolve.
413 base::ConditionVariable all_done_
;
418 class HostResolverImplTest
: public testing::Test
{
420 static const int kDefaultPort
= 80;
422 HostResolverImplTest() : proc_(new MockHostResolverProc()) {}
424 void CreateResolver() {
425 CreateResolverWithLimitsAndParams(DefaultLimits(),
426 DefaultParams(proc_
.get()));
429 // This HostResolverImpl will only allow 1 outstanding resolve at a time and
430 // perform no retries.
431 void CreateSerialResolver() {
432 HostResolverImpl::ProcTaskParams params
= DefaultParams(proc_
.get());
433 params
.max_retry_attempts
= 0u;
434 PrioritizedDispatcher::Limits
limits(NUM_PRIORITIES
, 1);
435 CreateResolverWithLimitsAndParams(limits
, params
);
439 // A Request::Handler which is a proxy to the HostResolverImplTest fixture.
440 struct Handler
: public Request::Handler
{
441 virtual ~Handler() {}
443 // Proxy functions so that classes derived from Handler can access them.
444 Request
* CreateRequest(const HostResolver::RequestInfo
& info
,
445 RequestPriority priority
) {
446 return test
->CreateRequest(info
, priority
);
448 Request
* CreateRequest(const std::string
& hostname
, int port
) {
449 return test
->CreateRequest(hostname
, port
);
451 Request
* CreateRequest(const std::string
& hostname
) {
452 return test
->CreateRequest(hostname
);
454 ScopedVector
<Request
>& requests() { return test
->requests_
; }
456 void DeleteResolver() { test
->resolver_
.reset(); }
458 HostResolverImplTest
* test
;
461 // testing::Test implementation:
462 virtual void SetUp() OVERRIDE
{
466 virtual void TearDown() OVERRIDE
{
468 EXPECT_EQ(0u, resolver_
->num_running_dispatcher_jobs_for_tests());
469 EXPECT_FALSE(proc_
->HasBlockedRequests());
472 virtual void CreateResolverWithLimitsAndParams(
473 const PrioritizedDispatcher::Limits
& limits
,
474 const HostResolverImpl::ProcTaskParams
& params
) {
475 resolver_
.reset(new HostResolverImpl(HostCache::CreateDefaultCache(),
476 limits
, params
, NULL
));
479 // The Request will not be made until a call to |Resolve()|, and the Job will
480 // not start until released by |proc_->SignalXXX|.
481 Request
* CreateRequest(const HostResolver::RequestInfo
& info
,
482 RequestPriority priority
) {
483 Request
* req
= new Request(
484 info
, priority
, requests_
.size(), resolver_
.get(), handler_
.get());
485 requests_
.push_back(req
);
489 Request
* CreateRequest(const std::string
& hostname
,
491 RequestPriority priority
,
492 AddressFamily family
) {
493 HostResolver::RequestInfo
info(HostPortPair(hostname
, port
));
494 info
.set_address_family(family
);
495 return CreateRequest(info
, priority
);
498 Request
* CreateRequest(const std::string
& hostname
,
500 RequestPriority priority
) {
501 return CreateRequest(hostname
, port
, priority
, ADDRESS_FAMILY_UNSPECIFIED
);
504 Request
* CreateRequest(const std::string
& hostname
, int port
) {
505 return CreateRequest(hostname
, port
, MEDIUM
);
508 Request
* CreateRequest(const std::string
& hostname
) {
509 return CreateRequest(hostname
, kDefaultPort
);
512 void set_handler(Handler
* handler
) {
513 handler_
.reset(handler
);
514 handler_
->test
= this;
517 // Friendship is not inherited, so use proxies to access those.
518 size_t num_running_dispatcher_jobs() const {
519 DCHECK(resolver_
.get());
520 return resolver_
->num_running_dispatcher_jobs_for_tests();
523 void set_fallback_to_proctask(bool fallback_to_proctask
) {
524 DCHECK(resolver_
.get());
525 resolver_
->fallback_to_proctask_
= fallback_to_proctask
;
528 static unsigned maximum_dns_failures() {
529 return HostResolverImpl::kMaximumDnsFailures
;
532 scoped_refptr
<MockHostResolverProc
> proc_
;
533 scoped_ptr
<HostResolverImpl
> resolver_
;
534 ScopedVector
<Request
> requests_
;
536 scoped_ptr
<Handler
> handler_
;
539 TEST_F(HostResolverImplTest
, AsynchronousLookup
) {
540 proc_
->AddRuleForAllFamilies("just.testing", "192.168.1.42");
541 proc_
->SignalMultiple(1u);
543 Request
* req
= CreateRequest("just.testing", 80);
544 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
545 EXPECT_EQ(OK
, req
->WaitForResult());
547 EXPECT_TRUE(req
->HasOneAddress("192.168.1.42", 80));
549 EXPECT_EQ("just.testing", proc_
->GetCaptureList()[0].hostname
);
552 TEST_F(HostResolverImplTest
, EmptyListMeansNameNotResolved
) {
553 proc_
->AddRuleForAllFamilies("just.testing", "");
554 proc_
->SignalMultiple(1u);
556 Request
* req
= CreateRequest("just.testing", 80);
557 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
558 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req
->WaitForResult());
559 EXPECT_EQ(0u, req
->NumberOfAddresses());
560 EXPECT_EQ("just.testing", proc_
->GetCaptureList()[0].hostname
);
563 TEST_F(HostResolverImplTest
, FailedAsynchronousLookup
) {
564 proc_
->AddRuleForAllFamilies(std::string(),
565 "0.0.0.0"); // Default to failures.
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());
572 EXPECT_EQ("just.testing", proc_
->GetCaptureList()[0].hostname
);
574 // Also test that the error is not cached.
575 EXPECT_EQ(ERR_DNS_CACHE_MISS
, req
->ResolveFromCache());
578 TEST_F(HostResolverImplTest
, AbortedAsynchronousLookup
) {
579 Request
* req0
= CreateRequest("just.testing", 80);
580 EXPECT_EQ(ERR_IO_PENDING
, req0
->Resolve());
582 EXPECT_TRUE(proc_
->WaitFor(1u));
584 // Resolver is destroyed while job is running on WorkerPool.
589 // To ensure there was no spurious callback, complete with a new resolver.
591 Request
* req1
= CreateRequest("just.testing", 80);
592 EXPECT_EQ(ERR_IO_PENDING
, req1
->Resolve());
594 proc_
->SignalMultiple(2u);
596 EXPECT_EQ(OK
, req1
->WaitForResult());
598 // This request was canceled.
599 EXPECT_FALSE(req0
->completed());
602 #if defined(THREAD_SANITIZER)
603 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
604 #define MAYBE_NumericIPv4Address DISABLED_NumericIPv4Address
606 #define MAYBE_NumericIPv4Address NumericIPv4Address
608 TEST_F(HostResolverImplTest
, MAYBE_NumericIPv4Address
) {
609 // Stevens says dotted quads with AI_UNSPEC resolve to a single sockaddr_in.
610 Request
* req
= CreateRequest("127.1.2.3", 5555);
611 EXPECT_EQ(OK
, req
->Resolve());
613 EXPECT_TRUE(req
->HasOneAddress("127.1.2.3", 5555));
616 #if defined(THREAD_SANITIZER)
617 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
618 #define MAYBE_NumericIPv6Address DISABLED_NumericIPv6Address
620 #define MAYBE_NumericIPv6Address NumericIPv6Address
622 TEST_F(HostResolverImplTest
, MAYBE_NumericIPv6Address
) {
623 // Resolve a plain IPv6 address. Don't worry about [brackets], because
624 // the caller should have removed them.
625 Request
* req
= CreateRequest("2001:db8::1", 5555);
626 EXPECT_EQ(OK
, req
->Resolve());
628 EXPECT_TRUE(req
->HasOneAddress("2001:db8::1", 5555));
631 #if defined(THREAD_SANITIZER)
632 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
633 #define MAYBE_EmptyHost DISABLED_EmptyHost
635 #define MAYBE_EmptyHost EmptyHost
637 TEST_F(HostResolverImplTest
, MAYBE_EmptyHost
) {
638 Request
* req
= CreateRequest(std::string(), 5555);
639 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req
->Resolve());
642 #if defined(THREAD_SANITIZER)
643 // There's a data race in this test that may lead to use-after-free.
644 // If the test starts to crash without ThreadSanitizer it needs to be disabled
645 // globally. See http://crbug.com/268946 (stacks for this test in
646 // crbug.com/333567).
647 #define MAYBE_EmptyDotsHost DISABLED_EmptyDotsHost
649 #define MAYBE_EmptyDotsHost EmptyDotsHost
651 TEST_F(HostResolverImplTest
, MAYBE_EmptyDotsHost
) {
652 for (int i
= 0; i
< 16; ++i
) {
653 Request
* req
= CreateRequest(std::string(i
, '.'), 5555);
654 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req
->Resolve());
658 #if defined(THREAD_SANITIZER)
659 // There's a data race in this test that may lead to use-after-free.
660 // If the test starts to crash without ThreadSanitizer it needs to be disabled
661 // globally. See http://crbug.com/268946.
662 #define MAYBE_LongHost DISABLED_LongHost
664 #define MAYBE_LongHost LongHost
666 TEST_F(HostResolverImplTest
, MAYBE_LongHost
) {
667 Request
* req
= CreateRequest(std::string(4097, 'a'), 5555);
668 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req
->Resolve());
671 TEST_F(HostResolverImplTest
, DeDupeRequests
) {
672 // Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is
673 // blocked, these should all pile up until we signal it.
674 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80)->Resolve());
675 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 80)->Resolve());
676 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 81)->Resolve());
677 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 82)->Resolve());
678 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 83)->Resolve());
680 proc_
->SignalMultiple(2u); // One for "a", one for "b".
682 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
683 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
687 TEST_F(HostResolverImplTest
, CancelMultipleRequests
) {
688 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80)->Resolve());
689 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 80)->Resolve());
690 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 81)->Resolve());
691 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 82)->Resolve());
692 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 83)->Resolve());
694 // Cancel everything except request for ("a", 82).
695 requests_
[0]->Cancel();
696 requests_
[1]->Cancel();
697 requests_
[2]->Cancel();
698 requests_
[4]->Cancel();
700 proc_
->SignalMultiple(2u); // One for "a", one for "b".
702 EXPECT_EQ(OK
, requests_
[3]->WaitForResult());
705 TEST_F(HostResolverImplTest
, CanceledRequestsReleaseJobSlots
) {
706 // Fill up the dispatcher and queue.
707 for (unsigned i
= 0; i
< kMaxJobs
+ 1; ++i
) {
708 std::string hostname
= "a_";
709 hostname
[1] = 'a' + i
;
710 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(hostname
, 80)->Resolve());
711 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(hostname
, 81)->Resolve());
714 EXPECT_TRUE(proc_
->WaitFor(kMaxJobs
));
716 // Cancel all but last two.
717 for (unsigned i
= 0; i
< requests_
.size() - 2; ++i
) {
718 requests_
[i
]->Cancel();
721 EXPECT_TRUE(proc_
->WaitFor(kMaxJobs
+ 1));
725 size_t num_requests
= requests_
.size();
726 EXPECT_EQ(OK
, requests_
[num_requests
- 1]->WaitForResult());
727 EXPECT_EQ(OK
, requests_
[num_requests
- 2]->result());
730 TEST_F(HostResolverImplTest
, CancelWithinCallback
) {
731 struct MyHandler
: public Handler
{
732 virtual void Handle(Request
* req
) OVERRIDE
{
733 // Port 80 is the first request that the callback will be invoked for.
734 // While we are executing within that callback, cancel the other requests
735 // in the job and start another request.
736 if (req
->index() == 0) {
737 // Once "a:80" completes, it will cancel "a:81" and "a:82".
738 requests()[1]->Cancel();
739 requests()[2]->Cancel();
743 set_handler(new MyHandler());
745 for (size_t i
= 0; i
< 4; ++i
) {
746 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80 + i
)->Resolve()) << i
;
749 proc_
->SignalMultiple(2u); // One for "a". One for "finalrequest".
751 EXPECT_EQ(OK
, requests_
[0]->WaitForResult());
753 Request
* final_request
= CreateRequest("finalrequest", 70);
754 EXPECT_EQ(ERR_IO_PENDING
, final_request
->Resolve());
755 EXPECT_EQ(OK
, final_request
->WaitForResult());
756 EXPECT_TRUE(requests_
[3]->completed());
759 TEST_F(HostResolverImplTest
, DeleteWithinCallback
) {
760 struct MyHandler
: public Handler
{
761 virtual void Handle(Request
* req
) OVERRIDE
{
762 EXPECT_EQ("a", req
->info().hostname());
763 EXPECT_EQ(80, req
->info().port());
767 // Quit after returning from OnCompleted (to give it a chance at
768 // incorrectly running the cancelled tasks).
769 base::MessageLoop::current()->PostTask(FROM_HERE
,
770 base::MessageLoop::QuitClosure());
773 set_handler(new MyHandler());
775 for (size_t i
= 0; i
< 4; ++i
) {
776 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80 + i
)->Resolve()) << i
;
779 proc_
->SignalMultiple(1u); // One for "a".
781 // |MyHandler| will send quit message once all the requests have finished.
782 base::MessageLoop::current()->Run();
785 TEST_F(HostResolverImplTest
, DeleteWithinAbortedCallback
) {
786 struct MyHandler
: public Handler
{
787 virtual void Handle(Request
* req
) OVERRIDE
{
788 EXPECT_EQ("a", req
->info().hostname());
789 EXPECT_EQ(80, req
->info().port());
793 // Quit after returning from OnCompleted (to give it a chance at
794 // incorrectly running the cancelled tasks).
795 base::MessageLoop::current()->PostTask(FROM_HERE
,
796 base::MessageLoop::QuitClosure());
799 set_handler(new MyHandler());
801 // This test assumes that the Jobs will be Aborted in order ["a", "b"]
802 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80)->Resolve());
803 // HostResolverImpl will be deleted before later Requests can complete.
804 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 81)->Resolve());
805 // Job for 'b' will be aborted before it can complete.
806 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 82)->Resolve());
807 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 83)->Resolve());
809 EXPECT_TRUE(proc_
->WaitFor(1u));
811 // Triggering an IP address change.
812 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
814 // |MyHandler| will send quit message once all the requests have finished.
815 base::MessageLoop::current()->Run();
817 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[0]->result());
818 EXPECT_EQ(ERR_IO_PENDING
, requests_
[1]->result());
819 EXPECT_EQ(ERR_IO_PENDING
, requests_
[2]->result());
820 EXPECT_EQ(ERR_IO_PENDING
, requests_
[3]->result());
822 proc_
->SignalMultiple(requests_
.size());
825 TEST_F(HostResolverImplTest
, StartWithinCallback
) {
826 struct MyHandler
: public Handler
{
827 virtual void Handle(Request
* req
) OVERRIDE
{
828 if (req
->index() == 0) {
829 // On completing the first request, start another request for "a".
830 // Since caching is disabled, this will result in another async request.
831 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 70)->Resolve());
835 set_handler(new MyHandler());
837 // Turn off caching for this host resolver.
838 resolver_
.reset(new HostResolverImpl(scoped_ptr
<HostCache
>(),
840 DefaultParams(proc_
.get()),
843 for (size_t i
= 0; i
< 4; ++i
) {
844 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80 + i
)->Resolve()) << i
;
847 proc_
->SignalMultiple(2u); // One for "a". One for the second "a".
849 EXPECT_EQ(OK
, requests_
[0]->WaitForResult());
850 ASSERT_EQ(5u, requests_
.size());
851 EXPECT_EQ(OK
, requests_
.back()->WaitForResult());
853 EXPECT_EQ(2u, proc_
->GetCaptureList().size());
856 TEST_F(HostResolverImplTest
, BypassCache
) {
857 struct MyHandler
: public Handler
{
858 virtual void Handle(Request
* req
) OVERRIDE
{
859 if (req
->index() == 0) {
860 // On completing the first request, start another request for "a".
861 // Since caching is enabled, this should complete synchronously.
862 std::string hostname
= req
->info().hostname();
863 EXPECT_EQ(OK
, CreateRequest(hostname
, 70)->Resolve());
864 EXPECT_EQ(OK
, CreateRequest(hostname
, 75)->ResolveFromCache());
866 // Ok good. Now make sure that if we ask to bypass the cache, it can no
867 // longer service the request synchronously.
868 HostResolver::RequestInfo
info(HostPortPair(hostname
, 71));
869 info
.set_allow_cached_response(false);
870 EXPECT_EQ(ERR_IO_PENDING
,
871 CreateRequest(info
, DEFAULT_PRIORITY
)->Resolve());
872 } else if (71 == req
->info().port()) {
874 base::MessageLoop::current()->Quit();
876 FAIL() << "Unexpected request";
880 set_handler(new MyHandler());
882 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80)->Resolve());
883 proc_
->SignalMultiple(3u); // Only need two, but be generous.
885 // |verifier| will send quit message once all the requests have finished.
886 base::MessageLoop::current()->Run();
887 EXPECT_EQ(2u, proc_
->GetCaptureList().size());
890 // Test that IP address changes flush the cache.
891 TEST_F(HostResolverImplTest
, FlushCacheOnIPAddressChange
) {
892 proc_
->SignalMultiple(2u); // One before the flush, one after.
894 Request
* req
= CreateRequest("host1", 70);
895 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
896 EXPECT_EQ(OK
, req
->WaitForResult());
898 req
= CreateRequest("host1", 75);
899 EXPECT_EQ(OK
, req
->Resolve()); // Should complete synchronously.
901 // Flush cache by triggering an IP address change.
902 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
903 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
905 // Resolve "host1" again -- this time it won't be served from cache, so it
906 // will complete asynchronously.
907 req
= CreateRequest("host1", 80);
908 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
909 EXPECT_EQ(OK
, req
->WaitForResult());
912 // Test that IP address changes send ERR_NETWORK_CHANGED to pending requests.
913 TEST_F(HostResolverImplTest
, AbortOnIPAddressChanged
) {
914 Request
* req
= CreateRequest("host1", 70);
915 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
917 EXPECT_TRUE(proc_
->WaitFor(1u));
918 // Triggering an IP address change.
919 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
920 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
923 EXPECT_EQ(ERR_NETWORK_CHANGED
, req
->WaitForResult());
924 EXPECT_EQ(0u, resolver_
->GetHostCache()->size());
927 // Obey pool constraints after IP address has changed.
928 TEST_F(HostResolverImplTest
, ObeyPoolConstraintsAfterIPAddressChange
) {
929 // Runs at most one job at a time.
930 CreateSerialResolver();
931 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a")->Resolve());
932 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b")->Resolve());
933 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("c")->Resolve());
935 EXPECT_TRUE(proc_
->WaitFor(1u));
936 // Triggering an IP address change.
937 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
938 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
939 proc_
->SignalMultiple(3u); // Let the false-start go so that we can catch it.
941 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[0]->WaitForResult());
943 EXPECT_EQ(1u, num_running_dispatcher_jobs());
945 EXPECT_FALSE(requests_
[1]->completed());
946 EXPECT_FALSE(requests_
[2]->completed());
948 EXPECT_EQ(OK
, requests_
[2]->WaitForResult());
949 EXPECT_EQ(OK
, requests_
[1]->result());
952 // Tests that a new Request made from the callback of a previously aborted one
953 // will not be aborted.
954 TEST_F(HostResolverImplTest
, AbortOnlyExistingRequestsOnIPAddressChange
) {
955 struct MyHandler
: public Handler
{
956 virtual void Handle(Request
* req
) OVERRIDE
{
957 // Start new request for a different hostname to ensure that the order
958 // of jobs in HostResolverImpl is not stable.
959 std::string hostname
;
960 if (req
->index() == 0)
962 else if (req
->index() == 1)
964 else if (req
->index() == 2)
967 return; // A request started from within MyHandler.
968 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(hostname
)->Resolve()) << hostname
;
971 set_handler(new MyHandler());
973 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("bbb")->Resolve());
974 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("eee")->Resolve());
975 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ccc")->Resolve());
977 // Wait until all are blocked;
978 EXPECT_TRUE(proc_
->WaitFor(3u));
979 // Trigger an IP address change.
980 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
981 // This should abort all running jobs.
982 base::MessageLoop::current()->RunUntilIdle();
983 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[0]->result());
984 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[1]->result());
985 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[2]->result());
986 ASSERT_EQ(6u, requests_
.size());
987 // Unblock all calls to proc.
988 proc_
->SignalMultiple(requests_
.size());
989 // Run until the re-started requests finish.
990 EXPECT_EQ(OK
, requests_
[3]->WaitForResult());
991 EXPECT_EQ(OK
, requests_
[4]->WaitForResult());
992 EXPECT_EQ(OK
, requests_
[5]->WaitForResult());
993 // Verify that results of aborted Jobs were not cached.
994 EXPECT_EQ(6u, proc_
->GetCaptureList().size());
995 EXPECT_EQ(3u, resolver_
->GetHostCache()->size());
998 // Tests that when the maximum threads is set to 1, requests are dequeued
999 // in order of priority.
1000 TEST_F(HostResolverImplTest
, HigherPriorityRequestsStartedFirst
) {
1001 CreateSerialResolver();
1003 // Note that at this point the MockHostResolverProc is blocked, so any
1004 // requests we make will not complete.
1005 CreateRequest("req0", 80, LOW
);
1006 CreateRequest("req1", 80, MEDIUM
);
1007 CreateRequest("req2", 80, MEDIUM
);
1008 CreateRequest("req3", 80, LOW
);
1009 CreateRequest("req4", 80, HIGHEST
);
1010 CreateRequest("req5", 80, LOW
);
1011 CreateRequest("req6", 80, LOW
);
1012 CreateRequest("req5", 80, HIGHEST
);
1014 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1015 EXPECT_EQ(ERR_IO_PENDING
, requests_
[i
]->Resolve()) << i
;
1018 // Unblock the resolver thread so the requests can run.
1019 proc_
->SignalMultiple(requests_
.size()); // More than needed.
1021 // Wait for all the requests to complete succesfully.
1022 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1023 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1026 // Since we have restricted to a single concurrent thread in the jobpool,
1027 // the requests should complete in order of priority (with the exception
1028 // of the first request, which gets started right away, since there is
1029 // nothing outstanding).
1030 MockHostResolverProc::CaptureList capture_list
= proc_
->GetCaptureList();
1031 ASSERT_EQ(7u, capture_list
.size());
1033 EXPECT_EQ("req0", capture_list
[0].hostname
);
1034 EXPECT_EQ("req4", capture_list
[1].hostname
);
1035 EXPECT_EQ("req5", capture_list
[2].hostname
);
1036 EXPECT_EQ("req1", capture_list
[3].hostname
);
1037 EXPECT_EQ("req2", capture_list
[4].hostname
);
1038 EXPECT_EQ("req3", capture_list
[5].hostname
);
1039 EXPECT_EQ("req6", capture_list
[6].hostname
);
1042 // Try cancelling a job which has not started yet.
1043 TEST_F(HostResolverImplTest
, CancelPendingRequest
) {
1044 CreateSerialResolver();
1046 CreateRequest("req0", 80, LOWEST
);
1047 CreateRequest("req1", 80, HIGHEST
); // Will cancel.
1048 CreateRequest("req2", 80, MEDIUM
);
1049 CreateRequest("req3", 80, LOW
);
1050 CreateRequest("req4", 80, HIGHEST
); // Will cancel.
1051 CreateRequest("req5", 80, LOWEST
); // Will cancel.
1052 CreateRequest("req6", 80, MEDIUM
);
1054 // Start all of the requests.
1055 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1056 EXPECT_EQ(ERR_IO_PENDING
, requests_
[i
]->Resolve()) << i
;
1059 // Cancel some requests
1060 requests_
[1]->Cancel();
1061 requests_
[4]->Cancel();
1062 requests_
[5]->Cancel();
1064 // Unblock the resolver thread so the requests can run.
1065 proc_
->SignalMultiple(requests_
.size()); // More than needed.
1067 // Wait for all the requests to complete succesfully.
1068 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1069 if (!requests_
[i
]->pending())
1070 continue; // Don't wait for the requests we cancelled.
1071 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1074 // Verify that they called out the the resolver proc (which runs on the
1075 // resolver thread) in the expected order.
1076 MockHostResolverProc::CaptureList capture_list
= proc_
->GetCaptureList();
1077 ASSERT_EQ(4u, capture_list
.size());
1079 EXPECT_EQ("req0", capture_list
[0].hostname
);
1080 EXPECT_EQ("req2", capture_list
[1].hostname
);
1081 EXPECT_EQ("req6", capture_list
[2].hostname
);
1082 EXPECT_EQ("req3", capture_list
[3].hostname
);
1085 // Test that when too many requests are enqueued, old ones start to be aborted.
1086 TEST_F(HostResolverImplTest
, QueueOverflow
) {
1087 CreateSerialResolver();
1089 // Allow only 3 queued jobs.
1090 const size_t kMaxPendingJobs
= 3u;
1091 resolver_
->SetMaxQueuedJobs(kMaxPendingJobs
);
1093 // Note that at this point the MockHostResolverProc is blocked, so any
1094 // requests we make will not complete.
1096 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req0", 80, LOWEST
)->Resolve());
1097 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req1", 80, HIGHEST
)->Resolve());
1098 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req2", 80, MEDIUM
)->Resolve());
1099 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req3", 80, MEDIUM
)->Resolve());
1101 // At this point, there are 3 enqueued jobs.
1102 // Insertion of subsequent requests will cause evictions
1103 // based on priority.
1105 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
,
1106 CreateRequest("req4", 80, LOW
)->Resolve()); // Evicts itself!
1108 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req5", 80, MEDIUM
)->Resolve());
1109 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
, requests_
[2]->result());
1110 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req6", 80, HIGHEST
)->Resolve());
1111 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
, requests_
[3]->result());
1112 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req7", 80, MEDIUM
)->Resolve());
1113 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
, requests_
[5]->result());
1115 // Unblock the resolver thread so the requests can run.
1116 proc_
->SignalMultiple(4u);
1118 // The rest should succeed.
1119 EXPECT_EQ(OK
, requests_
[7]->WaitForResult());
1120 EXPECT_EQ(OK
, requests_
[0]->result());
1121 EXPECT_EQ(OK
, requests_
[1]->result());
1122 EXPECT_EQ(OK
, requests_
[6]->result());
1124 // Verify that they called out the the resolver proc (which runs on the
1125 // resolver thread) in the expected order.
1126 MockHostResolverProc::CaptureList capture_list
= proc_
->GetCaptureList();
1127 ASSERT_EQ(4u, capture_list
.size());
1129 EXPECT_EQ("req0", capture_list
[0].hostname
);
1130 EXPECT_EQ("req1", capture_list
[1].hostname
);
1131 EXPECT_EQ("req6", capture_list
[2].hostname
);
1132 EXPECT_EQ("req7", capture_list
[3].hostname
);
1134 // Verify that the evicted (incomplete) requests were not cached.
1135 EXPECT_EQ(4u, resolver_
->GetHostCache()->size());
1137 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1138 EXPECT_TRUE(requests_
[i
]->completed()) << i
;
1142 // Tests that after changing the default AddressFamily to IPV4, requests
1143 // with UNSPECIFIED address family map to IPV4.
1144 TEST_F(HostResolverImplTest
, SetDefaultAddressFamily_IPv4
) {
1145 CreateSerialResolver(); // To guarantee order of resolutions.
1147 proc_
->AddRule("h1", ADDRESS_FAMILY_IPV4
, "1.0.0.1");
1148 proc_
->AddRule("h1", ADDRESS_FAMILY_IPV6
, "::2");
1150 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1152 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_UNSPECIFIED
);
1153 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_IPV4
);
1154 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_IPV6
);
1156 // Start all of the requests.
1157 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1158 EXPECT_EQ(ERR_IO_PENDING
, requests_
[i
]->Resolve()) << i
;
1161 proc_
->SignalMultiple(requests_
.size());
1163 // Wait for all the requests to complete.
1164 for (size_t i
= 0u; i
< requests_
.size(); ++i
) {
1165 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1168 // Since the requests all had the same priority and we limited the thread
1169 // count to 1, they should have completed in the same order as they were
1170 // requested. Moreover, request0 and request1 will have been serviced by
1173 MockHostResolverProc::CaptureList capture_list
= proc_
->GetCaptureList();
1174 ASSERT_EQ(2u, capture_list
.size());
1176 EXPECT_EQ("h1", capture_list
[0].hostname
);
1177 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, capture_list
[0].address_family
);
1179 EXPECT_EQ("h1", capture_list
[1].hostname
);
1180 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, capture_list
[1].address_family
);
1182 // Now check that the correct resolved IP addresses were returned.
1183 EXPECT_TRUE(requests_
[0]->HasOneAddress("1.0.0.1", 80));
1184 EXPECT_TRUE(requests_
[1]->HasOneAddress("1.0.0.1", 80));
1185 EXPECT_TRUE(requests_
[2]->HasOneAddress("::2", 80));
1188 // This is the exact same test as SetDefaultAddressFamily_IPv4, except the
1189 // default family is set to IPv6 and the family of requests is flipped where
1191 TEST_F(HostResolverImplTest
, SetDefaultAddressFamily_IPv6
) {
1192 CreateSerialResolver(); // To guarantee order of resolutions.
1194 // Don't use IPv6 replacements here since some systems don't support it.
1195 proc_
->AddRule("h1", ADDRESS_FAMILY_IPV4
, "1.0.0.1");
1196 proc_
->AddRule("h1", ADDRESS_FAMILY_IPV6
, "::2");
1198 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV6
);
1200 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_UNSPECIFIED
);
1201 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_IPV6
);
1202 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_IPV4
);
1204 // Start all of the requests.
1205 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1206 EXPECT_EQ(ERR_IO_PENDING
, requests_
[i
]->Resolve()) << i
;
1209 proc_
->SignalMultiple(requests_
.size());
1211 // Wait for all the requests to complete.
1212 for (size_t i
= 0u; i
< requests_
.size(); ++i
) {
1213 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1216 // Since the requests all had the same priority and we limited the thread
1217 // count to 1, they should have completed in the same order as they were
1218 // requested. Moreover, request0 and request1 will have been serviced by
1221 MockHostResolverProc::CaptureList capture_list
= proc_
->GetCaptureList();
1222 ASSERT_EQ(2u, capture_list
.size());
1224 EXPECT_EQ("h1", capture_list
[0].hostname
);
1225 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, capture_list
[0].address_family
);
1227 EXPECT_EQ("h1", capture_list
[1].hostname
);
1228 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, capture_list
[1].address_family
);
1230 // Now check that the correct resolved IP addresses were returned.
1231 EXPECT_TRUE(requests_
[0]->HasOneAddress("::2", 80));
1232 EXPECT_TRUE(requests_
[1]->HasOneAddress("::2", 80));
1233 EXPECT_TRUE(requests_
[2]->HasOneAddress("1.0.0.1", 80));
1236 TEST_F(HostResolverImplTest
, ResolveFromCache
) {
1237 proc_
->AddRuleForAllFamilies("just.testing", "192.168.1.42");
1238 proc_
->SignalMultiple(1u); // Need only one.
1240 HostResolver::RequestInfo
info(HostPortPair("just.testing", 80));
1242 // First hit will miss the cache.
1243 EXPECT_EQ(ERR_DNS_CACHE_MISS
,
1244 CreateRequest(info
, DEFAULT_PRIORITY
)->ResolveFromCache());
1246 // This time, we fetch normally.
1247 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(info
, DEFAULT_PRIORITY
)->Resolve());
1248 EXPECT_EQ(OK
, requests_
[1]->WaitForResult());
1250 // Now we should be able to fetch from the cache.
1251 EXPECT_EQ(OK
, CreateRequest(info
, DEFAULT_PRIORITY
)->ResolveFromCache());
1252 EXPECT_TRUE(requests_
[2]->HasOneAddress("192.168.1.42", 80));
1255 // Test the retry attempts simulating host resolver proc that takes too long.
1256 TEST_F(HostResolverImplTest
, MultipleAttempts
) {
1257 // Total number of attempts would be 3 and we want the 3rd attempt to resolve
1258 // the host. First and second attempt will be forced to sleep until they get
1259 // word that a resolution has completed. The 3rd resolution attempt will try
1260 // to get done ASAP, and won't sleep..
1261 int kAttemptNumberToResolve
= 3;
1262 int kTotalAttempts
= 3;
1264 scoped_refptr
<LookupAttemptHostResolverProc
> resolver_proc(
1265 new LookupAttemptHostResolverProc(
1266 NULL
, kAttemptNumberToResolve
, kTotalAttempts
));
1268 HostResolverImpl::ProcTaskParams params
= DefaultParams(resolver_proc
.get());
1270 // Specify smaller interval for unresponsive_delay_ for HostResolverImpl so
1271 // that unit test runs faster. For example, this test finishes in 1.5 secs
1273 params
.unresponsive_delay
= base::TimeDelta::FromMilliseconds(500);
1276 new HostResolverImpl(HostCache::CreateDefaultCache(),
1282 HostResolver::RequestInfo
info(HostPortPair("host1", 70));
1283 Request
* req
= CreateRequest(info
, DEFAULT_PRIORITY
);
1284 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1286 // Resolve returns -4 to indicate that 3rd attempt has resolved the host.
1287 EXPECT_EQ(-4, req
->WaitForResult());
1289 resolver_proc
->WaitForAllAttemptsToFinish(
1290 base::TimeDelta::FromMilliseconds(60000));
1291 base::MessageLoop::current()->RunUntilIdle();
1293 EXPECT_EQ(resolver_proc
->total_attempts_resolved(), kTotalAttempts
);
1294 EXPECT_EQ(resolver_proc
->resolved_attempt_number(), kAttemptNumberToResolve
);
1297 DnsConfig
CreateValidDnsConfig() {
1298 IPAddressNumber dns_ip
;
1299 bool rv
= ParseIPLiteralToNumber("192.168.1.0", &dns_ip
);
1303 config
.nameservers
.push_back(IPEndPoint(dns_ip
, dns_protocol::kDefaultPort
));
1304 EXPECT_TRUE(config
.IsValid());
1308 // Specialized fixture for tests of DnsTask.
1309 class HostResolverImplDnsTest
: public HostResolverImplTest
{
1311 HostResolverImplDnsTest() : dns_client_(NULL
) {}
1314 // testing::Test implementation:
1315 virtual void SetUp() OVERRIDE
{
1316 AddDnsRule("nx", dns_protocol::kTypeA
, MockDnsClientRule::FAIL
, false);
1317 AddDnsRule("nx", dns_protocol::kTypeAAAA
, MockDnsClientRule::FAIL
, false);
1318 AddDnsRule("ok", dns_protocol::kTypeA
, MockDnsClientRule::OK
, false);
1319 AddDnsRule("ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::OK
, false);
1320 AddDnsRule("4ok", dns_protocol::kTypeA
, MockDnsClientRule::OK
, false);
1321 AddDnsRule("4ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::EMPTY
, false);
1322 AddDnsRule("6ok", dns_protocol::kTypeA
, MockDnsClientRule::EMPTY
, false);
1323 AddDnsRule("6ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::OK
, false);
1324 AddDnsRule("4nx", dns_protocol::kTypeA
, MockDnsClientRule::OK
, false);
1325 AddDnsRule("4nx", dns_protocol::kTypeAAAA
, MockDnsClientRule::FAIL
, false);
1326 AddDnsRule("empty", dns_protocol::kTypeA
, MockDnsClientRule::EMPTY
, false);
1327 AddDnsRule("empty", dns_protocol::kTypeAAAA
, MockDnsClientRule::EMPTY
,
1330 AddDnsRule("slow_nx", dns_protocol::kTypeA
, MockDnsClientRule::FAIL
, true);
1331 AddDnsRule("slow_nx", dns_protocol::kTypeAAAA
, MockDnsClientRule::FAIL
,
1334 AddDnsRule("4slow_ok", dns_protocol::kTypeA
, MockDnsClientRule::OK
, true);
1335 AddDnsRule("4slow_ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::OK
,
1337 AddDnsRule("6slow_ok", dns_protocol::kTypeA
, MockDnsClientRule::OK
, false);
1338 AddDnsRule("6slow_ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::OK
,
1340 AddDnsRule("4slow_4ok", dns_protocol::kTypeA
, MockDnsClientRule::OK
, true);
1341 AddDnsRule("4slow_4ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::EMPTY
,
1343 AddDnsRule("4slow_4timeout", dns_protocol::kTypeA
,
1344 MockDnsClientRule::TIMEOUT
, true);
1345 AddDnsRule("4slow_4timeout", dns_protocol::kTypeAAAA
, MockDnsClientRule::OK
,
1347 AddDnsRule("4slow_6timeout", dns_protocol::kTypeA
,
1348 MockDnsClientRule::OK
, true);
1349 AddDnsRule("4slow_6timeout", dns_protocol::kTypeAAAA
,
1350 MockDnsClientRule::TIMEOUT
, false);
1354 // HostResolverImplTest implementation:
1355 virtual void CreateResolverWithLimitsAndParams(
1356 const PrioritizedDispatcher::Limits
& limits
,
1357 const HostResolverImpl::ProcTaskParams
& params
) OVERRIDE
{
1358 resolver_
.reset(new HostResolverImpl(HostCache::CreateDefaultCache(),
1362 // Disable IPv6 support probing.
1363 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1364 dns_client_
= new MockDnsClient(DnsConfig(), dns_rules_
);
1365 resolver_
->SetDnsClient(scoped_ptr
<DnsClient
>(dns_client_
));
1368 // Adds a rule to |dns_rules_|. Must be followed by |CreateResolver| to apply.
1369 void AddDnsRule(const std::string
& prefix
,
1371 MockDnsClientRule::Result result
,
1373 dns_rules_
.push_back(MockDnsClientRule(prefix
, qtype
, result
, delay
));
1376 void ChangeDnsConfig(const DnsConfig
& config
) {
1377 NetworkChangeNotifier::SetDnsConfig(config
);
1378 // Notification is delivered asynchronously.
1379 base::MessageLoop::current()->RunUntilIdle();
1382 MockDnsClientRuleList dns_rules_
;
1383 // Owned by |resolver_|.
1384 MockDnsClient
* dns_client_
;
1387 // TODO(szym): Test AbortAllInProgressJobs due to DnsConfig change.
1389 // TODO(cbentzel): Test a mix of requests with different HostResolverFlags.
1391 // Test successful and fallback resolutions in HostResolverImpl::DnsTask.
1392 TEST_F(HostResolverImplDnsTest
, DnsTask
) {
1393 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1395 proc_
->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
1396 // All other hostnames will fail in proc_.
1398 // Initially there is no config, so client should not be invoked.
1399 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok_fail", 80)->Resolve());
1400 proc_
->SignalMultiple(requests_
.size());
1402 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[0]->WaitForResult());
1404 ChangeDnsConfig(CreateValidDnsConfig());
1406 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok_fail", 80)->Resolve());
1407 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_fail", 80)->Resolve());
1408 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_succeed", 80)->Resolve());
1410 proc_
->SignalMultiple(requests_
.size());
1412 for (size_t i
= 1; i
< requests_
.size(); ++i
)
1413 EXPECT_NE(ERR_UNEXPECTED
, requests_
[i
]->WaitForResult()) << i
;
1415 EXPECT_EQ(OK
, requests_
[1]->result());
1416 // Resolved by MockDnsClient.
1417 EXPECT_TRUE(requests_
[1]->HasOneAddress("127.0.0.1", 80));
1418 // Fallback to ProcTask.
1419 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[2]->result());
1420 EXPECT_EQ(OK
, requests_
[3]->result());
1421 EXPECT_TRUE(requests_
[3]->HasOneAddress("192.168.1.102", 80));
1424 // Test successful and failing resolutions in HostResolverImpl::DnsTask when
1425 // fallback to ProcTask is disabled.
1426 TEST_F(HostResolverImplDnsTest
, NoFallbackToProcTask
) {
1427 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1428 set_fallback_to_proctask(false);
1430 proc_
->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
1431 // All other hostnames will fail in proc_.
1433 // Set empty DnsConfig.
1434 ChangeDnsConfig(DnsConfig());
1435 // Initially there is no config, so client should not be invoked.
1436 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok_fail", 80)->Resolve());
1437 // There is no config, so fallback to ProcTask must work.
1438 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_succeed", 80)->Resolve());
1439 proc_
->SignalMultiple(requests_
.size());
1441 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[0]->WaitForResult());
1442 EXPECT_EQ(OK
, requests_
[1]->WaitForResult());
1443 EXPECT_TRUE(requests_
[1]->HasOneAddress("192.168.1.102", 80));
1445 ChangeDnsConfig(CreateValidDnsConfig());
1447 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok_abort", 80)->Resolve());
1448 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_abort", 80)->Resolve());
1450 // Simulate the case when the preference or policy has disabled the DNS client
1451 // causing AbortDnsTasks.
1452 resolver_
->SetDnsClient(
1453 scoped_ptr
<DnsClient
>(new MockDnsClient(DnsConfig(), dns_rules_
)));
1454 ChangeDnsConfig(CreateValidDnsConfig());
1456 // First request is resolved by MockDnsClient, others should fail due to
1457 // disabled fallback to ProcTask.
1458 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok_fail", 80)->Resolve());
1459 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_fail", 80)->Resolve());
1460 proc_
->SignalMultiple(requests_
.size());
1462 // Aborted due to Network Change.
1463 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[2]->WaitForResult());
1464 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[3]->WaitForResult());
1465 // Resolved by MockDnsClient.
1466 EXPECT_EQ(OK
, requests_
[4]->WaitForResult());
1467 EXPECT_TRUE(requests_
[4]->HasOneAddress("127.0.0.1", 80));
1468 // Fallback to ProcTask is disabled.
1469 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[5]->WaitForResult());
1472 // Test behavior of OnDnsTaskFailure when Job is aborted.
1473 TEST_F(HostResolverImplDnsTest
, OnDnsTaskFailureAbortedJob
) {
1474 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1475 ChangeDnsConfig(CreateValidDnsConfig());
1476 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_abort", 80)->Resolve());
1477 // Abort all jobs here.
1479 proc_
->SignalMultiple(requests_
.size());
1480 // Run to completion.
1481 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1482 // It shouldn't crash during OnDnsTaskFailure callbacks.
1483 EXPECT_EQ(ERR_IO_PENDING
, requests_
[0]->result());
1485 // Repeat test with Fallback to ProcTask disabled
1486 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1487 set_fallback_to_proctask(false);
1488 ChangeDnsConfig(CreateValidDnsConfig());
1489 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_abort", 80)->Resolve());
1490 // Abort all jobs here.
1492 // Run to completion.
1493 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1494 // It shouldn't crash during OnDnsTaskFailure callbacks.
1495 EXPECT_EQ(ERR_IO_PENDING
, requests_
[1]->result());
1498 TEST_F(HostResolverImplDnsTest
, DnsTaskUnspec
) {
1499 ChangeDnsConfig(CreateValidDnsConfig());
1501 proc_
->AddRuleForAllFamilies("4nx", "192.168.1.101");
1502 // All other hostnames will fail in proc_.
1504 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1505 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4ok", 80)->Resolve());
1506 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("6ok", 80)->Resolve());
1507 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4nx", 80)->Resolve());
1509 proc_
->SignalMultiple(requests_
.size());
1511 for (size_t i
= 0; i
< requests_
.size(); ++i
)
1512 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1514 EXPECT_EQ(2u, requests_
[0]->NumberOfAddresses());
1515 EXPECT_TRUE(requests_
[0]->HasAddress("127.0.0.1", 80));
1516 EXPECT_TRUE(requests_
[0]->HasAddress("::1", 80));
1517 EXPECT_EQ(1u, requests_
[1]->NumberOfAddresses());
1518 EXPECT_TRUE(requests_
[1]->HasAddress("127.0.0.1", 80));
1519 EXPECT_EQ(1u, requests_
[2]->NumberOfAddresses());
1520 EXPECT_TRUE(requests_
[2]->HasAddress("::1", 80));
1521 EXPECT_EQ(1u, requests_
[3]->NumberOfAddresses());
1522 EXPECT_TRUE(requests_
[3]->HasAddress("192.168.1.101", 80));
1525 TEST_F(HostResolverImplDnsTest
, ServeFromHosts
) {
1526 // Initially, use empty HOSTS file.
1527 DnsConfig config
= CreateValidDnsConfig();
1528 ChangeDnsConfig(config
);
1530 proc_
->AddRuleForAllFamilies(std::string(),
1531 std::string()); // Default to failures.
1532 proc_
->SignalMultiple(1u); // For the first request which misses.
1534 Request
* req0
= CreateRequest("nx_ipv4", 80);
1535 EXPECT_EQ(ERR_IO_PENDING
, req0
->Resolve());
1536 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req0
->WaitForResult());
1538 IPAddressNumber local_ipv4
, local_ipv6
;
1539 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4
));
1540 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6
));
1543 hosts
[DnsHostsKey("nx_ipv4", ADDRESS_FAMILY_IPV4
)] = local_ipv4
;
1544 hosts
[DnsHostsKey("nx_ipv6", ADDRESS_FAMILY_IPV6
)] = local_ipv6
;
1545 hosts
[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV4
)] = local_ipv4
;
1546 hosts
[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV6
)] = local_ipv6
;
1548 // Update HOSTS file.
1549 config
.hosts
= hosts
;
1550 ChangeDnsConfig(config
);
1552 Request
* req1
= CreateRequest("nx_ipv4", 80);
1553 EXPECT_EQ(OK
, req1
->Resolve());
1554 EXPECT_TRUE(req1
->HasOneAddress("127.0.0.1", 80));
1556 Request
* req2
= CreateRequest("nx_ipv6", 80);
1557 EXPECT_EQ(OK
, req2
->Resolve());
1558 EXPECT_TRUE(req2
->HasOneAddress("::1", 80));
1560 Request
* req3
= CreateRequest("nx_both", 80);
1561 EXPECT_EQ(OK
, req3
->Resolve());
1562 EXPECT_TRUE(req3
->HasAddress("127.0.0.1", 80) &&
1563 req3
->HasAddress("::1", 80));
1565 // Requests with specified AddressFamily.
1566 Request
* req4
= CreateRequest("nx_ipv4", 80, MEDIUM
, ADDRESS_FAMILY_IPV4
);
1567 EXPECT_EQ(OK
, req4
->Resolve());
1568 EXPECT_TRUE(req4
->HasOneAddress("127.0.0.1", 80));
1570 Request
* req5
= CreateRequest("nx_ipv6", 80, MEDIUM
, ADDRESS_FAMILY_IPV6
);
1571 EXPECT_EQ(OK
, req5
->Resolve());
1572 EXPECT_TRUE(req5
->HasOneAddress("::1", 80));
1574 // Request with upper case.
1575 Request
* req6
= CreateRequest("nx_IPV4", 80);
1576 EXPECT_EQ(OK
, req6
->Resolve());
1577 EXPECT_TRUE(req6
->HasOneAddress("127.0.0.1", 80));
1580 TEST_F(HostResolverImplDnsTest
, BypassDnsTask
) {
1581 ChangeDnsConfig(CreateValidDnsConfig());
1583 proc_
->AddRuleForAllFamilies(std::string(),
1584 std::string()); // Default to failures.
1586 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok.local", 80)->Resolve());
1587 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok.local.", 80)->Resolve());
1588 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("oklocal", 80)->Resolve());
1589 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("oklocal.", 80)->Resolve());
1590 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1592 proc_
->SignalMultiple(requests_
.size());
1594 for (size_t i
= 0; i
< 2; ++i
)
1595 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[i
]->WaitForResult()) << i
;
1597 for (size_t i
= 2; i
< requests_
.size(); ++i
)
1598 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1601 TEST_F(HostResolverImplDnsTest
, SystemOnlyBypassesDnsTask
) {
1602 ChangeDnsConfig(CreateValidDnsConfig());
1604 proc_
->AddRuleForAllFamilies(std::string(), std::string());
1606 HostResolver::RequestInfo
info_bypass(HostPortPair("ok", 80));
1607 info_bypass
.set_host_resolver_flags(HOST_RESOLVER_SYSTEM_ONLY
);
1608 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(info_bypass
, MEDIUM
)->Resolve());
1610 HostResolver::RequestInfo
info(HostPortPair("ok", 80));
1611 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(info
, MEDIUM
)->Resolve());
1613 proc_
->SignalMultiple(requests_
.size());
1615 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[0]->WaitForResult());
1616 EXPECT_EQ(OK
, requests_
[1]->WaitForResult());
1619 TEST_F(HostResolverImplDnsTest
, DisableDnsClientOnPersistentFailure
) {
1620 ChangeDnsConfig(CreateValidDnsConfig());
1622 proc_
->AddRuleForAllFamilies(std::string(),
1623 std::string()); // Default to failures.
1625 // Check that DnsTask works.
1626 Request
* req
= CreateRequest("ok_1", 80);
1627 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1628 EXPECT_EQ(OK
, req
->WaitForResult());
1630 for (unsigned i
= 0; i
< maximum_dns_failures(); ++i
) {
1631 // Use custom names to require separate Jobs.
1632 std::string hostname
= base::StringPrintf("nx_%u", i
);
1633 // Ensure fallback to ProcTask succeeds.
1634 proc_
->AddRuleForAllFamilies(hostname
, "192.168.1.101");
1635 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(hostname
, 80)->Resolve()) << i
;
1638 proc_
->SignalMultiple(requests_
.size());
1640 for (size_t i
= 0; i
< requests_
.size(); ++i
)
1641 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1643 ASSERT_FALSE(proc_
->HasBlockedRequests());
1645 // DnsTask should be disabled by now.
1646 req
= CreateRequest("ok_2", 80);
1647 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1648 proc_
->SignalMultiple(1u);
1649 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req
->WaitForResult());
1651 // Check that it is re-enabled after DNS change.
1652 ChangeDnsConfig(CreateValidDnsConfig());
1653 req
= CreateRequest("ok_3", 80);
1654 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1655 EXPECT_EQ(OK
, req
->WaitForResult());
1658 TEST_F(HostResolverImplDnsTest
, DontDisableDnsClientOnSporadicFailure
) {
1659 ChangeDnsConfig(CreateValidDnsConfig());
1661 // |proc_| defaults to successes.
1663 // 20 failures interleaved with 20 successes.
1664 for (unsigned i
= 0; i
< 40; ++i
) {
1665 // Use custom names to require separate Jobs.
1666 std::string hostname
= (i
% 2) == 0 ? base::StringPrintf("nx_%u", i
)
1667 : base::StringPrintf("ok_%u", i
);
1668 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(hostname
, 80)->Resolve()) << i
;
1671 proc_
->SignalMultiple(requests_
.size());
1673 for (size_t i
= 0; i
< requests_
.size(); ++i
)
1674 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1676 // Make |proc_| default to failures.
1677 proc_
->AddRuleForAllFamilies(std::string(), std::string());
1679 // DnsTask should still be enabled.
1680 Request
* req
= CreateRequest("ok_last", 80);
1681 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1682 EXPECT_EQ(OK
, req
->WaitForResult());
1685 // Confirm that resolving "localhost" is unrestricted even if there are no
1686 // global IPv6 address. See SystemHostResolverCall for rationale.
1687 // Test both the DnsClient and system host resolver paths.
1688 TEST_F(HostResolverImplDnsTest
, DualFamilyLocalhost
) {
1689 // Use regular SystemHostResolverCall!
1690 scoped_refptr
<HostResolverProc
> proc(new SystemHostResolverProc());
1691 resolver_
.reset(new HostResolverImpl(HostCache::CreateDefaultCache(),
1693 DefaultParams(proc
.get()),
1695 resolver_
->SetDnsClient(
1696 scoped_ptr
<DnsClient
>(new MockDnsClient(DnsConfig(), dns_rules_
)));
1697 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1699 // Get the expected output.
1700 AddressList addrlist
;
1701 int rv
= proc
->Resolve("localhost", ADDRESS_FAMILY_UNSPECIFIED
, 0, &addrlist
,
1706 for (unsigned i
= 0; i
< addrlist
.size(); ++i
)
1707 LOG(WARNING
) << addrlist
[i
].ToString();
1709 bool saw_ipv4
= AddressListContains(addrlist
, "127.0.0.1", 0);
1710 bool saw_ipv6
= AddressListContains(addrlist
, "::1", 0);
1711 if (!saw_ipv4
&& !saw_ipv6
)
1714 HostResolver::RequestInfo
info(HostPortPair("localhost", 80));
1715 info
.set_address_family(ADDRESS_FAMILY_UNSPECIFIED
);
1716 info
.set_host_resolver_flags(HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
);
1718 // Try without DnsClient.
1719 ChangeDnsConfig(DnsConfig());
1720 Request
* req
= CreateRequest(info
, DEFAULT_PRIORITY
);
1721 // It is resolved via getaddrinfo, so expect asynchronous result.
1722 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1723 EXPECT_EQ(OK
, req
->WaitForResult());
1725 EXPECT_EQ(saw_ipv4
, req
->HasAddress("127.0.0.1", 80));
1726 EXPECT_EQ(saw_ipv6
, req
->HasAddress("::1", 80));
1728 // Configure DnsClient with dual-host HOSTS file.
1729 DnsConfig config
= CreateValidDnsConfig();
1731 IPAddressNumber local_ipv4
, local_ipv6
;
1732 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4
));
1733 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6
));
1735 hosts
[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4
)] = local_ipv4
;
1737 hosts
[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV6
)] = local_ipv6
;
1738 config
.hosts
= hosts
;
1740 ChangeDnsConfig(config
);
1741 req
= CreateRequest(info
, DEFAULT_PRIORITY
);
1742 // Expect synchronous resolution from DnsHosts.
1743 EXPECT_EQ(OK
, req
->Resolve());
1745 EXPECT_EQ(saw_ipv4
, req
->HasAddress("127.0.0.1", 80));
1746 EXPECT_EQ(saw_ipv6
, req
->HasAddress("::1", 80));
1749 // Cancel a request with a single DNS transaction active.
1750 TEST_F(HostResolverImplDnsTest
, CancelWithOneTransactionActive
) {
1751 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1752 ChangeDnsConfig(CreateValidDnsConfig());
1754 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1755 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1756 requests_
[0]->Cancel();
1758 // Dispatcher state checked in TearDown.
1761 // Cancel a request with a single DNS transaction active and another pending.
1762 TEST_F(HostResolverImplDnsTest
, CancelWithOneTransactionActiveOnePending
) {
1763 CreateSerialResolver();
1764 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1765 ChangeDnsConfig(CreateValidDnsConfig());
1767 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1768 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1769 requests_
[0]->Cancel();
1771 // Dispatcher state checked in TearDown.
1774 // Cancel a request with two DNS transactions active.
1775 TEST_F(HostResolverImplDnsTest
, CancelWithTwoTransactionsActive
) {
1776 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1777 ChangeDnsConfig(CreateValidDnsConfig());
1779 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1780 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1781 requests_
[0]->Cancel();
1783 // Dispatcher state checked in TearDown.
1786 // Delete a resolver with some active requests and some queued requests.
1787 TEST_F(HostResolverImplDnsTest
, DeleteWithActiveTransactions
) {
1788 // At most 10 Jobs active at once.
1789 CreateResolverWithLimitsAndParams(
1790 PrioritizedDispatcher::Limits(NUM_PRIORITIES
, 10u),
1791 DefaultParams(proc_
.get()));
1793 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1794 ChangeDnsConfig(CreateValidDnsConfig());
1796 // First active job is an IPv4 request.
1797 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80, MEDIUM
,
1798 ADDRESS_FAMILY_IPV4
)->Resolve());
1800 // Add 10 more DNS lookups for different hostnames. First 4 should have two
1801 // active jobs, next one has a single active job, and one pending. Others
1802 // should all be queued.
1803 for (int i
= 0; i
< 10; ++i
) {
1804 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(
1805 base::StringPrintf("ok%i", i
))->Resolve());
1807 EXPECT_EQ(10u, num_running_dispatcher_jobs());
1812 // Cancel a request with only the IPv6 transaction active.
1813 TEST_F(HostResolverImplDnsTest
, CancelWithIPv6TransactionActive
) {
1814 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1815 ChangeDnsConfig(CreateValidDnsConfig());
1817 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("6slow_ok", 80)->Resolve());
1818 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1820 // The IPv4 request should complete, the IPv6 request is still pending.
1821 base::RunLoop().RunUntilIdle();
1822 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1823 requests_
[0]->Cancel();
1825 // Dispatcher state checked in TearDown.
1828 // Cancel a request with only the IPv4 transaction pending.
1829 TEST_F(HostResolverImplDnsTest
, CancelWithIPv4TransactionPending
) {
1830 set_fallback_to_proctask(false);
1831 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1832 ChangeDnsConfig(CreateValidDnsConfig());
1834 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4slow_ok", 80)->Resolve());
1835 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1837 // The IPv6 request should complete, the IPv4 request is still pending.
1838 base::RunLoop().RunUntilIdle();
1839 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1841 requests_
[0]->Cancel();
1844 // Test cases where AAAA completes first.
1845 TEST_F(HostResolverImplDnsTest
, AAAACompletesFirst
) {
1846 set_fallback_to_proctask(false);
1847 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1848 ChangeDnsConfig(CreateValidDnsConfig());
1850 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4slow_ok", 80)->Resolve());
1851 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4slow_4ok", 80)->Resolve());
1852 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4slow_4timeout", 80)->Resolve());
1853 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4slow_6timeout", 80)->Resolve());
1855 base::RunLoop().RunUntilIdle();
1856 EXPECT_FALSE(requests_
[0]->completed());
1857 EXPECT_FALSE(requests_
[1]->completed());
1858 EXPECT_FALSE(requests_
[2]->completed());
1859 // The IPv6 of the third request should have failed and resulted in cancelling
1860 // the IPv4 request.
1861 EXPECT_TRUE(requests_
[3]->completed());
1862 EXPECT_EQ(ERR_DNS_TIMED_OUT
, requests_
[3]->result());
1863 EXPECT_EQ(3u, num_running_dispatcher_jobs());
1865 dns_client_
->CompleteDelayedTransactions();
1866 EXPECT_TRUE(requests_
[0]->completed());
1867 EXPECT_EQ(OK
, requests_
[0]->result());
1868 EXPECT_EQ(2u, requests_
[0]->NumberOfAddresses());
1869 EXPECT_TRUE(requests_
[0]->HasAddress("127.0.0.1", 80));
1870 EXPECT_TRUE(requests_
[0]->HasAddress("::1", 80));
1872 EXPECT_TRUE(requests_
[1]->completed());
1873 EXPECT_EQ(OK
, requests_
[1]->result());
1874 EXPECT_EQ(1u, requests_
[1]->NumberOfAddresses());
1875 EXPECT_TRUE(requests_
[1]->HasAddress("127.0.0.1", 80));
1877 EXPECT_TRUE(requests_
[2]->completed());
1878 EXPECT_EQ(ERR_DNS_TIMED_OUT
, requests_
[2]->result());
1881 // Test the case where only a single transaction slot is available.
1882 TEST_F(HostResolverImplDnsTest
, SerialResolver
) {
1883 CreateSerialResolver();
1884 set_fallback_to_proctask(false);
1885 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1886 ChangeDnsConfig(CreateValidDnsConfig());
1888 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1889 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1891 base::RunLoop().RunUntilIdle();
1892 EXPECT_TRUE(requests_
[0]->completed());
1893 EXPECT_EQ(OK
, requests_
[0]->result());
1894 EXPECT_EQ(2u, requests_
[0]->NumberOfAddresses());
1895 EXPECT_TRUE(requests_
[0]->HasAddress("127.0.0.1", 80));
1896 EXPECT_TRUE(requests_
[0]->HasAddress("::1", 80));
1899 // Test the case where the AAAA query is started when another transaction
1901 TEST_F(HostResolverImplDnsTest
, AAAAStartsAfterOtherJobFinishes
) {
1902 CreateResolverWithLimitsAndParams(
1903 PrioritizedDispatcher::Limits(NUM_PRIORITIES
, 2),
1904 DefaultParams(proc_
.get()));
1905 set_fallback_to_proctask(false);
1906 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1907 ChangeDnsConfig(CreateValidDnsConfig());
1909 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80, MEDIUM
,
1910 ADDRESS_FAMILY_IPV4
)->Resolve());
1911 EXPECT_EQ(ERR_IO_PENDING
,
1912 CreateRequest("4slow_ok", 80, MEDIUM
)->Resolve());
1913 // An IPv4 request should have been started pending for each job.
1914 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1916 // Request 0's IPv4 request should complete, starting Request 1's IPv6
1917 // request, which should also complete.
1918 base::RunLoop().RunUntilIdle();
1919 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1920 EXPECT_TRUE(requests_
[0]->completed());
1921 EXPECT_FALSE(requests_
[1]->completed());
1923 dns_client_
->CompleteDelayedTransactions();
1924 EXPECT_TRUE(requests_
[1]->completed());
1925 EXPECT_EQ(OK
, requests_
[1]->result());
1926 EXPECT_EQ(2u, requests_
[1]->NumberOfAddresses());
1927 EXPECT_TRUE(requests_
[1]->HasAddress("127.0.0.1", 80));
1928 EXPECT_TRUE(requests_
[1]->HasAddress("::1", 80));
1931 // Tests the case that a Job with a single transaction receives an empty address
1932 // list, triggering fallback to ProcTask.
1933 TEST_F(HostResolverImplDnsTest
, IPv4EmptyFallback
) {
1934 ChangeDnsConfig(CreateValidDnsConfig());
1935 proc_
->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
1936 proc_
->SignalMultiple(1u);
1937 EXPECT_EQ(ERR_IO_PENDING
,
1938 CreateRequest("empty_fallback", 80, MEDIUM
,
1939 ADDRESS_FAMILY_IPV4
)->Resolve());
1940 EXPECT_EQ(OK
, requests_
[0]->WaitForResult());
1941 EXPECT_TRUE(requests_
[0]->HasOneAddress("192.168.0.1", 80));
1944 // Tests the case that a Job with two transactions receives two empty address
1945 // lists, triggering fallback to ProcTask.
1946 TEST_F(HostResolverImplDnsTest
, UnspecEmptyFallback
) {
1947 ChangeDnsConfig(CreateValidDnsConfig());
1948 proc_
->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
1949 proc_
->SignalMultiple(1u);
1950 EXPECT_EQ(ERR_IO_PENDING
,
1951 CreateRequest("empty_fallback", 80, MEDIUM
,
1952 ADDRESS_FAMILY_UNSPECIFIED
)->Resolve());
1953 EXPECT_EQ(OK
, requests_
[0]->WaitForResult());
1954 EXPECT_TRUE(requests_
[0]->HasOneAddress("192.168.0.1", 80));
1957 // Tests getting a new invalid DnsConfig while there are active DnsTasks.
1958 TEST_F(HostResolverImplDnsTest
, InvalidDnsConfigWithPendingRequests
) {
1959 // At most 3 jobs active at once. This number is important, since we want to
1960 // make sure that aborting the first HostResolverImpl::Job does not trigger
1961 // another DnsTransaction on the second Job when it releases its second
1962 // prioritized dispatcher slot.
1963 CreateResolverWithLimitsAndParams(
1964 PrioritizedDispatcher::Limits(NUM_PRIORITIES
, 3u),
1965 DefaultParams(proc_
.get()));
1967 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1968 ChangeDnsConfig(CreateValidDnsConfig());
1970 proc_
->AddRuleForAllFamilies("slow_nx1", "192.168.0.1");
1971 proc_
->AddRuleForAllFamilies("slow_nx2", "192.168.0.2");
1972 proc_
->AddRuleForAllFamilies("ok", "192.168.0.3");
1974 // First active job gets two slots.
1975 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_nx1")->Resolve());
1976 // Next job gets one slot, and waits on another.
1977 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_nx2")->Resolve());
1978 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok")->Resolve());
1980 EXPECT_EQ(3u, num_running_dispatcher_jobs());
1982 // Clear DNS config. Two in-progress jobs should be aborted, and the next one
1983 // should use a ProcTask.
1984 ChangeDnsConfig(DnsConfig());
1985 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[0]->WaitForResult());
1986 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[1]->WaitForResult());
1988 // Finish up the third job. Should bypass the DnsClient, and get its results
1989 // from MockHostResolverProc.
1990 EXPECT_FALSE(requests_
[2]->completed());
1991 proc_
->SignalMultiple(1u);
1992 EXPECT_EQ(OK
, requests_
[2]->WaitForResult());
1993 EXPECT_TRUE(requests_
[2]->HasOneAddress("192.168.0.3", 80));
1996 // Tests the case that DnsClient is automatically disabled due to failures
1997 // while there are active DnsTasks.
1998 TEST_F(HostResolverImplDnsTest
,
1999 AutomaticallyDisableDnsClientWithPendingRequests
) {
2000 // Trying different limits is important for this test: Different limits
2001 // result in different behavior when aborting in-progress DnsTasks. Having
2002 // a DnsTask that has one job active and one in the queue when another job
2003 // occupying two slots has its DnsTask aborted is the case most likely to run
2005 for (size_t limit
= 1u; limit
< 6u; ++limit
) {
2006 CreateResolverWithLimitsAndParams(
2007 PrioritizedDispatcher::Limits(NUM_PRIORITIES
, limit
),
2008 DefaultParams(proc_
.get()));
2010 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
2011 ChangeDnsConfig(CreateValidDnsConfig());
2013 // Queue up enough failures to disable DnsTasks. These will all fall back
2014 // to ProcTasks, and succeed there.
2015 for (unsigned i
= 0u; i
< maximum_dns_failures(); ++i
) {
2016 std::string host
= base::StringPrintf("nx%u", i
);
2017 proc_
->AddRuleForAllFamilies(host
, "192.168.0.1");
2018 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(host
)->Resolve());
2021 // These requests should all bypass DnsTasks, due to the above failures,
2022 // so should end up using ProcTasks.
2023 proc_
->AddRuleForAllFamilies("slow_ok1", "192.168.0.2");
2024 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_ok1")->Resolve());
2025 proc_
->AddRuleForAllFamilies("slow_ok2", "192.168.0.3");
2026 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_ok2")->Resolve());
2027 proc_
->AddRuleForAllFamilies("slow_ok3", "192.168.0.4");
2028 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_ok3")->Resolve());
2029 proc_
->SignalMultiple(maximum_dns_failures() + 3);
2031 for (size_t i
= 0u; i
< maximum_dns_failures(); ++i
) {
2032 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult());
2033 EXPECT_TRUE(requests_
[i
]->HasOneAddress("192.168.0.1", 80));
2036 EXPECT_EQ(OK
, requests_
[maximum_dns_failures()]->WaitForResult());
2037 EXPECT_TRUE(requests_
[maximum_dns_failures()]->HasOneAddress(
2038 "192.168.0.2", 80));
2039 EXPECT_EQ(OK
, requests_
[maximum_dns_failures() + 1]->WaitForResult());
2040 EXPECT_TRUE(requests_
[maximum_dns_failures() + 1]->HasOneAddress(
2041 "192.168.0.3", 80));
2042 EXPECT_EQ(OK
, requests_
[maximum_dns_failures() + 2]->WaitForResult());
2043 EXPECT_TRUE(requests_
[maximum_dns_failures() + 2]->HasOneAddress(
2044 "192.168.0.4", 80));
2049 // Tests a call to SetDnsClient while there are active DnsTasks.
2050 TEST_F(HostResolverImplDnsTest
, ManuallyDisableDnsClientWithPendingRequests
) {
2051 // At most 3 jobs active at once. This number is important, since we want to
2052 // make sure that aborting the first HostResolverImpl::Job does not trigger
2053 // another DnsTransaction on the second Job when it releases its second
2054 // prioritized dispatcher slot.
2055 CreateResolverWithLimitsAndParams(
2056 PrioritizedDispatcher::Limits(NUM_PRIORITIES
, 3u),
2057 DefaultParams(proc_
.get()));
2059 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
2060 ChangeDnsConfig(CreateValidDnsConfig());
2062 proc_
->AddRuleForAllFamilies("slow_ok1", "192.168.0.1");
2063 proc_
->AddRuleForAllFamilies("slow_ok2", "192.168.0.2");
2064 proc_
->AddRuleForAllFamilies("ok", "192.168.0.3");
2066 // First active job gets two slots.
2067 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_ok1")->Resolve());
2068 // Next job gets one slot, and waits on another.
2069 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_ok2")->Resolve());
2070 // Next one is queued.
2071 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok")->Resolve());
2073 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2075 // Clear DnsClient. The two in-progress jobs should fall back to a ProcTask,
2076 // and the next one should be started with a ProcTask.
2077 resolver_
->SetDnsClient(scoped_ptr
<DnsClient
>());
2079 // All three in-progress requests should now be running a ProcTask.
2080 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2081 proc_
->SignalMultiple(3u);
2083 EXPECT_EQ(OK
, requests_
[0]->WaitForResult());
2084 EXPECT_TRUE(requests_
[0]->HasOneAddress("192.168.0.1", 80));
2085 EXPECT_EQ(OK
, requests_
[1]->WaitForResult());
2086 EXPECT_TRUE(requests_
[1]->HasOneAddress("192.168.0.2", 80));
2087 EXPECT_EQ(OK
, requests_
[2]->WaitForResult());
2088 EXPECT_TRUE(requests_
[2]->HasOneAddress("192.168.0.3", 80));