QUIC - enable LargePostSmallBandwidthLargeBuffer unittest.
[chromium-blink-merge.git] / net / dns / host_resolver_impl_unittest.cc
blob9166350121612230cce81d872c16a364793492ec
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"
7 #include <algorithm>
8 #include <string>
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 "net/log/test_net_log.h"
29 #include "testing/gtest/include/gtest/gtest.h"
31 namespace net {
33 namespace {
35 const size_t kMaxJobs = 10u;
36 const size_t kMaxRetryAttempts = 4u;
38 HostResolver::Options DefaultOptions() {
39 HostResolver::Options options;
40 options.max_concurrent_resolves = kMaxJobs;
41 options.max_retry_attempts = kMaxRetryAttempts;
42 options.enable_caching = true;
43 return options;
46 HostResolverImpl::ProcTaskParams DefaultParams(
47 HostResolverProc* resolver_proc) {
48 return HostResolverImpl::ProcTaskParams(resolver_proc, kMaxRetryAttempts);
51 // A HostResolverProc that pushes each host mapped into a list and allows
52 // waiting for a specific number of requests. Unlike RuleBasedHostResolverProc
53 // it never calls SystemHostResolverCall. By default resolves all hostnames to
54 // "127.0.0.1". After AddRule(), it resolves only names explicitly specified.
55 class MockHostResolverProc : public HostResolverProc {
56 public:
57 struct ResolveKey {
58 ResolveKey(const std::string& hostname, AddressFamily address_family)
59 : hostname(hostname), address_family(address_family) {}
60 bool operator<(const ResolveKey& other) const {
61 return address_family < other.address_family ||
62 (address_family == other.address_family && hostname < other.hostname);
64 std::string hostname;
65 AddressFamily address_family;
68 typedef std::vector<ResolveKey> CaptureList;
70 MockHostResolverProc()
71 : HostResolverProc(NULL),
72 num_requests_waiting_(0),
73 num_slots_available_(0),
74 requests_waiting_(&lock_),
75 slots_available_(&lock_) {
78 // Waits until |count| calls to |Resolve| are blocked. Returns false when
79 // timed out.
80 bool WaitFor(unsigned count) {
81 base::AutoLock lock(lock_);
82 base::Time start_time = base::Time::Now();
83 while (num_requests_waiting_ < count) {
84 requests_waiting_.TimedWait(TestTimeouts::action_timeout());
85 if (base::Time::Now() > start_time + TestTimeouts::action_timeout())
86 return false;
88 return true;
91 // Signals |count| waiting calls to |Resolve|. First come first served.
92 void SignalMultiple(unsigned count) {
93 base::AutoLock lock(lock_);
94 num_slots_available_ += count;
95 slots_available_.Broadcast();
98 // Signals all waiting calls to |Resolve|. Beware of races.
99 void SignalAll() {
100 base::AutoLock lock(lock_);
101 num_slots_available_ = num_requests_waiting_;
102 slots_available_.Broadcast();
105 void AddRule(const std::string& hostname, AddressFamily family,
106 const AddressList& result) {
107 base::AutoLock lock(lock_);
108 rules_[ResolveKey(hostname, family)] = result;
111 void AddRule(const std::string& hostname, AddressFamily family,
112 const std::string& ip_list) {
113 AddressList result;
114 int rv = ParseAddressList(ip_list, std::string(), &result);
115 DCHECK_EQ(OK, rv);
116 AddRule(hostname, family, result);
119 void AddRuleForAllFamilies(const std::string& hostname,
120 const std::string& ip_list) {
121 AddressList result;
122 int rv = ParseAddressList(ip_list, std::string(), &result);
123 DCHECK_EQ(OK, rv);
124 AddRule(hostname, ADDRESS_FAMILY_UNSPECIFIED, result);
125 AddRule(hostname, ADDRESS_FAMILY_IPV4, result);
126 AddRule(hostname, ADDRESS_FAMILY_IPV6, result);
129 int Resolve(const std::string& hostname,
130 AddressFamily address_family,
131 HostResolverFlags host_resolver_flags,
132 AddressList* addrlist,
133 int* os_error) override {
134 base::AutoLock lock(lock_);
135 capture_list_.push_back(ResolveKey(hostname, address_family));
136 ++num_requests_waiting_;
137 requests_waiting_.Broadcast();
138 while (!num_slots_available_)
139 slots_available_.Wait();
140 DCHECK_GT(num_requests_waiting_, 0u);
141 --num_slots_available_;
142 --num_requests_waiting_;
143 if (rules_.empty()) {
144 int rv = ParseAddressList("127.0.0.1", std::string(), addrlist);
145 DCHECK_EQ(OK, rv);
146 return OK;
148 ResolveKey key(hostname, address_family);
149 if (rules_.count(key) == 0)
150 return ERR_NAME_NOT_RESOLVED;
151 *addrlist = rules_[key];
152 return OK;
155 CaptureList GetCaptureList() const {
156 CaptureList copy;
158 base::AutoLock lock(lock_);
159 copy = capture_list_;
161 return copy;
164 bool HasBlockedRequests() const {
165 base::AutoLock lock(lock_);
166 return num_requests_waiting_ > num_slots_available_;
169 protected:
170 ~MockHostResolverProc() override {}
172 private:
173 mutable base::Lock lock_;
174 std::map<ResolveKey, AddressList> rules_;
175 CaptureList capture_list_;
176 unsigned num_requests_waiting_;
177 unsigned num_slots_available_;
178 base::ConditionVariable requests_waiting_;
179 base::ConditionVariable slots_available_;
181 DISALLOW_COPY_AND_ASSIGN(MockHostResolverProc);
184 bool AddressListContains(const AddressList& list, const std::string& address,
185 uint16 port) {
186 IPAddressNumber ip;
187 bool rv = ParseIPLiteralToNumber(address, &ip);
188 DCHECK(rv);
189 return std::find(list.begin(),
190 list.end(),
191 IPEndPoint(ip, port)) != list.end();
194 // A wrapper for requests to a HostResolver.
195 class Request {
196 public:
197 // Base class of handlers to be executed on completion of requests.
198 struct Handler {
199 virtual ~Handler() {}
200 virtual void Handle(Request* request) = 0;
203 Request(const HostResolver::RequestInfo& info,
204 RequestPriority priority,
205 size_t index,
206 HostResolver* resolver,
207 Handler* handler)
208 : info_(info),
209 priority_(priority),
210 index_(index),
211 resolver_(resolver),
212 handler_(handler),
213 quit_on_complete_(false),
214 result_(ERR_UNEXPECTED),
215 handle_(NULL) {}
217 int Resolve() {
218 DCHECK(resolver_);
219 DCHECK(!handle_);
220 list_ = AddressList();
221 result_ = resolver_->Resolve(
222 info_,
223 priority_,
224 &list_,
225 base::Bind(&Request::OnComplete, base::Unretained(this)),
226 &handle_,
227 BoundNetLog());
228 if (!list_.empty())
229 EXPECT_EQ(OK, result_);
230 return result_;
233 int ResolveFromCache() {
234 DCHECK(resolver_);
235 DCHECK(!handle_);
236 return resolver_->ResolveFromCache(info_, &list_, BoundNetLog());
239 void Cancel() {
240 DCHECK(resolver_);
241 DCHECK(handle_);
242 resolver_->CancelRequest(handle_);
243 handle_ = NULL;
246 const HostResolver::RequestInfo& info() const { return info_; }
247 size_t index() const { return index_; }
248 const AddressList& list() const { return list_; }
249 int result() const { return result_; }
250 bool completed() const { return result_ != ERR_IO_PENDING; }
251 bool pending() const { return handle_ != NULL; }
253 bool HasAddress(const std::string& address, uint16 port) const {
254 return AddressListContains(list_, address, port);
257 // Returns the number of addresses in |list_|.
258 unsigned NumberOfAddresses() const {
259 return list_.size();
262 bool HasOneAddress(const std::string& address, uint16 port) const {
263 return HasAddress(address, port) && (NumberOfAddresses() == 1u);
266 // Returns ERR_UNEXPECTED if timed out.
267 int WaitForResult() {
268 if (completed())
269 return result_;
270 base::CancelableClosure closure(base::MessageLoop::QuitClosure());
271 base::MessageLoop::current()->PostDelayedTask(
272 FROM_HERE, closure.callback(), TestTimeouts::action_max_timeout());
273 quit_on_complete_ = true;
274 base::MessageLoop::current()->Run();
275 bool did_quit = !quit_on_complete_;
276 quit_on_complete_ = false;
277 closure.Cancel();
278 if (did_quit)
279 return result_;
280 else
281 return ERR_UNEXPECTED;
284 private:
285 void OnComplete(int rv) {
286 EXPECT_TRUE(pending());
287 EXPECT_EQ(ERR_IO_PENDING, result_);
288 EXPECT_NE(ERR_IO_PENDING, rv);
289 result_ = rv;
290 handle_ = NULL;
291 if (!list_.empty()) {
292 EXPECT_EQ(OK, result_);
293 EXPECT_EQ(info_.port(), list_.front().port());
295 if (handler_)
296 handler_->Handle(this);
297 if (quit_on_complete_) {
298 base::MessageLoop::current()->Quit();
299 quit_on_complete_ = false;
303 HostResolver::RequestInfo info_;
304 RequestPriority priority_;
305 size_t index_;
306 HostResolver* resolver_;
307 Handler* handler_;
308 bool quit_on_complete_;
310 AddressList list_;
311 int result_;
312 HostResolver::RequestHandle handle_;
314 DISALLOW_COPY_AND_ASSIGN(Request);
317 // Using LookupAttemptHostResolverProc simulate very long lookups, and control
318 // which attempt resolves the host.
319 class LookupAttemptHostResolverProc : public HostResolverProc {
320 public:
321 LookupAttemptHostResolverProc(HostResolverProc* previous,
322 int attempt_number_to_resolve,
323 int total_attempts)
324 : HostResolverProc(previous),
325 attempt_number_to_resolve_(attempt_number_to_resolve),
326 current_attempt_number_(0),
327 total_attempts_(total_attempts),
328 total_attempts_resolved_(0),
329 resolved_attempt_number_(0),
330 all_done_(&lock_) {
333 // Test harness will wait for all attempts to finish before checking the
334 // results.
335 void WaitForAllAttemptsToFinish(const base::TimeDelta& wait_time) {
336 base::TimeTicks end_time = base::TimeTicks::Now() + wait_time;
338 base::AutoLock auto_lock(lock_);
339 while (total_attempts_resolved_ != total_attempts_ &&
340 base::TimeTicks::Now() < end_time) {
341 all_done_.TimedWait(end_time - base::TimeTicks::Now());
346 // All attempts will wait for an attempt to resolve the host.
347 void WaitForAnAttemptToComplete() {
348 base::TimeDelta wait_time = base::TimeDelta::FromSeconds(60);
349 base::TimeTicks end_time = base::TimeTicks::Now() + wait_time;
351 base::AutoLock auto_lock(lock_);
352 while (resolved_attempt_number_ == 0 && base::TimeTicks::Now() < end_time)
353 all_done_.TimedWait(end_time - base::TimeTicks::Now());
355 all_done_.Broadcast(); // Tell all waiting attempts to proceed.
358 // Returns the number of attempts that have finished the Resolve() method.
359 int total_attempts_resolved() { return total_attempts_resolved_; }
361 // Returns the first attempt that that has resolved the host.
362 int resolved_attempt_number() { return resolved_attempt_number_; }
364 // HostResolverProc methods.
365 int Resolve(const std::string& host,
366 AddressFamily address_family,
367 HostResolverFlags host_resolver_flags,
368 AddressList* addrlist,
369 int* os_error) override {
370 bool wait_for_right_attempt_to_complete = true;
372 base::AutoLock auto_lock(lock_);
373 ++current_attempt_number_;
374 if (current_attempt_number_ == attempt_number_to_resolve_) {
375 resolved_attempt_number_ = current_attempt_number_;
376 wait_for_right_attempt_to_complete = false;
380 if (wait_for_right_attempt_to_complete)
381 // Wait for the attempt_number_to_resolve_ attempt to resolve.
382 WaitForAnAttemptToComplete();
384 int result = ResolveUsingPrevious(host, address_family, host_resolver_flags,
385 addrlist, os_error);
388 base::AutoLock auto_lock(lock_);
389 ++total_attempts_resolved_;
392 all_done_.Broadcast(); // Tell all attempts to proceed.
394 // Since any negative number is considered a network error, with -1 having
395 // special meaning (ERR_IO_PENDING). We could return the attempt that has
396 // resolved the host as a negative number. For example, if attempt number 3
397 // resolves the host, then this method returns -4.
398 if (result == OK)
399 return -1 - resolved_attempt_number_;
400 else
401 return result;
404 protected:
405 ~LookupAttemptHostResolverProc() override {}
407 private:
408 int attempt_number_to_resolve_;
409 int current_attempt_number_; // Incremented whenever Resolve is called.
410 int total_attempts_;
411 int total_attempts_resolved_;
412 int resolved_attempt_number_;
414 // All attempts wait for right attempt to be resolve.
415 base::Lock lock_;
416 base::ConditionVariable all_done_;
419 } // namespace
421 class HostResolverImplTest : public testing::Test {
422 public:
423 static const int kDefaultPort = 80;
425 HostResolverImplTest() : proc_(new MockHostResolverProc()) {}
427 void CreateResolver() {
428 CreateResolverWithLimitsAndParams(kMaxJobs,
429 DefaultParams(proc_.get()));
432 // This HostResolverImpl will only allow 1 outstanding resolve at a time and
433 // perform no retries.
434 void CreateSerialResolver() {
435 HostResolverImpl::ProcTaskParams params = DefaultParams(proc_.get());
436 params.max_retry_attempts = 0u;
437 CreateResolverWithLimitsAndParams(1u, params);
440 protected:
441 // A Request::Handler which is a proxy to the HostResolverImplTest fixture.
442 struct Handler : public Request::Handler {
443 ~Handler() override {}
445 // Proxy functions so that classes derived from Handler can access them.
446 Request* CreateRequest(const HostResolver::RequestInfo& info,
447 RequestPriority priority) {
448 return test->CreateRequest(info, priority);
450 Request* CreateRequest(const std::string& hostname, int port) {
451 return test->CreateRequest(hostname, port);
453 Request* CreateRequest(const std::string& hostname) {
454 return test->CreateRequest(hostname);
456 ScopedVector<Request>& requests() { return test->requests_; }
458 void DeleteResolver() { test->resolver_.reset(); }
460 HostResolverImplTest* test;
463 // testing::Test implementation:
464 void SetUp() override { CreateResolver(); }
466 void TearDown() override {
467 if (resolver_.get())
468 EXPECT_EQ(0u, resolver_->num_running_dispatcher_jobs_for_tests());
469 EXPECT_FALSE(proc_->HasBlockedRequests());
472 virtual void CreateResolverWithLimitsAndParams(
473 size_t max_concurrent_resolves,
474 const HostResolverImpl::ProcTaskParams& params) {
475 HostResolverImpl::Options options = DefaultOptions();
476 options.max_concurrent_resolves = max_concurrent_resolves;
477 resolver_.reset(new HostResolverImpl(options, NULL));
478 resolver_->set_proc_params_for_test(params);
481 // The Request will not be made until a call to |Resolve()|, and the Job will
482 // not start until released by |proc_->SignalXXX|.
483 Request* CreateRequest(const HostResolver::RequestInfo& info,
484 RequestPriority priority) {
485 Request* req = new Request(
486 info, priority, requests_.size(), resolver_.get(), handler_.get());
487 requests_.push_back(req);
488 return req;
491 Request* CreateRequest(const std::string& hostname,
492 int port,
493 RequestPriority priority,
494 AddressFamily family) {
495 HostResolver::RequestInfo info(HostPortPair(hostname, port));
496 info.set_address_family(family);
497 return CreateRequest(info, priority);
500 Request* CreateRequest(const std::string& hostname,
501 int port,
502 RequestPriority priority) {
503 return CreateRequest(hostname, port, priority, ADDRESS_FAMILY_UNSPECIFIED);
506 Request* CreateRequest(const std::string& hostname, int port) {
507 return CreateRequest(hostname, port, MEDIUM);
510 Request* CreateRequest(const std::string& hostname) {
511 return CreateRequest(hostname, kDefaultPort);
514 void set_handler(Handler* handler) {
515 handler_.reset(handler);
516 handler_->test = this;
519 // Friendship is not inherited, so use proxies to access those.
520 size_t num_running_dispatcher_jobs() const {
521 DCHECK(resolver_.get());
522 return resolver_->num_running_dispatcher_jobs_for_tests();
525 void set_fallback_to_proctask(bool fallback_to_proctask) {
526 DCHECK(resolver_.get());
527 resolver_->fallback_to_proctask_ = fallback_to_proctask;
530 static unsigned maximum_dns_failures() {
531 return HostResolverImpl::kMaximumDnsFailures;
534 bool IsIPv6Reachable(const BoundNetLog& net_log) {
535 return resolver_->IsIPv6Reachable(net_log);
538 scoped_refptr<MockHostResolverProc> proc_;
539 scoped_ptr<HostResolverImpl> resolver_;
540 ScopedVector<Request> requests_;
542 scoped_ptr<Handler> handler_;
545 TEST_F(HostResolverImplTest, AsynchronousLookup) {
546 proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
547 proc_->SignalMultiple(1u);
549 Request* req = CreateRequest("just.testing", 80);
550 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
551 EXPECT_EQ(OK, req->WaitForResult());
553 EXPECT_TRUE(req->HasOneAddress("192.168.1.42", 80));
555 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
558 TEST_F(HostResolverImplTest, LocalhostLookup) {
559 proc_->SignalMultiple(1u);
560 Request* req = CreateRequest("foo.localhost", 80);
561 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
562 EXPECT_EQ(OK, req->WaitForResult());
564 EXPECT_TRUE(req->HasOneAddress("127.0.0.1", 80));
566 EXPECT_EQ("localhost.", proc_->GetCaptureList()[0].hostname);
569 TEST_F(HostResolverImplTest, EmptyListMeansNameNotResolved) {
570 proc_->AddRuleForAllFamilies("just.testing", "");
571 proc_->SignalMultiple(1u);
573 Request* req = CreateRequest("just.testing", 80);
574 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
575 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult());
576 EXPECT_EQ(0u, req->NumberOfAddresses());
577 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
580 TEST_F(HostResolverImplTest, FailedAsynchronousLookup) {
581 proc_->AddRuleForAllFamilies(std::string(),
582 "0.0.0.0"); // Default to failures.
583 proc_->SignalMultiple(1u);
585 Request* req = CreateRequest("just.testing", 80);
586 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
587 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult());
589 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
591 // Also test that the error is not cached.
592 EXPECT_EQ(ERR_DNS_CACHE_MISS, req->ResolveFromCache());
595 TEST_F(HostResolverImplTest, AbortedAsynchronousLookup) {
596 Request* req0 = CreateRequest("just.testing", 80);
597 EXPECT_EQ(ERR_IO_PENDING, req0->Resolve());
599 EXPECT_TRUE(proc_->WaitFor(1u));
601 // Resolver is destroyed while job is running on WorkerPool.
602 resolver_.reset();
604 proc_->SignalAll();
606 // To ensure there was no spurious callback, complete with a new resolver.
607 CreateResolver();
608 Request* req1 = CreateRequest("just.testing", 80);
609 EXPECT_EQ(ERR_IO_PENDING, req1->Resolve());
611 proc_->SignalMultiple(2u);
613 EXPECT_EQ(OK, req1->WaitForResult());
615 // This request was canceled.
616 EXPECT_FALSE(req0->completed());
619 #if defined(THREAD_SANITIZER)
620 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
621 #define MAYBE_NumericIPv4Address DISABLED_NumericIPv4Address
622 #else
623 #define MAYBE_NumericIPv4Address NumericIPv4Address
624 #endif
625 TEST_F(HostResolverImplTest, MAYBE_NumericIPv4Address) {
626 // Stevens says dotted quads with AI_UNSPEC resolve to a single sockaddr_in.
627 Request* req = CreateRequest("127.1.2.3", 5555);
628 EXPECT_EQ(OK, req->Resolve());
630 EXPECT_TRUE(req->HasOneAddress("127.1.2.3", 5555));
633 #if defined(THREAD_SANITIZER)
634 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
635 #define MAYBE_NumericIPv6Address DISABLED_NumericIPv6Address
636 #else
637 #define MAYBE_NumericIPv6Address NumericIPv6Address
638 #endif
639 TEST_F(HostResolverImplTest, MAYBE_NumericIPv6Address) {
640 // Resolve a plain IPv6 address. Don't worry about [brackets], because
641 // the caller should have removed them.
642 Request* req = CreateRequest("2001:db8::1", 5555);
643 EXPECT_EQ(OK, req->Resolve());
645 EXPECT_TRUE(req->HasOneAddress("2001:db8::1", 5555));
648 #if defined(THREAD_SANITIZER)
649 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
650 #define MAYBE_EmptyHost DISABLED_EmptyHost
651 #else
652 #define MAYBE_EmptyHost EmptyHost
653 #endif
654 TEST_F(HostResolverImplTest, MAYBE_EmptyHost) {
655 Request* req = CreateRequest(std::string(), 5555);
656 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
659 #if defined(THREAD_SANITIZER)
660 // There's a data race in this test that may lead to use-after-free.
661 // If the test starts to crash without ThreadSanitizer it needs to be disabled
662 // globally. See http://crbug.com/268946 (stacks for this test in
663 // crbug.com/333567).
664 #define MAYBE_EmptyDotsHost DISABLED_EmptyDotsHost
665 #else
666 #define MAYBE_EmptyDotsHost EmptyDotsHost
667 #endif
668 TEST_F(HostResolverImplTest, MAYBE_EmptyDotsHost) {
669 for (int i = 0; i < 16; ++i) {
670 Request* req = CreateRequest(std::string(i, '.'), 5555);
671 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
675 #if defined(THREAD_SANITIZER)
676 // There's a data race in this test that may lead to use-after-free.
677 // If the test starts to crash without ThreadSanitizer it needs to be disabled
678 // globally. See http://crbug.com/268946.
679 #define MAYBE_LongHost DISABLED_LongHost
680 #else
681 #define MAYBE_LongHost LongHost
682 #endif
683 TEST_F(HostResolverImplTest, MAYBE_LongHost) {
684 Request* req = CreateRequest(std::string(4097, 'a'), 5555);
685 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
688 TEST_F(HostResolverImplTest, DeDupeRequests) {
689 // Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is
690 // blocked, these should all pile up until we signal it.
691 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
692 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 80)->Resolve());
693 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 81)->Resolve());
694 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 82)->Resolve());
695 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve());
697 proc_->SignalMultiple(2u); // One for "a", one for "b".
699 for (size_t i = 0; i < requests_.size(); ++i) {
700 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
704 TEST_F(HostResolverImplTest, CancelMultipleRequests) {
705 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
706 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 80)->Resolve());
707 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 81)->Resolve());
708 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 82)->Resolve());
709 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve());
711 // Cancel everything except request for ("a", 82).
712 requests_[0]->Cancel();
713 requests_[1]->Cancel();
714 requests_[2]->Cancel();
715 requests_[4]->Cancel();
717 proc_->SignalMultiple(2u); // One for "a", one for "b".
719 EXPECT_EQ(OK, requests_[3]->WaitForResult());
722 TEST_F(HostResolverImplTest, CanceledRequestsReleaseJobSlots) {
723 // Fill up the dispatcher and queue.
724 for (unsigned i = 0; i < kMaxJobs + 1; ++i) {
725 std::string hostname = "a_";
726 hostname[1] = 'a' + i;
727 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve());
728 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 81)->Resolve());
731 EXPECT_TRUE(proc_->WaitFor(kMaxJobs));
733 // Cancel all but last two.
734 for (unsigned i = 0; i < requests_.size() - 2; ++i) {
735 requests_[i]->Cancel();
738 EXPECT_TRUE(proc_->WaitFor(kMaxJobs + 1));
740 proc_->SignalAll();
742 size_t num_requests = requests_.size();
743 EXPECT_EQ(OK, requests_[num_requests - 1]->WaitForResult());
744 EXPECT_EQ(OK, requests_[num_requests - 2]->result());
747 TEST_F(HostResolverImplTest, CancelWithinCallback) {
748 struct MyHandler : public Handler {
749 void Handle(Request* req) override {
750 // Port 80 is the first request that the callback will be invoked for.
751 // While we are executing within that callback, cancel the other requests
752 // in the job and start another request.
753 if (req->index() == 0) {
754 // Once "a:80" completes, it will cancel "a:81" and "a:82".
755 requests()[1]->Cancel();
756 requests()[2]->Cancel();
760 set_handler(new MyHandler());
762 for (size_t i = 0; i < 4; ++i) {
763 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
766 proc_->SignalMultiple(2u); // One for "a". One for "finalrequest".
768 EXPECT_EQ(OK, requests_[0]->WaitForResult());
770 Request* final_request = CreateRequest("finalrequest", 70);
771 EXPECT_EQ(ERR_IO_PENDING, final_request->Resolve());
772 EXPECT_EQ(OK, final_request->WaitForResult());
773 EXPECT_TRUE(requests_[3]->completed());
776 TEST_F(HostResolverImplTest, DeleteWithinCallback) {
777 struct MyHandler : public Handler {
778 void Handle(Request* req) override {
779 EXPECT_EQ("a", req->info().hostname());
780 EXPECT_EQ(80, req->info().port());
782 DeleteResolver();
784 // Quit after returning from OnCompleted (to give it a chance at
785 // incorrectly running the cancelled tasks).
786 base::MessageLoop::current()->PostTask(FROM_HERE,
787 base::MessageLoop::QuitClosure());
790 set_handler(new MyHandler());
792 for (size_t i = 0; i < 4; ++i) {
793 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
796 proc_->SignalMultiple(1u); // One for "a".
798 // |MyHandler| will send quit message once all the requests have finished.
799 base::MessageLoop::current()->Run();
802 TEST_F(HostResolverImplTest, DeleteWithinAbortedCallback) {
803 struct MyHandler : public Handler {
804 void Handle(Request* req) override {
805 EXPECT_EQ("a", req->info().hostname());
806 EXPECT_EQ(80, req->info().port());
808 DeleteResolver();
810 // Quit after returning from OnCompleted (to give it a chance at
811 // incorrectly running the cancelled tasks).
812 base::MessageLoop::current()->PostTask(FROM_HERE,
813 base::MessageLoop::QuitClosure());
816 set_handler(new MyHandler());
818 // This test assumes that the Jobs will be Aborted in order ["a", "b"]
819 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
820 // HostResolverImpl will be deleted before later Requests can complete.
821 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 81)->Resolve());
822 // Job for 'b' will be aborted before it can complete.
823 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 82)->Resolve());
824 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve());
826 EXPECT_TRUE(proc_->WaitFor(1u));
828 // Triggering an IP address change.
829 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
831 // |MyHandler| will send quit message once all the requests have finished.
832 base::MessageLoop::current()->Run();
834 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->result());
835 EXPECT_EQ(ERR_IO_PENDING, requests_[1]->result());
836 EXPECT_EQ(ERR_IO_PENDING, requests_[2]->result());
837 EXPECT_EQ(ERR_IO_PENDING, requests_[3]->result());
838 // Clean up.
839 proc_->SignalMultiple(requests_.size());
842 TEST_F(HostResolverImplTest, StartWithinCallback) {
843 struct MyHandler : public Handler {
844 void Handle(Request* req) override {
845 if (req->index() == 0) {
846 // On completing the first request, start another request for "a".
847 // Since caching is disabled, this will result in another async request.
848 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 70)->Resolve());
852 set_handler(new MyHandler());
854 // Turn off caching for this host resolver.
855 HostResolver::Options options = DefaultOptions();
856 options.enable_caching = false;
857 resolver_.reset(new HostResolverImpl(options, NULL));
858 resolver_->set_proc_params_for_test(DefaultParams(proc_.get()));
860 for (size_t i = 0; i < 4; ++i) {
861 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
864 proc_->SignalMultiple(2u); // One for "a". One for the second "a".
866 EXPECT_EQ(OK, requests_[0]->WaitForResult());
867 ASSERT_EQ(5u, requests_.size());
868 EXPECT_EQ(OK, requests_.back()->WaitForResult());
870 EXPECT_EQ(2u, proc_->GetCaptureList().size());
873 TEST_F(HostResolverImplTest, BypassCache) {
874 struct MyHandler : public Handler {
875 void Handle(Request* req) override {
876 if (req->index() == 0) {
877 // On completing the first request, start another request for "a".
878 // Since caching is enabled, this should complete synchronously.
879 std::string hostname = req->info().hostname();
880 EXPECT_EQ(OK, CreateRequest(hostname, 70)->Resolve());
881 EXPECT_EQ(OK, CreateRequest(hostname, 75)->ResolveFromCache());
883 // Ok good. Now make sure that if we ask to bypass the cache, it can no
884 // longer service the request synchronously.
885 HostResolver::RequestInfo info(HostPortPair(hostname, 71));
886 info.set_allow_cached_response(false);
887 EXPECT_EQ(ERR_IO_PENDING,
888 CreateRequest(info, DEFAULT_PRIORITY)->Resolve());
889 } else if (71 == req->info().port()) {
890 // Test is done.
891 base::MessageLoop::current()->Quit();
892 } else {
893 FAIL() << "Unexpected request";
897 set_handler(new MyHandler());
899 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
900 proc_->SignalMultiple(3u); // Only need two, but be generous.
902 // |verifier| will send quit message once all the requests have finished.
903 base::MessageLoop::current()->Run();
904 EXPECT_EQ(2u, proc_->GetCaptureList().size());
907 // Test that IP address changes flush the cache but initial DNS config reads do
908 // not.
909 TEST_F(HostResolverImplTest, FlushCacheOnIPAddressChange) {
910 proc_->SignalMultiple(2u); // One before the flush, one after.
912 Request* req = CreateRequest("host1", 70);
913 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
914 EXPECT_EQ(OK, req->WaitForResult());
916 req = CreateRequest("host1", 75);
917 EXPECT_EQ(OK, req->Resolve()); // Should complete synchronously.
919 // Verify initial DNS config read does not flush cache.
920 NetworkChangeNotifier::NotifyObserversOfInitialDNSConfigReadForTests();
921 req = CreateRequest("host1", 75);
922 EXPECT_EQ(OK, req->Resolve()); // Should complete synchronously.
924 // Flush cache by triggering an IP address change.
925 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
926 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
928 // Resolve "host1" again -- this time it won't be served from cache, so it
929 // will complete asynchronously.
930 req = CreateRequest("host1", 80);
931 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
932 EXPECT_EQ(OK, req->WaitForResult());
935 // Test that IP address changes send ERR_NETWORK_CHANGED to pending requests.
936 TEST_F(HostResolverImplTest, AbortOnIPAddressChanged) {
937 Request* req = CreateRequest("host1", 70);
938 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
940 EXPECT_TRUE(proc_->WaitFor(1u));
941 // Triggering an IP address change.
942 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
943 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
944 proc_->SignalAll();
946 EXPECT_EQ(ERR_NETWORK_CHANGED, req->WaitForResult());
947 EXPECT_EQ(0u, resolver_->GetHostCache()->size());
950 // Test that initial DNS config read signals do not abort pending requests.
951 TEST_F(HostResolverImplTest, DontAbortOnInitialDNSConfigRead) {
952 Request* req = CreateRequest("host1", 70);
953 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
955 EXPECT_TRUE(proc_->WaitFor(1u));
956 // Triggering initial DNS config read signal.
957 NetworkChangeNotifier::NotifyObserversOfInitialDNSConfigReadForTests();
958 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
959 proc_->SignalAll();
961 EXPECT_EQ(OK, req->WaitForResult());
964 // Obey pool constraints after IP address has changed.
965 TEST_F(HostResolverImplTest, ObeyPoolConstraintsAfterIPAddressChange) {
966 // Runs at most one job at a time.
967 CreateSerialResolver();
968 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a")->Resolve());
969 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b")->Resolve());
970 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("c")->Resolve());
972 EXPECT_TRUE(proc_->WaitFor(1u));
973 // Triggering an IP address change.
974 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
975 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
976 proc_->SignalMultiple(3u); // Let the false-start go so that we can catch it.
978 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->WaitForResult());
980 EXPECT_EQ(1u, num_running_dispatcher_jobs());
982 EXPECT_FALSE(requests_[1]->completed());
983 EXPECT_FALSE(requests_[2]->completed());
985 EXPECT_EQ(OK, requests_[2]->WaitForResult());
986 EXPECT_EQ(OK, requests_[1]->result());
989 // Tests that a new Request made from the callback of a previously aborted one
990 // will not be aborted.
991 TEST_F(HostResolverImplTest, AbortOnlyExistingRequestsOnIPAddressChange) {
992 struct MyHandler : public Handler {
993 void Handle(Request* req) override {
994 // Start new request for a different hostname to ensure that the order
995 // of jobs in HostResolverImpl is not stable.
996 std::string hostname;
997 if (req->index() == 0)
998 hostname = "zzz";
999 else if (req->index() == 1)
1000 hostname = "aaa";
1001 else if (req->index() == 2)
1002 hostname = "eee";
1003 else
1004 return; // A request started from within MyHandler.
1005 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname)->Resolve()) << hostname;
1008 set_handler(new MyHandler());
1010 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("bbb")->Resolve());
1011 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("eee")->Resolve());
1012 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ccc")->Resolve());
1014 // Wait until all are blocked;
1015 EXPECT_TRUE(proc_->WaitFor(3u));
1016 // Trigger an IP address change.
1017 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1018 // This should abort all running jobs.
1019 base::MessageLoop::current()->RunUntilIdle();
1020 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->result());
1021 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[1]->result());
1022 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[2]->result());
1023 ASSERT_EQ(6u, requests_.size());
1024 // Unblock all calls to proc.
1025 proc_->SignalMultiple(requests_.size());
1026 // Run until the re-started requests finish.
1027 EXPECT_EQ(OK, requests_[3]->WaitForResult());
1028 EXPECT_EQ(OK, requests_[4]->WaitForResult());
1029 EXPECT_EQ(OK, requests_[5]->WaitForResult());
1030 // Verify that results of aborted Jobs were not cached.
1031 EXPECT_EQ(6u, proc_->GetCaptureList().size());
1032 EXPECT_EQ(3u, resolver_->GetHostCache()->size());
1035 // Tests that when the maximum threads is set to 1, requests are dequeued
1036 // in order of priority.
1037 TEST_F(HostResolverImplTest, HigherPriorityRequestsStartedFirst) {
1038 CreateSerialResolver();
1040 // Note that at this point the MockHostResolverProc is blocked, so any
1041 // requests we make will not complete.
1042 CreateRequest("req0", 80, LOW);
1043 CreateRequest("req1", 80, MEDIUM);
1044 CreateRequest("req2", 80, MEDIUM);
1045 CreateRequest("req3", 80, LOW);
1046 CreateRequest("req4", 80, HIGHEST);
1047 CreateRequest("req5", 80, LOW);
1048 CreateRequest("req6", 80, LOW);
1049 CreateRequest("req5", 80, HIGHEST);
1051 for (size_t i = 0; i < requests_.size(); ++i) {
1052 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1055 // Unblock the resolver thread so the requests can run.
1056 proc_->SignalMultiple(requests_.size()); // More than needed.
1058 // Wait for all the requests to complete succesfully.
1059 for (size_t i = 0; i < requests_.size(); ++i) {
1060 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1063 // Since we have restricted to a single concurrent thread in the jobpool,
1064 // the requests should complete in order of priority (with the exception
1065 // of the first request, which gets started right away, since there is
1066 // nothing outstanding).
1067 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1068 ASSERT_EQ(7u, capture_list.size());
1070 EXPECT_EQ("req0", capture_list[0].hostname);
1071 EXPECT_EQ("req4", capture_list[1].hostname);
1072 EXPECT_EQ("req5", capture_list[2].hostname);
1073 EXPECT_EQ("req1", capture_list[3].hostname);
1074 EXPECT_EQ("req2", capture_list[4].hostname);
1075 EXPECT_EQ("req3", capture_list[5].hostname);
1076 EXPECT_EQ("req6", capture_list[6].hostname);
1079 // Try cancelling a job which has not started yet.
1080 TEST_F(HostResolverImplTest, CancelPendingRequest) {
1081 CreateSerialResolver();
1083 CreateRequest("req0", 80, LOWEST);
1084 CreateRequest("req1", 80, HIGHEST); // Will cancel.
1085 CreateRequest("req2", 80, MEDIUM);
1086 CreateRequest("req3", 80, LOW);
1087 CreateRequest("req4", 80, HIGHEST); // Will cancel.
1088 CreateRequest("req5", 80, LOWEST); // Will cancel.
1089 CreateRequest("req6", 80, MEDIUM);
1091 // Start all of the requests.
1092 for (size_t i = 0; i < requests_.size(); ++i) {
1093 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1096 // Cancel some requests
1097 requests_[1]->Cancel();
1098 requests_[4]->Cancel();
1099 requests_[5]->Cancel();
1101 // Unblock the resolver thread so the requests can run.
1102 proc_->SignalMultiple(requests_.size()); // More than needed.
1104 // Wait for all the requests to complete succesfully.
1105 for (size_t i = 0; i < requests_.size(); ++i) {
1106 if (!requests_[i]->pending())
1107 continue; // Don't wait for the requests we cancelled.
1108 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1111 // Verify that they called out the the resolver proc (which runs on the
1112 // resolver thread) in the expected order.
1113 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1114 ASSERT_EQ(4u, capture_list.size());
1116 EXPECT_EQ("req0", capture_list[0].hostname);
1117 EXPECT_EQ("req2", capture_list[1].hostname);
1118 EXPECT_EQ("req6", capture_list[2].hostname);
1119 EXPECT_EQ("req3", capture_list[3].hostname);
1122 // Test that when too many requests are enqueued, old ones start to be aborted.
1123 TEST_F(HostResolverImplTest, QueueOverflow) {
1124 CreateSerialResolver();
1126 // Allow only 3 queued jobs.
1127 const size_t kMaxPendingJobs = 3u;
1128 resolver_->SetMaxQueuedJobs(kMaxPendingJobs);
1130 // Note that at this point the MockHostResolverProc is blocked, so any
1131 // requests we make will not complete.
1133 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req0", 80, LOWEST)->Resolve());
1134 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req1", 80, HIGHEST)->Resolve());
1135 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req2", 80, MEDIUM)->Resolve());
1136 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req3", 80, MEDIUM)->Resolve());
1138 // At this point, there are 3 enqueued jobs.
1139 // Insertion of subsequent requests will cause evictions
1140 // based on priority.
1142 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE,
1143 CreateRequest("req4", 80, LOW)->Resolve()); // Evicts itself!
1145 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req5", 80, MEDIUM)->Resolve());
1146 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[2]->result());
1147 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req6", 80, HIGHEST)->Resolve());
1148 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[3]->result());
1149 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req7", 80, MEDIUM)->Resolve());
1150 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[5]->result());
1152 // Unblock the resolver thread so the requests can run.
1153 proc_->SignalMultiple(4u);
1155 // The rest should succeed.
1156 EXPECT_EQ(OK, requests_[7]->WaitForResult());
1157 EXPECT_EQ(OK, requests_[0]->result());
1158 EXPECT_EQ(OK, requests_[1]->result());
1159 EXPECT_EQ(OK, requests_[6]->result());
1161 // Verify that they called out the the resolver proc (which runs on the
1162 // resolver thread) in the expected order.
1163 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1164 ASSERT_EQ(4u, capture_list.size());
1166 EXPECT_EQ("req0", capture_list[0].hostname);
1167 EXPECT_EQ("req1", capture_list[1].hostname);
1168 EXPECT_EQ("req6", capture_list[2].hostname);
1169 EXPECT_EQ("req7", capture_list[3].hostname);
1171 // Verify that the evicted (incomplete) requests were not cached.
1172 EXPECT_EQ(4u, resolver_->GetHostCache()->size());
1174 for (size_t i = 0; i < requests_.size(); ++i) {
1175 EXPECT_TRUE(requests_[i]->completed()) << i;
1179 // Tests that after changing the default AddressFamily to IPV4, requests
1180 // with UNSPECIFIED address family map to IPV4.
1181 TEST_F(HostResolverImplTest, SetDefaultAddressFamily_IPv4) {
1182 CreateSerialResolver(); // To guarantee order of resolutions.
1184 proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1");
1185 proc_->AddRule("h1", ADDRESS_FAMILY_IPV6, "::2");
1187 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1189 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1190 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1191 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1193 // Start all of the requests.
1194 for (size_t i = 0; i < requests_.size(); ++i) {
1195 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1198 proc_->SignalMultiple(requests_.size());
1200 // Wait for all the requests to complete.
1201 for (size_t i = 0u; i < requests_.size(); ++i) {
1202 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1205 // Since the requests all had the same priority and we limited the thread
1206 // count to 1, they should have completed in the same order as they were
1207 // requested. Moreover, request0 and request1 will have been serviced by
1208 // the same job.
1210 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1211 ASSERT_EQ(2u, capture_list.size());
1213 EXPECT_EQ("h1", capture_list[0].hostname);
1214 EXPECT_EQ(ADDRESS_FAMILY_IPV4, capture_list[0].address_family);
1216 EXPECT_EQ("h1", capture_list[1].hostname);
1217 EXPECT_EQ(ADDRESS_FAMILY_IPV6, capture_list[1].address_family);
1219 // Now check that the correct resolved IP addresses were returned.
1220 EXPECT_TRUE(requests_[0]->HasOneAddress("1.0.0.1", 80));
1221 EXPECT_TRUE(requests_[1]->HasOneAddress("1.0.0.1", 80));
1222 EXPECT_TRUE(requests_[2]->HasOneAddress("::2", 80));
1225 // This is the exact same test as SetDefaultAddressFamily_IPv4, except the
1226 // default family is set to IPv6 and the family of requests is flipped where
1227 // specified.
1228 TEST_F(HostResolverImplTest, SetDefaultAddressFamily_IPv6) {
1229 CreateSerialResolver(); // To guarantee order of resolutions.
1231 // Don't use IPv6 replacements here since some systems don't support it.
1232 proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1");
1233 proc_->AddRule("h1", ADDRESS_FAMILY_IPV6, "::2");
1235 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV6);
1237 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1238 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1239 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1241 // Start all of the requests.
1242 for (size_t i = 0; i < requests_.size(); ++i) {
1243 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1246 proc_->SignalMultiple(requests_.size());
1248 // Wait for all the requests to complete.
1249 for (size_t i = 0u; i < requests_.size(); ++i) {
1250 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1253 // Since the requests all had the same priority and we limited the thread
1254 // count to 1, they should have completed in the same order as they were
1255 // requested. Moreover, request0 and request1 will have been serviced by
1256 // the same job.
1258 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1259 ASSERT_EQ(2u, capture_list.size());
1261 EXPECT_EQ("h1", capture_list[0].hostname);
1262 EXPECT_EQ(ADDRESS_FAMILY_IPV6, capture_list[0].address_family);
1264 EXPECT_EQ("h1", capture_list[1].hostname);
1265 EXPECT_EQ(ADDRESS_FAMILY_IPV4, capture_list[1].address_family);
1267 // Now check that the correct resolved IP addresses were returned.
1268 EXPECT_TRUE(requests_[0]->HasOneAddress("::2", 80));
1269 EXPECT_TRUE(requests_[1]->HasOneAddress("::2", 80));
1270 EXPECT_TRUE(requests_[2]->HasOneAddress("1.0.0.1", 80));
1273 // Make sure that the address family parameter is respected when raw IPs are
1274 // passed in.
1275 TEST_F(HostResolverImplTest, AddressFamilyWithRawIPs) {
1276 Request* request =
1277 CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1278 EXPECT_EQ(OK, request->Resolve());
1279 EXPECT_TRUE(request->HasOneAddress("127.0.0.1", 80));
1281 request = CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1282 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, request->Resolve());
1284 request = CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1285 EXPECT_EQ(OK, request->Resolve());
1286 EXPECT_TRUE(request->HasOneAddress("127.0.0.1", 80));
1288 request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1289 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, request->Resolve());
1291 request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1292 EXPECT_EQ(OK, request->Resolve());
1293 EXPECT_TRUE(request->HasOneAddress("::1", 80));
1295 request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1296 EXPECT_EQ(OK, request->Resolve());
1297 EXPECT_TRUE(request->HasOneAddress("::1", 80));
1300 TEST_F(HostResolverImplTest, ResolveFromCache) {
1301 proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
1302 proc_->SignalMultiple(1u); // Need only one.
1304 HostResolver::RequestInfo info(HostPortPair("just.testing", 80));
1306 // First hit will miss the cache.
1307 EXPECT_EQ(ERR_DNS_CACHE_MISS,
1308 CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache());
1310 // This time, we fetch normally.
1311 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info, DEFAULT_PRIORITY)->Resolve());
1312 EXPECT_EQ(OK, requests_[1]->WaitForResult());
1314 // Now we should be able to fetch from the cache.
1315 EXPECT_EQ(OK, CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache());
1316 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.1.42", 80));
1319 // Test the retry attempts simulating host resolver proc that takes too long.
1320 TEST_F(HostResolverImplTest, MultipleAttempts) {
1321 // Total number of attempts would be 3 and we want the 3rd attempt to resolve
1322 // the host. First and second attempt will be forced to sleep until they get
1323 // word that a resolution has completed. The 3rd resolution attempt will try
1324 // to get done ASAP, and won't sleep..
1325 int kAttemptNumberToResolve = 3;
1326 int kTotalAttempts = 3;
1328 scoped_refptr<LookupAttemptHostResolverProc> resolver_proc(
1329 new LookupAttemptHostResolverProc(
1330 NULL, kAttemptNumberToResolve, kTotalAttempts));
1332 HostResolverImpl::ProcTaskParams params = DefaultParams(resolver_proc.get());
1334 // Specify smaller interval for unresponsive_delay_ for HostResolverImpl so
1335 // that unit test runs faster. For example, this test finishes in 1.5 secs
1336 // (500ms * 3).
1337 params.unresponsive_delay = base::TimeDelta::FromMilliseconds(500);
1339 resolver_.reset(new HostResolverImpl(DefaultOptions(), NULL));
1340 resolver_->set_proc_params_for_test(params);
1342 // Resolve "host1".
1343 HostResolver::RequestInfo info(HostPortPair("host1", 70));
1344 Request* req = CreateRequest(info, DEFAULT_PRIORITY);
1345 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1347 // Resolve returns -4 to indicate that 3rd attempt has resolved the host.
1348 EXPECT_EQ(-4, req->WaitForResult());
1350 resolver_proc->WaitForAllAttemptsToFinish(
1351 base::TimeDelta::FromMilliseconds(60000));
1352 base::MessageLoop::current()->RunUntilIdle();
1354 EXPECT_EQ(resolver_proc->total_attempts_resolved(), kTotalAttempts);
1355 EXPECT_EQ(resolver_proc->resolved_attempt_number(), kAttemptNumberToResolve);
1358 // If a host resolves to a list that includes 127.0.53.53, this is treated as
1359 // an error. 127.0.53.53 is a localhost address, however it has been given a
1360 // special significance by ICANN to help surfance name collision resulting from
1361 // the new gTLDs.
1362 TEST_F(HostResolverImplTest, NameCollision127_0_53_53) {
1363 proc_->AddRuleForAllFamilies("single", "127.0.53.53");
1364 proc_->AddRuleForAllFamilies("multiple", "127.0.0.1,127.0.53.53");
1365 proc_->AddRuleForAllFamilies("ipv6", "::127.0.53.53");
1366 proc_->AddRuleForAllFamilies("not_reserved1", "53.53.0.127");
1367 proc_->AddRuleForAllFamilies("not_reserved2", "127.0.53.54");
1368 proc_->AddRuleForAllFamilies("not_reserved3", "10.0.53.53");
1369 proc_->SignalMultiple(6u);
1371 Request* request;
1373 request = CreateRequest("single");
1374 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1375 EXPECT_EQ(ERR_ICANN_NAME_COLLISION, request->WaitForResult());
1377 request = CreateRequest("multiple");
1378 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1379 EXPECT_EQ(ERR_ICANN_NAME_COLLISION, request->WaitForResult());
1381 // Resolving an IP literal of 127.0.53.53 however is allowed.
1382 EXPECT_EQ(OK, CreateRequest("127.0.53.53")->Resolve());
1384 // Moreover the address should not be recognized when embedded in an IPv6
1385 // address.
1386 request = CreateRequest("ipv6");
1387 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1388 EXPECT_EQ(OK, request->WaitForResult());
1390 // Try some other IPs which are similar, but NOT an exact match on
1391 // 127.0.53.53.
1392 request = CreateRequest("not_reserved1");
1393 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1394 EXPECT_EQ(OK, request->WaitForResult());
1396 request = CreateRequest("not_reserved2");
1397 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1398 EXPECT_EQ(OK, request->WaitForResult());
1400 request = CreateRequest("not_reserved3");
1401 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1402 EXPECT_EQ(OK, request->WaitForResult());
1405 TEST_F(HostResolverImplTest, IsIPv6Reachable) {
1406 // Verify that two consecutive calls return the same value.
1407 TestNetLog net_log;
1408 BoundNetLog bound_net_log = BoundNetLog::Make(&net_log, NetLog::SOURCE_NONE);
1409 bool result1 = IsIPv6Reachable(bound_net_log);
1410 bool result2 = IsIPv6Reachable(bound_net_log);
1411 EXPECT_EQ(result1, result2);
1413 // Filter reachability check events and verify that there are two of them.
1414 TestNetLogEntry::List event_list;
1415 net_log.GetEntries(&event_list);
1416 TestNetLogEntry::List probe_event_list;
1417 for (const auto& event : event_list) {
1418 if (event.type == NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK) {
1419 probe_event_list.push_back(event);
1422 ASSERT_EQ(2U, probe_event_list.size());
1424 // Verify that the first request was not cached and the second one was.
1425 bool cached;
1426 EXPECT_TRUE(probe_event_list[0].GetBooleanValue("cached", &cached));
1427 EXPECT_FALSE(cached);
1428 EXPECT_TRUE(probe_event_list[1].GetBooleanValue("cached", &cached));
1429 EXPECT_TRUE(cached);
1432 DnsConfig CreateValidDnsConfig() {
1433 IPAddressNumber dns_ip;
1434 bool rv = ParseIPLiteralToNumber("192.168.1.0", &dns_ip);
1435 EXPECT_TRUE(rv);
1437 DnsConfig config;
1438 config.nameservers.push_back(IPEndPoint(dns_ip, dns_protocol::kDefaultPort));
1439 EXPECT_TRUE(config.IsValid());
1440 return config;
1443 // Specialized fixture for tests of DnsTask.
1444 class HostResolverImplDnsTest : public HostResolverImplTest {
1445 public:
1446 HostResolverImplDnsTest() : dns_client_(NULL) {}
1448 protected:
1449 // testing::Test implementation:
1450 void SetUp() override {
1451 AddDnsRule("nx", dns_protocol::kTypeA, MockDnsClientRule::FAIL, false);
1452 AddDnsRule("nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL, false);
1453 AddDnsRule("ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1454 AddDnsRule("ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK, false);
1455 AddDnsRule("4ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1456 AddDnsRule("4ok", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY, false);
1457 AddDnsRule("6ok", dns_protocol::kTypeA, MockDnsClientRule::EMPTY, false);
1458 AddDnsRule("6ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK, false);
1459 AddDnsRule("4nx", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1460 AddDnsRule("4nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL, false);
1461 AddDnsRule("empty", dns_protocol::kTypeA, MockDnsClientRule::EMPTY, false);
1462 AddDnsRule("empty", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY,
1463 false);
1465 AddDnsRule("slow_nx", dns_protocol::kTypeA, MockDnsClientRule::FAIL, true);
1466 AddDnsRule("slow_nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL,
1467 true);
1469 AddDnsRule("4slow_ok", dns_protocol::kTypeA, MockDnsClientRule::OK, true);
1470 AddDnsRule("4slow_ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1471 false);
1472 AddDnsRule("6slow_ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1473 AddDnsRule("6slow_ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1474 true);
1475 AddDnsRule("4slow_4ok", dns_protocol::kTypeA, MockDnsClientRule::OK, true);
1476 AddDnsRule("4slow_4ok", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY,
1477 false);
1478 AddDnsRule("4slow_4timeout", dns_protocol::kTypeA,
1479 MockDnsClientRule::TIMEOUT, true);
1480 AddDnsRule("4slow_4timeout", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1481 false);
1482 AddDnsRule("4slow_6timeout", dns_protocol::kTypeA,
1483 MockDnsClientRule::OK, true);
1484 AddDnsRule("4slow_6timeout", dns_protocol::kTypeAAAA,
1485 MockDnsClientRule::TIMEOUT, false);
1486 CreateResolver();
1489 // HostResolverImplTest implementation:
1490 void CreateResolverWithLimitsAndParams(
1491 size_t max_concurrent_resolves,
1492 const HostResolverImpl::ProcTaskParams& params) override {
1493 HostResolverImpl::Options options = DefaultOptions();
1494 options.max_concurrent_resolves = max_concurrent_resolves;
1495 resolver_.reset(new HostResolverImpl(options, NULL));
1496 resolver_->set_proc_params_for_test(params);
1497 // Disable IPv6 support probing.
1498 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1499 dns_client_ = new MockDnsClient(DnsConfig(), dns_rules_);
1500 resolver_->SetDnsClient(scoped_ptr<DnsClient>(dns_client_));
1503 // Adds a rule to |dns_rules_|. Must be followed by |CreateResolver| to apply.
1504 void AddDnsRule(const std::string& prefix,
1505 uint16 qtype,
1506 MockDnsClientRule::Result result,
1507 bool delay) {
1508 dns_rules_.push_back(MockDnsClientRule(prefix, qtype, result, delay));
1511 void ChangeDnsConfig(const DnsConfig& config) {
1512 NetworkChangeNotifier::SetDnsConfig(config);
1513 // Notification is delivered asynchronously.
1514 base::MessageLoop::current()->RunUntilIdle();
1517 MockDnsClientRuleList dns_rules_;
1518 // Owned by |resolver_|.
1519 MockDnsClient* dns_client_;
1522 // TODO(szym): Test AbortAllInProgressJobs due to DnsConfig change.
1524 // TODO(cbentzel): Test a mix of requests with different HostResolverFlags.
1526 // Test successful and fallback resolutions in HostResolverImpl::DnsTask.
1527 TEST_F(HostResolverImplDnsTest, DnsTask) {
1528 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1530 proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
1531 // All other hostnames will fail in proc_.
1533 // Initially there is no config, so client should not be invoked.
1534 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve());
1535 proc_->SignalMultiple(requests_.size());
1537 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult());
1539 ChangeDnsConfig(CreateValidDnsConfig());
1541 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve());
1542 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_fail", 80)->Resolve());
1543 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_succeed", 80)->Resolve());
1545 proc_->SignalMultiple(requests_.size());
1547 for (size_t i = 1; i < requests_.size(); ++i)
1548 EXPECT_NE(ERR_UNEXPECTED, requests_[i]->WaitForResult()) << i;
1550 EXPECT_EQ(OK, requests_[1]->result());
1551 // Resolved by MockDnsClient.
1552 EXPECT_TRUE(requests_[1]->HasOneAddress("127.0.0.1", 80));
1553 // Fallback to ProcTask.
1554 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[2]->result());
1555 EXPECT_EQ(OK, requests_[3]->result());
1556 EXPECT_TRUE(requests_[3]->HasOneAddress("192.168.1.102", 80));
1559 // Test successful and failing resolutions in HostResolverImpl::DnsTask when
1560 // fallback to ProcTask is disabled.
1561 TEST_F(HostResolverImplDnsTest, NoFallbackToProcTask) {
1562 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1563 set_fallback_to_proctask(false);
1565 proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
1566 // All other hostnames will fail in proc_.
1568 // Set empty DnsConfig.
1569 ChangeDnsConfig(DnsConfig());
1570 // Initially there is no config, so client should not be invoked.
1571 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve());
1572 // There is no config, so fallback to ProcTask must work.
1573 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_succeed", 80)->Resolve());
1574 proc_->SignalMultiple(requests_.size());
1576 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult());
1577 EXPECT_EQ(OK, requests_[1]->WaitForResult());
1578 EXPECT_TRUE(requests_[1]->HasOneAddress("192.168.1.102", 80));
1580 ChangeDnsConfig(CreateValidDnsConfig());
1582 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_abort", 80)->Resolve());
1583 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80)->Resolve());
1585 // Simulate the case when the preference or policy has disabled the DNS client
1586 // causing AbortDnsTasks.
1587 resolver_->SetDnsClient(
1588 scoped_ptr<DnsClient>(new MockDnsClient(DnsConfig(), dns_rules_)));
1589 ChangeDnsConfig(CreateValidDnsConfig());
1591 // First request is resolved by MockDnsClient, others should fail due to
1592 // disabled fallback to ProcTask.
1593 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve());
1594 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_fail", 80)->Resolve());
1595 proc_->SignalMultiple(requests_.size());
1597 // Aborted due to Network Change.
1598 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[2]->WaitForResult());
1599 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[3]->WaitForResult());
1600 // Resolved by MockDnsClient.
1601 EXPECT_EQ(OK, requests_[4]->WaitForResult());
1602 EXPECT_TRUE(requests_[4]->HasOneAddress("127.0.0.1", 80));
1603 // Fallback to ProcTask is disabled.
1604 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[5]->WaitForResult());
1607 // Test behavior of OnDnsTaskFailure when Job is aborted.
1608 TEST_F(HostResolverImplDnsTest, OnDnsTaskFailureAbortedJob) {
1609 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1610 ChangeDnsConfig(CreateValidDnsConfig());
1611 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80)->Resolve());
1612 // Abort all jobs here.
1613 CreateResolver();
1614 proc_->SignalMultiple(requests_.size());
1615 // Run to completion.
1616 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1617 // It shouldn't crash during OnDnsTaskFailure callbacks.
1618 EXPECT_EQ(ERR_IO_PENDING, requests_[0]->result());
1620 // Repeat test with Fallback to ProcTask disabled
1621 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1622 set_fallback_to_proctask(false);
1623 ChangeDnsConfig(CreateValidDnsConfig());
1624 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80)->Resolve());
1625 // Abort all jobs here.
1626 CreateResolver();
1627 // Run to completion.
1628 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1629 // It shouldn't crash during OnDnsTaskFailure callbacks.
1630 EXPECT_EQ(ERR_IO_PENDING, requests_[1]->result());
1633 TEST_F(HostResolverImplDnsTest, DnsTaskUnspec) {
1634 ChangeDnsConfig(CreateValidDnsConfig());
1636 proc_->AddRuleForAllFamilies("4nx", "192.168.1.101");
1637 // All other hostnames will fail in proc_.
1639 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1640 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4ok", 80)->Resolve());
1641 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("6ok", 80)->Resolve());
1642 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4nx", 80)->Resolve());
1644 proc_->SignalMultiple(requests_.size());
1646 for (size_t i = 0; i < requests_.size(); ++i)
1647 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1649 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses());
1650 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80));
1651 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80));
1652 EXPECT_EQ(1u, requests_[1]->NumberOfAddresses());
1653 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80));
1654 EXPECT_EQ(1u, requests_[2]->NumberOfAddresses());
1655 EXPECT_TRUE(requests_[2]->HasAddress("::1", 80));
1656 EXPECT_EQ(1u, requests_[3]->NumberOfAddresses());
1657 EXPECT_TRUE(requests_[3]->HasAddress("192.168.1.101", 80));
1660 TEST_F(HostResolverImplDnsTest, ServeFromHosts) {
1661 // Initially, use empty HOSTS file.
1662 DnsConfig config = CreateValidDnsConfig();
1663 ChangeDnsConfig(config);
1665 proc_->AddRuleForAllFamilies(std::string(),
1666 std::string()); // Default to failures.
1667 proc_->SignalMultiple(1u); // For the first request which misses.
1669 Request* req0 = CreateRequest("nx_ipv4", 80);
1670 EXPECT_EQ(ERR_IO_PENDING, req0->Resolve());
1671 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req0->WaitForResult());
1673 IPAddressNumber local_ipv4, local_ipv6;
1674 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4));
1675 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6));
1677 DnsHosts hosts;
1678 hosts[DnsHostsKey("nx_ipv4", ADDRESS_FAMILY_IPV4)] = local_ipv4;
1679 hosts[DnsHostsKey("nx_ipv6", ADDRESS_FAMILY_IPV6)] = local_ipv6;
1680 hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV4)] = local_ipv4;
1681 hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV6)] = local_ipv6;
1683 // Update HOSTS file.
1684 config.hosts = hosts;
1685 ChangeDnsConfig(config);
1687 Request* req1 = CreateRequest("nx_ipv4", 80);
1688 EXPECT_EQ(OK, req1->Resolve());
1689 EXPECT_TRUE(req1->HasOneAddress("127.0.0.1", 80));
1691 Request* req2 = CreateRequest("nx_ipv6", 80);
1692 EXPECT_EQ(OK, req2->Resolve());
1693 EXPECT_TRUE(req2->HasOneAddress("::1", 80));
1695 Request* req3 = CreateRequest("nx_both", 80);
1696 EXPECT_EQ(OK, req3->Resolve());
1697 EXPECT_TRUE(req3->HasAddress("127.0.0.1", 80) &&
1698 req3->HasAddress("::1", 80));
1700 // Requests with specified AddressFamily.
1701 Request* req4 = CreateRequest("nx_ipv4", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1702 EXPECT_EQ(OK, req4->Resolve());
1703 EXPECT_TRUE(req4->HasOneAddress("127.0.0.1", 80));
1705 Request* req5 = CreateRequest("nx_ipv6", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1706 EXPECT_EQ(OK, req5->Resolve());
1707 EXPECT_TRUE(req5->HasOneAddress("::1", 80));
1709 // Request with upper case.
1710 Request* req6 = CreateRequest("nx_IPV4", 80);
1711 EXPECT_EQ(OK, req6->Resolve());
1712 EXPECT_TRUE(req6->HasOneAddress("127.0.0.1", 80));
1715 TEST_F(HostResolverImplDnsTest, BypassDnsTask) {
1716 ChangeDnsConfig(CreateValidDnsConfig());
1718 proc_->AddRuleForAllFamilies(std::string(),
1719 std::string()); // Default to failures.
1721 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok.local", 80)->Resolve());
1722 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok.local.", 80)->Resolve());
1723 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("oklocal", 80)->Resolve());
1724 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("oklocal.", 80)->Resolve());
1725 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1727 proc_->SignalMultiple(requests_.size());
1729 for (size_t i = 0; i < 2; ++i)
1730 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[i]->WaitForResult()) << i;
1732 for (size_t i = 2; i < requests_.size(); ++i)
1733 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1736 TEST_F(HostResolverImplDnsTest, SystemOnlyBypassesDnsTask) {
1737 ChangeDnsConfig(CreateValidDnsConfig());
1739 proc_->AddRuleForAllFamilies(std::string(), std::string());
1741 HostResolver::RequestInfo info_bypass(HostPortPair("ok", 80));
1742 info_bypass.set_host_resolver_flags(HOST_RESOLVER_SYSTEM_ONLY);
1743 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info_bypass, MEDIUM)->Resolve());
1745 HostResolver::RequestInfo info(HostPortPair("ok", 80));
1746 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info, MEDIUM)->Resolve());
1748 proc_->SignalMultiple(requests_.size());
1750 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult());
1751 EXPECT_EQ(OK, requests_[1]->WaitForResult());
1754 TEST_F(HostResolverImplDnsTest, DisableDnsClientOnPersistentFailure) {
1755 ChangeDnsConfig(CreateValidDnsConfig());
1757 proc_->AddRuleForAllFamilies(std::string(),
1758 std::string()); // Default to failures.
1760 // Check that DnsTask works.
1761 Request* req = CreateRequest("ok_1", 80);
1762 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1763 EXPECT_EQ(OK, req->WaitForResult());
1765 for (unsigned i = 0; i < maximum_dns_failures(); ++i) {
1766 // Use custom names to require separate Jobs.
1767 std::string hostname = base::StringPrintf("nx_%u", i);
1768 // Ensure fallback to ProcTask succeeds.
1769 proc_->AddRuleForAllFamilies(hostname, "192.168.1.101");
1770 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve()) << i;
1773 proc_->SignalMultiple(requests_.size());
1775 for (size_t i = 0; i < requests_.size(); ++i)
1776 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1778 ASSERT_FALSE(proc_->HasBlockedRequests());
1780 // DnsTask should be disabled by now.
1781 req = CreateRequest("ok_2", 80);
1782 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1783 proc_->SignalMultiple(1u);
1784 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult());
1786 // Check that it is re-enabled after DNS change.
1787 ChangeDnsConfig(CreateValidDnsConfig());
1788 req = CreateRequest("ok_3", 80);
1789 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1790 EXPECT_EQ(OK, req->WaitForResult());
1793 TEST_F(HostResolverImplDnsTest, DontDisableDnsClientOnSporadicFailure) {
1794 ChangeDnsConfig(CreateValidDnsConfig());
1796 // |proc_| defaults to successes.
1798 // 20 failures interleaved with 20 successes.
1799 for (unsigned i = 0; i < 40; ++i) {
1800 // Use custom names to require separate Jobs.
1801 std::string hostname = (i % 2) == 0 ? base::StringPrintf("nx_%u", i)
1802 : base::StringPrintf("ok_%u", i);
1803 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve()) << i;
1806 proc_->SignalMultiple(requests_.size());
1808 for (size_t i = 0; i < requests_.size(); ++i)
1809 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1811 // Make |proc_| default to failures.
1812 proc_->AddRuleForAllFamilies(std::string(), std::string());
1814 // DnsTask should still be enabled.
1815 Request* req = CreateRequest("ok_last", 80);
1816 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1817 EXPECT_EQ(OK, req->WaitForResult());
1820 // Confirm that resolving "localhost" is unrestricted even if there are no
1821 // global IPv6 address. See SystemHostResolverCall for rationale.
1822 // Test both the DnsClient and system host resolver paths.
1823 TEST_F(HostResolverImplDnsTest, DualFamilyLocalhost) {
1824 // Use regular SystemHostResolverCall!
1825 scoped_refptr<HostResolverProc> proc(new SystemHostResolverProc());
1826 resolver_.reset(new HostResolverImpl(DefaultOptions(), NULL));
1827 resolver_->set_proc_params_for_test(DefaultParams(proc.get()));
1829 resolver_->SetDnsClient(
1830 scoped_ptr<DnsClient>(new MockDnsClient(DnsConfig(), dns_rules_)));
1831 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1833 // Get the expected output.
1834 AddressList addrlist;
1835 int rv = proc->Resolve("localhost", ADDRESS_FAMILY_UNSPECIFIED, 0, &addrlist,
1836 NULL);
1837 if (rv != OK)
1838 return;
1840 for (unsigned i = 0; i < addrlist.size(); ++i)
1841 LOG(WARNING) << addrlist[i].ToString();
1843 bool saw_ipv4 = AddressListContains(addrlist, "127.0.0.1", 0);
1844 bool saw_ipv6 = AddressListContains(addrlist, "::1", 0);
1845 if (!saw_ipv4 && !saw_ipv6)
1846 return;
1848 HostResolver::RequestInfo info(HostPortPair("localhost", 80));
1849 info.set_address_family(ADDRESS_FAMILY_UNSPECIFIED);
1850 info.set_host_resolver_flags(HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6);
1852 // Try without DnsClient.
1853 ChangeDnsConfig(DnsConfig());
1854 Request* req = CreateRequest(info, DEFAULT_PRIORITY);
1855 // It is resolved via getaddrinfo, so expect asynchronous result.
1856 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1857 EXPECT_EQ(OK, req->WaitForResult());
1859 EXPECT_EQ(saw_ipv4, req->HasAddress("127.0.0.1", 80));
1860 EXPECT_EQ(saw_ipv6, req->HasAddress("::1", 80));
1862 // Configure DnsClient with dual-host HOSTS file.
1863 DnsConfig config = CreateValidDnsConfig();
1864 DnsHosts hosts;
1865 IPAddressNumber local_ipv4, local_ipv6;
1866 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4));
1867 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6));
1868 if (saw_ipv4)
1869 hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4)] = local_ipv4;
1870 if (saw_ipv6)
1871 hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV6)] = local_ipv6;
1872 config.hosts = hosts;
1874 ChangeDnsConfig(config);
1875 req = CreateRequest(info, DEFAULT_PRIORITY);
1876 // Expect synchronous resolution from DnsHosts.
1877 EXPECT_EQ(OK, req->Resolve());
1879 EXPECT_EQ(saw_ipv4, req->HasAddress("127.0.0.1", 80));
1880 EXPECT_EQ(saw_ipv6, req->HasAddress("::1", 80));
1883 // Cancel a request with a single DNS transaction active.
1884 TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActive) {
1885 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1886 ChangeDnsConfig(CreateValidDnsConfig());
1888 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1889 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1890 requests_[0]->Cancel();
1892 // Dispatcher state checked in TearDown.
1895 // Cancel a request with a single DNS transaction active and another pending.
1896 TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActiveOnePending) {
1897 CreateSerialResolver();
1898 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1899 ChangeDnsConfig(CreateValidDnsConfig());
1901 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1902 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1903 requests_[0]->Cancel();
1905 // Dispatcher state checked in TearDown.
1908 // Cancel a request with two DNS transactions active.
1909 TEST_F(HostResolverImplDnsTest, CancelWithTwoTransactionsActive) {
1910 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1911 ChangeDnsConfig(CreateValidDnsConfig());
1913 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1914 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1915 requests_[0]->Cancel();
1917 // Dispatcher state checked in TearDown.
1920 // Delete a resolver with some active requests and some queued requests.
1921 TEST_F(HostResolverImplDnsTest, DeleteWithActiveTransactions) {
1922 // At most 10 Jobs active at once.
1923 CreateResolverWithLimitsAndParams(10u, DefaultParams(proc_.get()));
1925 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1926 ChangeDnsConfig(CreateValidDnsConfig());
1928 // First active job is an IPv4 request.
1929 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM,
1930 ADDRESS_FAMILY_IPV4)->Resolve());
1932 // Add 10 more DNS lookups for different hostnames. First 4 should have two
1933 // active jobs, next one has a single active job, and one pending. Others
1934 // should all be queued.
1935 for (int i = 0; i < 10; ++i) {
1936 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(
1937 base::StringPrintf("ok%i", i))->Resolve());
1939 EXPECT_EQ(10u, num_running_dispatcher_jobs());
1941 resolver_.reset();
1944 // Cancel a request with only the IPv6 transaction active.
1945 TEST_F(HostResolverImplDnsTest, CancelWithIPv6TransactionActive) {
1946 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1947 ChangeDnsConfig(CreateValidDnsConfig());
1949 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("6slow_ok", 80)->Resolve());
1950 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1952 // The IPv4 request should complete, the IPv6 request is still pending.
1953 base::RunLoop().RunUntilIdle();
1954 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1955 requests_[0]->Cancel();
1957 // Dispatcher state checked in TearDown.
1960 // Cancel a request with only the IPv4 transaction pending.
1961 TEST_F(HostResolverImplDnsTest, CancelWithIPv4TransactionPending) {
1962 set_fallback_to_proctask(false);
1963 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1964 ChangeDnsConfig(CreateValidDnsConfig());
1966 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_ok", 80)->Resolve());
1967 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1969 // The IPv6 request should complete, the IPv4 request is still pending.
1970 base::RunLoop().RunUntilIdle();
1971 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1973 requests_[0]->Cancel();
1976 // Test cases where AAAA completes first.
1977 TEST_F(HostResolverImplDnsTest, AAAACompletesFirst) {
1978 set_fallback_to_proctask(false);
1979 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1980 ChangeDnsConfig(CreateValidDnsConfig());
1982 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_ok", 80)->Resolve());
1983 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_4ok", 80)->Resolve());
1984 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_4timeout", 80)->Resolve());
1985 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_6timeout", 80)->Resolve());
1987 base::RunLoop().RunUntilIdle();
1988 EXPECT_FALSE(requests_[0]->completed());
1989 EXPECT_FALSE(requests_[1]->completed());
1990 EXPECT_FALSE(requests_[2]->completed());
1991 // The IPv6 of the third request should have failed and resulted in cancelling
1992 // the IPv4 request.
1993 EXPECT_TRUE(requests_[3]->completed());
1994 EXPECT_EQ(ERR_DNS_TIMED_OUT, requests_[3]->result());
1995 EXPECT_EQ(3u, num_running_dispatcher_jobs());
1997 dns_client_->CompleteDelayedTransactions();
1998 EXPECT_TRUE(requests_[0]->completed());
1999 EXPECT_EQ(OK, requests_[0]->result());
2000 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses());
2001 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80));
2002 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80));
2004 EXPECT_TRUE(requests_[1]->completed());
2005 EXPECT_EQ(OK, requests_[1]->result());
2006 EXPECT_EQ(1u, requests_[1]->NumberOfAddresses());
2007 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80));
2009 EXPECT_TRUE(requests_[2]->completed());
2010 EXPECT_EQ(ERR_DNS_TIMED_OUT, requests_[2]->result());
2013 // Test the case where only a single transaction slot is available.
2014 TEST_F(HostResolverImplDnsTest, SerialResolver) {
2015 CreateSerialResolver();
2016 set_fallback_to_proctask(false);
2017 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
2018 ChangeDnsConfig(CreateValidDnsConfig());
2020 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
2021 EXPECT_EQ(1u, num_running_dispatcher_jobs());
2023 base::RunLoop().RunUntilIdle();
2024 EXPECT_TRUE(requests_[0]->completed());
2025 EXPECT_EQ(OK, requests_[0]->result());
2026 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses());
2027 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80));
2028 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80));
2031 // Test the case where the AAAA query is started when another transaction
2032 // completes.
2033 TEST_F(HostResolverImplDnsTest, AAAAStartsAfterOtherJobFinishes) {
2034 CreateResolverWithLimitsAndParams(2u, DefaultParams(proc_.get()));
2035 set_fallback_to_proctask(false);
2036 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
2037 ChangeDnsConfig(CreateValidDnsConfig());
2039 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM,
2040 ADDRESS_FAMILY_IPV4)->Resolve());
2041 EXPECT_EQ(ERR_IO_PENDING,
2042 CreateRequest("4slow_ok", 80, MEDIUM)->Resolve());
2043 // An IPv4 request should have been started pending for each job.
2044 EXPECT_EQ(2u, num_running_dispatcher_jobs());
2046 // Request 0's IPv4 request should complete, starting Request 1's IPv6
2047 // request, which should also complete.
2048 base::RunLoop().RunUntilIdle();
2049 EXPECT_EQ(1u, num_running_dispatcher_jobs());
2050 EXPECT_TRUE(requests_[0]->completed());
2051 EXPECT_FALSE(requests_[1]->completed());
2053 dns_client_->CompleteDelayedTransactions();
2054 EXPECT_TRUE(requests_[1]->completed());
2055 EXPECT_EQ(OK, requests_[1]->result());
2056 EXPECT_EQ(2u, requests_[1]->NumberOfAddresses());
2057 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80));
2058 EXPECT_TRUE(requests_[1]->HasAddress("::1", 80));
2061 // Tests the case that a Job with a single transaction receives an empty address
2062 // list, triggering fallback to ProcTask.
2063 TEST_F(HostResolverImplDnsTest, IPv4EmptyFallback) {
2064 ChangeDnsConfig(CreateValidDnsConfig());
2065 proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
2066 proc_->SignalMultiple(1u);
2067 EXPECT_EQ(ERR_IO_PENDING,
2068 CreateRequest("empty_fallback", 80, MEDIUM,
2069 ADDRESS_FAMILY_IPV4)->Resolve());
2070 EXPECT_EQ(OK, requests_[0]->WaitForResult());
2071 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
2074 // Tests the case that a Job with two transactions receives two empty address
2075 // lists, triggering fallback to ProcTask.
2076 TEST_F(HostResolverImplDnsTest, UnspecEmptyFallback) {
2077 ChangeDnsConfig(CreateValidDnsConfig());
2078 proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
2079 proc_->SignalMultiple(1u);
2080 EXPECT_EQ(ERR_IO_PENDING,
2081 CreateRequest("empty_fallback", 80, MEDIUM,
2082 ADDRESS_FAMILY_UNSPECIFIED)->Resolve());
2083 EXPECT_EQ(OK, requests_[0]->WaitForResult());
2084 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
2087 // Tests getting a new invalid DnsConfig while there are active DnsTasks.
2088 TEST_F(HostResolverImplDnsTest, InvalidDnsConfigWithPendingRequests) {
2089 // At most 3 jobs active at once. This number is important, since we want to
2090 // make sure that aborting the first HostResolverImpl::Job does not trigger
2091 // another DnsTransaction on the second Job when it releases its second
2092 // prioritized dispatcher slot.
2093 CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_.get()));
2095 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
2096 ChangeDnsConfig(CreateValidDnsConfig());
2098 proc_->AddRuleForAllFamilies("slow_nx1", "192.168.0.1");
2099 proc_->AddRuleForAllFamilies("slow_nx2", "192.168.0.2");
2100 proc_->AddRuleForAllFamilies("ok", "192.168.0.3");
2102 // First active job gets two slots.
2103 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_nx1")->Resolve());
2104 // Next job gets one slot, and waits on another.
2105 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_nx2")->Resolve());
2106 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok")->Resolve());
2108 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2110 // Clear DNS config. Two in-progress jobs should be aborted, and the next one
2111 // should use a ProcTask.
2112 ChangeDnsConfig(DnsConfig());
2113 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->WaitForResult());
2114 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[1]->WaitForResult());
2116 // Finish up the third job. Should bypass the DnsClient, and get its results
2117 // from MockHostResolverProc.
2118 EXPECT_FALSE(requests_[2]->completed());
2119 proc_->SignalMultiple(1u);
2120 EXPECT_EQ(OK, requests_[2]->WaitForResult());
2121 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80));
2124 // Tests the case that DnsClient is automatically disabled due to failures
2125 // while there are active DnsTasks.
2126 TEST_F(HostResolverImplDnsTest,
2127 AutomaticallyDisableDnsClientWithPendingRequests) {
2128 // Trying different limits is important for this test: Different limits
2129 // result in different behavior when aborting in-progress DnsTasks. Having
2130 // a DnsTask that has one job active and one in the queue when another job
2131 // occupying two slots has its DnsTask aborted is the case most likely to run
2132 // into problems.
2133 for (size_t limit = 1u; limit < 6u; ++limit) {
2134 CreateResolverWithLimitsAndParams(limit, DefaultParams(proc_.get()));
2136 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
2137 ChangeDnsConfig(CreateValidDnsConfig());
2139 // Queue up enough failures to disable DnsTasks. These will all fall back
2140 // to ProcTasks, and succeed there.
2141 for (unsigned i = 0u; i < maximum_dns_failures(); ++i) {
2142 std::string host = base::StringPrintf("nx%u", i);
2143 proc_->AddRuleForAllFamilies(host, "192.168.0.1");
2144 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(host)->Resolve());
2147 // These requests should all bypass DnsTasks, due to the above failures,
2148 // so should end up using ProcTasks.
2149 proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.2");
2150 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok1")->Resolve());
2151 proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.3");
2152 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok2")->Resolve());
2153 proc_->AddRuleForAllFamilies("slow_ok3", "192.168.0.4");
2154 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok3")->Resolve());
2155 proc_->SignalMultiple(maximum_dns_failures() + 3);
2157 for (size_t i = 0u; i < maximum_dns_failures(); ++i) {
2158 EXPECT_EQ(OK, requests_[i]->WaitForResult());
2159 EXPECT_TRUE(requests_[i]->HasOneAddress("192.168.0.1", 80));
2162 EXPECT_EQ(OK, requests_[maximum_dns_failures()]->WaitForResult());
2163 EXPECT_TRUE(requests_[maximum_dns_failures()]->HasOneAddress(
2164 "192.168.0.2", 80));
2165 EXPECT_EQ(OK, requests_[maximum_dns_failures() + 1]->WaitForResult());
2166 EXPECT_TRUE(requests_[maximum_dns_failures() + 1]->HasOneAddress(
2167 "192.168.0.3", 80));
2168 EXPECT_EQ(OK, requests_[maximum_dns_failures() + 2]->WaitForResult());
2169 EXPECT_TRUE(requests_[maximum_dns_failures() + 2]->HasOneAddress(
2170 "192.168.0.4", 80));
2171 requests_.clear();
2175 // Tests a call to SetDnsClient while there are active DnsTasks.
2176 TEST_F(HostResolverImplDnsTest, ManuallyDisableDnsClientWithPendingRequests) {
2177 // At most 3 jobs active at once. This number is important, since we want to
2178 // make sure that aborting the first HostResolverImpl::Job does not trigger
2179 // another DnsTransaction on the second Job when it releases its second
2180 // prioritized dispatcher slot.
2181 CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_.get()));
2183 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
2184 ChangeDnsConfig(CreateValidDnsConfig());
2186 proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.1");
2187 proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.2");
2188 proc_->AddRuleForAllFamilies("ok", "192.168.0.3");
2190 // First active job gets two slots.
2191 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok1")->Resolve());
2192 // Next job gets one slot, and waits on another.
2193 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok2")->Resolve());
2194 // Next one is queued.
2195 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok")->Resolve());
2197 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2199 // Clear DnsClient. The two in-progress jobs should fall back to a ProcTask,
2200 // and the next one should be started with a ProcTask.
2201 resolver_->SetDnsClient(scoped_ptr<DnsClient>());
2203 // All three in-progress requests should now be running a ProcTask.
2204 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2205 proc_->SignalMultiple(3u);
2207 EXPECT_EQ(OK, requests_[0]->WaitForResult());
2208 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
2209 EXPECT_EQ(OK, requests_[1]->WaitForResult());
2210 EXPECT_TRUE(requests_[1]->HasOneAddress("192.168.0.2", 80));
2211 EXPECT_EQ(OK, requests_[2]->WaitForResult());
2212 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80));
2215 } // namespace net