Lots of random cleanups, mostly for native_theme_win.cc:
[chromium-blink-merge.git] / net / dns / host_resolver_impl_unittest.cc
blob4ab8fdf1c3689c441109731ef6682f325dfc9de3
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 "testing/gtest/include/gtest/gtest.h"
30 namespace net {
32 namespace {
34 const size_t kMaxJobs = 10u;
35 const size_t kMaxRetryAttempts = 4u;
37 HostResolver::Options DefaultOptions() {
38 HostResolver::Options options;
39 options.max_concurrent_resolves = kMaxJobs;
40 options.max_retry_attempts = kMaxRetryAttempts;
41 options.enable_caching = true;
42 return options;
45 HostResolverImpl::ProcTaskParams DefaultParams(
46 HostResolverProc* resolver_proc) {
47 return HostResolverImpl::ProcTaskParams(resolver_proc, kMaxRetryAttempts);
50 // A HostResolverProc that pushes each host mapped into a list and allows
51 // waiting for a specific number of requests. Unlike RuleBasedHostResolverProc
52 // it never calls SystemHostResolverCall. By default resolves all hostnames to
53 // "127.0.0.1". After AddRule(), it resolves only names explicitly specified.
54 class MockHostResolverProc : public HostResolverProc {
55 public:
56 struct ResolveKey {
57 ResolveKey(const std::string& hostname, AddressFamily address_family)
58 : hostname(hostname), address_family(address_family) {}
59 bool operator<(const ResolveKey& other) const {
60 return address_family < other.address_family ||
61 (address_family == other.address_family && hostname < other.hostname);
63 std::string hostname;
64 AddressFamily address_family;
67 typedef std::vector<ResolveKey> CaptureList;
69 MockHostResolverProc()
70 : HostResolverProc(NULL),
71 num_requests_waiting_(0),
72 num_slots_available_(0),
73 requests_waiting_(&lock_),
74 slots_available_(&lock_) {
77 // Waits until |count| calls to |Resolve| are blocked. Returns false when
78 // timed out.
79 bool WaitFor(unsigned count) {
80 base::AutoLock lock(lock_);
81 base::Time start_time = base::Time::Now();
82 while (num_requests_waiting_ < count) {
83 requests_waiting_.TimedWait(TestTimeouts::action_timeout());
84 if (base::Time::Now() > start_time + TestTimeouts::action_timeout())
85 return false;
87 return true;
90 // Signals |count| waiting calls to |Resolve|. First come first served.
91 void SignalMultiple(unsigned count) {
92 base::AutoLock lock(lock_);
93 num_slots_available_ += count;
94 slots_available_.Broadcast();
97 // Signals all waiting calls to |Resolve|. Beware of races.
98 void SignalAll() {
99 base::AutoLock lock(lock_);
100 num_slots_available_ = num_requests_waiting_;
101 slots_available_.Broadcast();
104 void AddRule(const std::string& hostname, AddressFamily family,
105 const AddressList& result) {
106 base::AutoLock lock(lock_);
107 rules_[ResolveKey(hostname, family)] = result;
110 void AddRule(const std::string& hostname, AddressFamily family,
111 const std::string& ip_list) {
112 AddressList result;
113 int rv = ParseAddressList(ip_list, std::string(), &result);
114 DCHECK_EQ(OK, rv);
115 AddRule(hostname, family, result);
118 void AddRuleForAllFamilies(const std::string& hostname,
119 const std::string& ip_list) {
120 AddressList result;
121 int rv = ParseAddressList(ip_list, std::string(), &result);
122 DCHECK_EQ(OK, rv);
123 AddRule(hostname, ADDRESS_FAMILY_UNSPECIFIED, result);
124 AddRule(hostname, ADDRESS_FAMILY_IPV4, result);
125 AddRule(hostname, ADDRESS_FAMILY_IPV6, result);
128 virtual int Resolve(const std::string& hostname,
129 AddressFamily address_family,
130 HostResolverFlags host_resolver_flags,
131 AddressList* addrlist,
132 int* os_error) OVERRIDE {
133 base::AutoLock lock(lock_);
134 capture_list_.push_back(ResolveKey(hostname, address_family));
135 ++num_requests_waiting_;
136 requests_waiting_.Broadcast();
137 while (!num_slots_available_)
138 slots_available_.Wait();
139 DCHECK_GT(num_requests_waiting_, 0u);
140 --num_slots_available_;
141 --num_requests_waiting_;
142 if (rules_.empty()) {
143 int rv = ParseAddressList("127.0.0.1", std::string(), addrlist);
144 DCHECK_EQ(OK, rv);
145 return OK;
147 ResolveKey key(hostname, address_family);
148 if (rules_.count(key) == 0)
149 return ERR_NAME_NOT_RESOLVED;
150 *addrlist = rules_[key];
151 return OK;
154 CaptureList GetCaptureList() const {
155 CaptureList copy;
157 base::AutoLock lock(lock_);
158 copy = capture_list_;
160 return copy;
163 bool HasBlockedRequests() const {
164 base::AutoLock lock(lock_);
165 return num_requests_waiting_ > num_slots_available_;
168 protected:
169 virtual ~MockHostResolverProc() {}
171 private:
172 mutable base::Lock lock_;
173 std::map<ResolveKey, AddressList> rules_;
174 CaptureList capture_list_;
175 unsigned num_requests_waiting_;
176 unsigned num_slots_available_;
177 base::ConditionVariable requests_waiting_;
178 base::ConditionVariable slots_available_;
180 DISALLOW_COPY_AND_ASSIGN(MockHostResolverProc);
183 bool AddressListContains(const AddressList& list, const std::string& address,
184 int port) {
185 IPAddressNumber ip;
186 bool rv = ParseIPLiteralToNumber(address, &ip);
187 DCHECK(rv);
188 return std::find(list.begin(),
189 list.end(),
190 IPEndPoint(ip, port)) != list.end();
193 // A wrapper for requests to a HostResolver.
194 class Request {
195 public:
196 // Base class of handlers to be executed on completion of requests.
197 struct Handler {
198 virtual ~Handler() {}
199 virtual void Handle(Request* request) = 0;
202 Request(const HostResolver::RequestInfo& info,
203 RequestPriority priority,
204 size_t index,
205 HostResolver* resolver,
206 Handler* handler)
207 : info_(info),
208 priority_(priority),
209 index_(index),
210 resolver_(resolver),
211 handler_(handler),
212 quit_on_complete_(false),
213 result_(ERR_UNEXPECTED),
214 handle_(NULL) {}
216 int Resolve() {
217 DCHECK(resolver_);
218 DCHECK(!handle_);
219 list_ = AddressList();
220 result_ = resolver_->Resolve(
221 info_,
222 priority_,
223 &list_,
224 base::Bind(&Request::OnComplete, base::Unretained(this)),
225 &handle_,
226 BoundNetLog());
227 if (!list_.empty())
228 EXPECT_EQ(OK, result_);
229 return result_;
232 int ResolveFromCache() {
233 DCHECK(resolver_);
234 DCHECK(!handle_);
235 return resolver_->ResolveFromCache(info_, &list_, BoundNetLog());
238 void Cancel() {
239 DCHECK(resolver_);
240 DCHECK(handle_);
241 resolver_->CancelRequest(handle_);
242 handle_ = NULL;
245 const HostResolver::RequestInfo& info() const { return info_; }
246 size_t index() const { return index_; }
247 const AddressList& list() const { return list_; }
248 int result() const { return result_; }
249 bool completed() const { return result_ != ERR_IO_PENDING; }
250 bool pending() const { return handle_ != NULL; }
252 bool HasAddress(const std::string& address, int port) const {
253 return AddressListContains(list_, address, port);
256 // Returns the number of addresses in |list_|.
257 unsigned NumberOfAddresses() const {
258 return list_.size();
261 bool HasOneAddress(const std::string& address, int port) const {
262 return HasAddress(address, port) && (NumberOfAddresses() == 1u);
265 // Returns ERR_UNEXPECTED if timed out.
266 int WaitForResult() {
267 if (completed())
268 return result_;
269 base::CancelableClosure closure(base::MessageLoop::QuitClosure());
270 base::MessageLoop::current()->PostDelayedTask(
271 FROM_HERE, closure.callback(), TestTimeouts::action_max_timeout());
272 quit_on_complete_ = true;
273 base::MessageLoop::current()->Run();
274 bool did_quit = !quit_on_complete_;
275 quit_on_complete_ = false;
276 closure.Cancel();
277 if (did_quit)
278 return result_;
279 else
280 return ERR_UNEXPECTED;
283 private:
284 void OnComplete(int rv) {
285 EXPECT_TRUE(pending());
286 EXPECT_EQ(ERR_IO_PENDING, result_);
287 EXPECT_NE(ERR_IO_PENDING, rv);
288 result_ = rv;
289 handle_ = NULL;
290 if (!list_.empty()) {
291 EXPECT_EQ(OK, result_);
292 EXPECT_EQ(info_.port(), list_.front().port());
294 if (handler_)
295 handler_->Handle(this);
296 if (quit_on_complete_) {
297 base::MessageLoop::current()->Quit();
298 quit_on_complete_ = false;
302 HostResolver::RequestInfo info_;
303 RequestPriority priority_;
304 size_t index_;
305 HostResolver* resolver_;
306 Handler* handler_;
307 bool quit_on_complete_;
309 AddressList list_;
310 int result_;
311 HostResolver::RequestHandle handle_;
313 DISALLOW_COPY_AND_ASSIGN(Request);
316 // Using LookupAttemptHostResolverProc simulate very long lookups, and control
317 // which attempt resolves the host.
318 class LookupAttemptHostResolverProc : public HostResolverProc {
319 public:
320 LookupAttemptHostResolverProc(HostResolverProc* previous,
321 int attempt_number_to_resolve,
322 int total_attempts)
323 : HostResolverProc(previous),
324 attempt_number_to_resolve_(attempt_number_to_resolve),
325 current_attempt_number_(0),
326 total_attempts_(total_attempts),
327 total_attempts_resolved_(0),
328 resolved_attempt_number_(0),
329 all_done_(&lock_) {
332 // Test harness will wait for all attempts to finish before checking the
333 // results.
334 void WaitForAllAttemptsToFinish(const base::TimeDelta& wait_time) {
335 base::TimeTicks end_time = base::TimeTicks::Now() + wait_time;
337 base::AutoLock auto_lock(lock_);
338 while (total_attempts_resolved_ != total_attempts_ &&
339 base::TimeTicks::Now() < end_time) {
340 all_done_.TimedWait(end_time - base::TimeTicks::Now());
345 // All attempts will wait for an attempt to resolve the host.
346 void WaitForAnAttemptToComplete() {
347 base::TimeDelta wait_time = base::TimeDelta::FromSeconds(60);
348 base::TimeTicks end_time = base::TimeTicks::Now() + wait_time;
350 base::AutoLock auto_lock(lock_);
351 while (resolved_attempt_number_ == 0 && base::TimeTicks::Now() < end_time)
352 all_done_.TimedWait(end_time - base::TimeTicks::Now());
354 all_done_.Broadcast(); // Tell all waiting attempts to proceed.
357 // Returns the number of attempts that have finished the Resolve() method.
358 int total_attempts_resolved() { return total_attempts_resolved_; }
360 // Returns the first attempt that that has resolved the host.
361 int resolved_attempt_number() { return resolved_attempt_number_; }
363 // HostResolverProc methods.
364 virtual int Resolve(const std::string& host,
365 AddressFamily address_family,
366 HostResolverFlags host_resolver_flags,
367 AddressList* addrlist,
368 int* os_error) OVERRIDE {
369 bool wait_for_right_attempt_to_complete = true;
371 base::AutoLock auto_lock(lock_);
372 ++current_attempt_number_;
373 if (current_attempt_number_ == attempt_number_to_resolve_) {
374 resolved_attempt_number_ = current_attempt_number_;
375 wait_for_right_attempt_to_complete = false;
379 if (wait_for_right_attempt_to_complete)
380 // Wait for the attempt_number_to_resolve_ attempt to resolve.
381 WaitForAnAttemptToComplete();
383 int result = ResolveUsingPrevious(host, address_family, host_resolver_flags,
384 addrlist, os_error);
387 base::AutoLock auto_lock(lock_);
388 ++total_attempts_resolved_;
391 all_done_.Broadcast(); // Tell all attempts to proceed.
393 // Since any negative number is considered a network error, with -1 having
394 // special meaning (ERR_IO_PENDING). We could return the attempt that has
395 // resolved the host as a negative number. For example, if attempt number 3
396 // resolves the host, then this method returns -4.
397 if (result == OK)
398 return -1 - resolved_attempt_number_;
399 else
400 return result;
403 protected:
404 virtual ~LookupAttemptHostResolverProc() {}
406 private:
407 int attempt_number_to_resolve_;
408 int current_attempt_number_; // Incremented whenever Resolve is called.
409 int total_attempts_;
410 int total_attempts_resolved_;
411 int resolved_attempt_number_;
413 // All attempts wait for right attempt to be resolve.
414 base::Lock lock_;
415 base::ConditionVariable all_done_;
418 } // namespace
420 class HostResolverImplTest : public testing::Test {
421 public:
422 static const int kDefaultPort = 80;
424 HostResolverImplTest() : proc_(new MockHostResolverProc()) {}
426 void CreateResolver() {
427 CreateResolverWithLimitsAndParams(kMaxJobs,
428 DefaultParams(proc_.get()));
431 // This HostResolverImpl will only allow 1 outstanding resolve at a time and
432 // perform no retries.
433 void CreateSerialResolver() {
434 HostResolverImpl::ProcTaskParams params = DefaultParams(proc_.get());
435 params.max_retry_attempts = 0u;
436 CreateResolverWithLimitsAndParams(1u, params);
439 protected:
440 // A Request::Handler which is a proxy to the HostResolverImplTest fixture.
441 struct Handler : public Request::Handler {
442 virtual ~Handler() {}
444 // Proxy functions so that classes derived from Handler can access them.
445 Request* CreateRequest(const HostResolver::RequestInfo& info,
446 RequestPriority priority) {
447 return test->CreateRequest(info, priority);
449 Request* CreateRequest(const std::string& hostname, int port) {
450 return test->CreateRequest(hostname, port);
452 Request* CreateRequest(const std::string& hostname) {
453 return test->CreateRequest(hostname);
455 ScopedVector<Request>& requests() { return test->requests_; }
457 void DeleteResolver() { test->resolver_.reset(); }
459 HostResolverImplTest* test;
462 // testing::Test implementation:
463 virtual void SetUp() OVERRIDE {
464 CreateResolver();
467 virtual void TearDown() OVERRIDE {
468 if (resolver_.get())
469 EXPECT_EQ(0u, resolver_->num_running_dispatcher_jobs_for_tests());
470 EXPECT_FALSE(proc_->HasBlockedRequests());
473 virtual void CreateResolverWithLimitsAndParams(
474 size_t max_concurrent_resolves,
475 const HostResolverImpl::ProcTaskParams& params) {
476 HostResolverImpl::Options options = DefaultOptions();
477 options.max_concurrent_resolves = max_concurrent_resolves;
478 resolver_.reset(new HostResolverImpl(options, NULL));
479 resolver_->set_proc_params_for_test(params);
482 // The Request will not be made until a call to |Resolve()|, and the Job will
483 // not start until released by |proc_->SignalXXX|.
484 Request* CreateRequest(const HostResolver::RequestInfo& info,
485 RequestPriority priority) {
486 Request* req = new Request(
487 info, priority, requests_.size(), resolver_.get(), handler_.get());
488 requests_.push_back(req);
489 return req;
492 Request* CreateRequest(const std::string& hostname,
493 int port,
494 RequestPriority priority,
495 AddressFamily family) {
496 HostResolver::RequestInfo info(HostPortPair(hostname, port));
497 info.set_address_family(family);
498 return CreateRequest(info, priority);
501 Request* CreateRequest(const std::string& hostname,
502 int port,
503 RequestPriority priority) {
504 return CreateRequest(hostname, port, priority, ADDRESS_FAMILY_UNSPECIFIED);
507 Request* CreateRequest(const std::string& hostname, int port) {
508 return CreateRequest(hostname, port, MEDIUM);
511 Request* CreateRequest(const std::string& hostname) {
512 return CreateRequest(hostname, kDefaultPort);
515 void set_handler(Handler* handler) {
516 handler_.reset(handler);
517 handler_->test = this;
520 // Friendship is not inherited, so use proxies to access those.
521 size_t num_running_dispatcher_jobs() const {
522 DCHECK(resolver_.get());
523 return resolver_->num_running_dispatcher_jobs_for_tests();
526 void set_fallback_to_proctask(bool fallback_to_proctask) {
527 DCHECK(resolver_.get());
528 resolver_->fallback_to_proctask_ = fallback_to_proctask;
531 static unsigned maximum_dns_failures() {
532 return HostResolverImpl::kMaximumDnsFailures;
535 scoped_refptr<MockHostResolverProc> proc_;
536 scoped_ptr<HostResolverImpl> resolver_;
537 ScopedVector<Request> requests_;
539 scoped_ptr<Handler> handler_;
542 TEST_F(HostResolverImplTest, AsynchronousLookup) {
543 proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
544 proc_->SignalMultiple(1u);
546 Request* req = CreateRequest("just.testing", 80);
547 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
548 EXPECT_EQ(OK, req->WaitForResult());
550 EXPECT_TRUE(req->HasOneAddress("192.168.1.42", 80));
552 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
555 TEST_F(HostResolverImplTest, EmptyListMeansNameNotResolved) {
556 proc_->AddRuleForAllFamilies("just.testing", "");
557 proc_->SignalMultiple(1u);
559 Request* req = CreateRequest("just.testing", 80);
560 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
561 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult());
562 EXPECT_EQ(0u, req->NumberOfAddresses());
563 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
566 TEST_F(HostResolverImplTest, FailedAsynchronousLookup) {
567 proc_->AddRuleForAllFamilies(std::string(),
568 "0.0.0.0"); // Default to failures.
569 proc_->SignalMultiple(1u);
571 Request* req = CreateRequest("just.testing", 80);
572 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
573 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult());
575 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
577 // Also test that the error is not cached.
578 EXPECT_EQ(ERR_DNS_CACHE_MISS, req->ResolveFromCache());
581 TEST_F(HostResolverImplTest, AbortedAsynchronousLookup) {
582 Request* req0 = CreateRequest("just.testing", 80);
583 EXPECT_EQ(ERR_IO_PENDING, req0->Resolve());
585 EXPECT_TRUE(proc_->WaitFor(1u));
587 // Resolver is destroyed while job is running on WorkerPool.
588 resolver_.reset();
590 proc_->SignalAll();
592 // To ensure there was no spurious callback, complete with a new resolver.
593 CreateResolver();
594 Request* req1 = CreateRequest("just.testing", 80);
595 EXPECT_EQ(ERR_IO_PENDING, req1->Resolve());
597 proc_->SignalMultiple(2u);
599 EXPECT_EQ(OK, req1->WaitForResult());
601 // This request was canceled.
602 EXPECT_FALSE(req0->completed());
605 #if defined(THREAD_SANITIZER)
606 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
607 #define MAYBE_NumericIPv4Address DISABLED_NumericIPv4Address
608 #else
609 #define MAYBE_NumericIPv4Address NumericIPv4Address
610 #endif
611 TEST_F(HostResolverImplTest, MAYBE_NumericIPv4Address) {
612 // Stevens says dotted quads with AI_UNSPEC resolve to a single sockaddr_in.
613 Request* req = CreateRequest("127.1.2.3", 5555);
614 EXPECT_EQ(OK, req->Resolve());
616 EXPECT_TRUE(req->HasOneAddress("127.1.2.3", 5555));
619 #if defined(THREAD_SANITIZER)
620 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
621 #define MAYBE_NumericIPv6Address DISABLED_NumericIPv6Address
622 #else
623 #define MAYBE_NumericIPv6Address NumericIPv6Address
624 #endif
625 TEST_F(HostResolverImplTest, MAYBE_NumericIPv6Address) {
626 // Resolve a plain IPv6 address. Don't worry about [brackets], because
627 // the caller should have removed them.
628 Request* req = CreateRequest("2001:db8::1", 5555);
629 EXPECT_EQ(OK, req->Resolve());
631 EXPECT_TRUE(req->HasOneAddress("2001:db8::1", 5555));
634 #if defined(THREAD_SANITIZER)
635 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
636 #define MAYBE_EmptyHost DISABLED_EmptyHost
637 #else
638 #define MAYBE_EmptyHost EmptyHost
639 #endif
640 TEST_F(HostResolverImplTest, MAYBE_EmptyHost) {
641 Request* req = CreateRequest(std::string(), 5555);
642 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
645 #if defined(THREAD_SANITIZER)
646 // There's a data race in this test that may lead to use-after-free.
647 // If the test starts to crash without ThreadSanitizer it needs to be disabled
648 // globally. See http://crbug.com/268946 (stacks for this test in
649 // crbug.com/333567).
650 #define MAYBE_EmptyDotsHost DISABLED_EmptyDotsHost
651 #else
652 #define MAYBE_EmptyDotsHost EmptyDotsHost
653 #endif
654 TEST_F(HostResolverImplTest, MAYBE_EmptyDotsHost) {
655 for (int i = 0; i < 16; ++i) {
656 Request* req = CreateRequest(std::string(i, '.'), 5555);
657 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
661 #if defined(THREAD_SANITIZER)
662 // There's a data race in this test that may lead to use-after-free.
663 // If the test starts to crash without ThreadSanitizer it needs to be disabled
664 // globally. See http://crbug.com/268946.
665 #define MAYBE_LongHost DISABLED_LongHost
666 #else
667 #define MAYBE_LongHost LongHost
668 #endif
669 TEST_F(HostResolverImplTest, MAYBE_LongHost) {
670 Request* req = CreateRequest(std::string(4097, 'a'), 5555);
671 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
674 TEST_F(HostResolverImplTest, DeDupeRequests) {
675 // Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is
676 // blocked, these should all pile up until we signal it.
677 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
678 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 80)->Resolve());
679 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 81)->Resolve());
680 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 82)->Resolve());
681 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve());
683 proc_->SignalMultiple(2u); // One for "a", one for "b".
685 for (size_t i = 0; i < requests_.size(); ++i) {
686 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
690 TEST_F(HostResolverImplTest, CancelMultipleRequests) {
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 // Cancel everything except request for ("a", 82).
698 requests_[0]->Cancel();
699 requests_[1]->Cancel();
700 requests_[2]->Cancel();
701 requests_[4]->Cancel();
703 proc_->SignalMultiple(2u); // One for "a", one for "b".
705 EXPECT_EQ(OK, requests_[3]->WaitForResult());
708 TEST_F(HostResolverImplTest, CanceledRequestsReleaseJobSlots) {
709 // Fill up the dispatcher and queue.
710 for (unsigned i = 0; i < kMaxJobs + 1; ++i) {
711 std::string hostname = "a_";
712 hostname[1] = 'a' + i;
713 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve());
714 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 81)->Resolve());
717 EXPECT_TRUE(proc_->WaitFor(kMaxJobs));
719 // Cancel all but last two.
720 for (unsigned i = 0; i < requests_.size() - 2; ++i) {
721 requests_[i]->Cancel();
724 EXPECT_TRUE(proc_->WaitFor(kMaxJobs + 1));
726 proc_->SignalAll();
728 size_t num_requests = requests_.size();
729 EXPECT_EQ(OK, requests_[num_requests - 1]->WaitForResult());
730 EXPECT_EQ(OK, requests_[num_requests - 2]->result());
733 TEST_F(HostResolverImplTest, CancelWithinCallback) {
734 struct MyHandler : public Handler {
735 virtual void Handle(Request* req) OVERRIDE {
736 // Port 80 is the first request that the callback will be invoked for.
737 // While we are executing within that callback, cancel the other requests
738 // in the job and start another request.
739 if (req->index() == 0) {
740 // Once "a:80" completes, it will cancel "a:81" and "a:82".
741 requests()[1]->Cancel();
742 requests()[2]->Cancel();
746 set_handler(new MyHandler());
748 for (size_t i = 0; i < 4; ++i) {
749 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
752 proc_->SignalMultiple(2u); // One for "a". One for "finalrequest".
754 EXPECT_EQ(OK, requests_[0]->WaitForResult());
756 Request* final_request = CreateRequest("finalrequest", 70);
757 EXPECT_EQ(ERR_IO_PENDING, final_request->Resolve());
758 EXPECT_EQ(OK, final_request->WaitForResult());
759 EXPECT_TRUE(requests_[3]->completed());
762 TEST_F(HostResolverImplTest, DeleteWithinCallback) {
763 struct MyHandler : public Handler {
764 virtual void Handle(Request* req) OVERRIDE {
765 EXPECT_EQ("a", req->info().hostname());
766 EXPECT_EQ(80, req->info().port());
768 DeleteResolver();
770 // Quit after returning from OnCompleted (to give it a chance at
771 // incorrectly running the cancelled tasks).
772 base::MessageLoop::current()->PostTask(FROM_HERE,
773 base::MessageLoop::QuitClosure());
776 set_handler(new MyHandler());
778 for (size_t i = 0; i < 4; ++i) {
779 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
782 proc_->SignalMultiple(1u); // One for "a".
784 // |MyHandler| will send quit message once all the requests have finished.
785 base::MessageLoop::current()->Run();
788 TEST_F(HostResolverImplTest, DeleteWithinAbortedCallback) {
789 struct MyHandler : public Handler {
790 virtual void Handle(Request* req) OVERRIDE {
791 EXPECT_EQ("a", req->info().hostname());
792 EXPECT_EQ(80, req->info().port());
794 DeleteResolver();
796 // Quit after returning from OnCompleted (to give it a chance at
797 // incorrectly running the cancelled tasks).
798 base::MessageLoop::current()->PostTask(FROM_HERE,
799 base::MessageLoop::QuitClosure());
802 set_handler(new MyHandler());
804 // This test assumes that the Jobs will be Aborted in order ["a", "b"]
805 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
806 // HostResolverImpl will be deleted before later Requests can complete.
807 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 81)->Resolve());
808 // Job for 'b' will be aborted before it can complete.
809 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 82)->Resolve());
810 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve());
812 EXPECT_TRUE(proc_->WaitFor(1u));
814 // Triggering an IP address change.
815 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
817 // |MyHandler| will send quit message once all the requests have finished.
818 base::MessageLoop::current()->Run();
820 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->result());
821 EXPECT_EQ(ERR_IO_PENDING, requests_[1]->result());
822 EXPECT_EQ(ERR_IO_PENDING, requests_[2]->result());
823 EXPECT_EQ(ERR_IO_PENDING, requests_[3]->result());
824 // Clean up.
825 proc_->SignalMultiple(requests_.size());
828 TEST_F(HostResolverImplTest, StartWithinCallback) {
829 struct MyHandler : public Handler {
830 virtual void Handle(Request* req) OVERRIDE {
831 if (req->index() == 0) {
832 // On completing the first request, start another request for "a".
833 // Since caching is disabled, this will result in another async request.
834 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 70)->Resolve());
838 set_handler(new MyHandler());
840 // Turn off caching for this host resolver.
841 HostResolver::Options options = DefaultOptions();
842 options.enable_caching = false;
843 resolver_.reset(new HostResolverImpl(options, NULL));
844 resolver_->set_proc_params_for_test(DefaultParams(proc_.get()));
846 for (size_t i = 0; i < 4; ++i) {
847 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
850 proc_->SignalMultiple(2u); // One for "a". One for the second "a".
852 EXPECT_EQ(OK, requests_[0]->WaitForResult());
853 ASSERT_EQ(5u, requests_.size());
854 EXPECT_EQ(OK, requests_.back()->WaitForResult());
856 EXPECT_EQ(2u, proc_->GetCaptureList().size());
859 TEST_F(HostResolverImplTest, BypassCache) {
860 struct MyHandler : public Handler {
861 virtual void Handle(Request* req) OVERRIDE {
862 if (req->index() == 0) {
863 // On completing the first request, start another request for "a".
864 // Since caching is enabled, this should complete synchronously.
865 std::string hostname = req->info().hostname();
866 EXPECT_EQ(OK, CreateRequest(hostname, 70)->Resolve());
867 EXPECT_EQ(OK, CreateRequest(hostname, 75)->ResolveFromCache());
869 // Ok good. Now make sure that if we ask to bypass the cache, it can no
870 // longer service the request synchronously.
871 HostResolver::RequestInfo info(HostPortPair(hostname, 71));
872 info.set_allow_cached_response(false);
873 EXPECT_EQ(ERR_IO_PENDING,
874 CreateRequest(info, DEFAULT_PRIORITY)->Resolve());
875 } else if (71 == req->info().port()) {
876 // Test is done.
877 base::MessageLoop::current()->Quit();
878 } else {
879 FAIL() << "Unexpected request";
883 set_handler(new MyHandler());
885 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
886 proc_->SignalMultiple(3u); // Only need two, but be generous.
888 // |verifier| will send quit message once all the requests have finished.
889 base::MessageLoop::current()->Run();
890 EXPECT_EQ(2u, proc_->GetCaptureList().size());
893 // Test that IP address changes flush the cache.
894 TEST_F(HostResolverImplTest, FlushCacheOnIPAddressChange) {
895 proc_->SignalMultiple(2u); // One before the flush, one after.
897 Request* req = CreateRequest("host1", 70);
898 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
899 EXPECT_EQ(OK, req->WaitForResult());
901 req = CreateRequest("host1", 75);
902 EXPECT_EQ(OK, req->Resolve()); // Should complete synchronously.
904 // Flush cache by triggering an IP address change.
905 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
906 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
908 // Resolve "host1" again -- this time it won't be served from cache, so it
909 // will complete asynchronously.
910 req = CreateRequest("host1", 80);
911 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
912 EXPECT_EQ(OK, req->WaitForResult());
915 // Test that IP address changes send ERR_NETWORK_CHANGED to pending requests.
916 TEST_F(HostResolverImplTest, AbortOnIPAddressChanged) {
917 Request* req = CreateRequest("host1", 70);
918 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
920 EXPECT_TRUE(proc_->WaitFor(1u));
921 // Triggering an IP address change.
922 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
923 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
924 proc_->SignalAll();
926 EXPECT_EQ(ERR_NETWORK_CHANGED, req->WaitForResult());
927 EXPECT_EQ(0u, resolver_->GetHostCache()->size());
930 // Obey pool constraints after IP address has changed.
931 TEST_F(HostResolverImplTest, ObeyPoolConstraintsAfterIPAddressChange) {
932 // Runs at most one job at a time.
933 CreateSerialResolver();
934 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a")->Resolve());
935 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b")->Resolve());
936 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("c")->Resolve());
938 EXPECT_TRUE(proc_->WaitFor(1u));
939 // Triggering an IP address change.
940 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
941 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
942 proc_->SignalMultiple(3u); // Let the false-start go so that we can catch it.
944 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->WaitForResult());
946 EXPECT_EQ(1u, num_running_dispatcher_jobs());
948 EXPECT_FALSE(requests_[1]->completed());
949 EXPECT_FALSE(requests_[2]->completed());
951 EXPECT_EQ(OK, requests_[2]->WaitForResult());
952 EXPECT_EQ(OK, requests_[1]->result());
955 // Tests that a new Request made from the callback of a previously aborted one
956 // will not be aborted.
957 TEST_F(HostResolverImplTest, AbortOnlyExistingRequestsOnIPAddressChange) {
958 struct MyHandler : public Handler {
959 virtual void Handle(Request* req) OVERRIDE {
960 // Start new request for a different hostname to ensure that the order
961 // of jobs in HostResolverImpl is not stable.
962 std::string hostname;
963 if (req->index() == 0)
964 hostname = "zzz";
965 else if (req->index() == 1)
966 hostname = "aaa";
967 else if (req->index() == 2)
968 hostname = "eee";
969 else
970 return; // A request started from within MyHandler.
971 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname)->Resolve()) << hostname;
974 set_handler(new MyHandler());
976 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("bbb")->Resolve());
977 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("eee")->Resolve());
978 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ccc")->Resolve());
980 // Wait until all are blocked;
981 EXPECT_TRUE(proc_->WaitFor(3u));
982 // Trigger an IP address change.
983 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
984 // This should abort all running jobs.
985 base::MessageLoop::current()->RunUntilIdle();
986 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->result());
987 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[1]->result());
988 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[2]->result());
989 ASSERT_EQ(6u, requests_.size());
990 // Unblock all calls to proc.
991 proc_->SignalMultiple(requests_.size());
992 // Run until the re-started requests finish.
993 EXPECT_EQ(OK, requests_[3]->WaitForResult());
994 EXPECT_EQ(OK, requests_[4]->WaitForResult());
995 EXPECT_EQ(OK, requests_[5]->WaitForResult());
996 // Verify that results of aborted Jobs were not cached.
997 EXPECT_EQ(6u, proc_->GetCaptureList().size());
998 EXPECT_EQ(3u, resolver_->GetHostCache()->size());
1001 // Tests that when the maximum threads is set to 1, requests are dequeued
1002 // in order of priority.
1003 TEST_F(HostResolverImplTest, HigherPriorityRequestsStartedFirst) {
1004 CreateSerialResolver();
1006 // Note that at this point the MockHostResolverProc is blocked, so any
1007 // requests we make will not complete.
1008 CreateRequest("req0", 80, LOW);
1009 CreateRequest("req1", 80, MEDIUM);
1010 CreateRequest("req2", 80, MEDIUM);
1011 CreateRequest("req3", 80, LOW);
1012 CreateRequest("req4", 80, HIGHEST);
1013 CreateRequest("req5", 80, LOW);
1014 CreateRequest("req6", 80, LOW);
1015 CreateRequest("req5", 80, HIGHEST);
1017 for (size_t i = 0; i < requests_.size(); ++i) {
1018 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1021 // Unblock the resolver thread so the requests can run.
1022 proc_->SignalMultiple(requests_.size()); // More than needed.
1024 // Wait for all the requests to complete succesfully.
1025 for (size_t i = 0; i < requests_.size(); ++i) {
1026 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1029 // Since we have restricted to a single concurrent thread in the jobpool,
1030 // the requests should complete in order of priority (with the exception
1031 // of the first request, which gets started right away, since there is
1032 // nothing outstanding).
1033 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1034 ASSERT_EQ(7u, capture_list.size());
1036 EXPECT_EQ("req0", capture_list[0].hostname);
1037 EXPECT_EQ("req4", capture_list[1].hostname);
1038 EXPECT_EQ("req5", capture_list[2].hostname);
1039 EXPECT_EQ("req1", capture_list[3].hostname);
1040 EXPECT_EQ("req2", capture_list[4].hostname);
1041 EXPECT_EQ("req3", capture_list[5].hostname);
1042 EXPECT_EQ("req6", capture_list[6].hostname);
1045 // Try cancelling a job which has not started yet.
1046 TEST_F(HostResolverImplTest, CancelPendingRequest) {
1047 CreateSerialResolver();
1049 CreateRequest("req0", 80, LOWEST);
1050 CreateRequest("req1", 80, HIGHEST); // Will cancel.
1051 CreateRequest("req2", 80, MEDIUM);
1052 CreateRequest("req3", 80, LOW);
1053 CreateRequest("req4", 80, HIGHEST); // Will cancel.
1054 CreateRequest("req5", 80, LOWEST); // Will cancel.
1055 CreateRequest("req6", 80, MEDIUM);
1057 // Start all of the requests.
1058 for (size_t i = 0; i < requests_.size(); ++i) {
1059 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1062 // Cancel some requests
1063 requests_[1]->Cancel();
1064 requests_[4]->Cancel();
1065 requests_[5]->Cancel();
1067 // Unblock the resolver thread so the requests can run.
1068 proc_->SignalMultiple(requests_.size()); // More than needed.
1070 // Wait for all the requests to complete succesfully.
1071 for (size_t i = 0; i < requests_.size(); ++i) {
1072 if (!requests_[i]->pending())
1073 continue; // Don't wait for the requests we cancelled.
1074 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1077 // Verify that they called out the the resolver proc (which runs on the
1078 // resolver thread) in the expected order.
1079 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1080 ASSERT_EQ(4u, capture_list.size());
1082 EXPECT_EQ("req0", capture_list[0].hostname);
1083 EXPECT_EQ("req2", capture_list[1].hostname);
1084 EXPECT_EQ("req6", capture_list[2].hostname);
1085 EXPECT_EQ("req3", capture_list[3].hostname);
1088 // Test that when too many requests are enqueued, old ones start to be aborted.
1089 TEST_F(HostResolverImplTest, QueueOverflow) {
1090 CreateSerialResolver();
1092 // Allow only 3 queued jobs.
1093 const size_t kMaxPendingJobs = 3u;
1094 resolver_->SetMaxQueuedJobs(kMaxPendingJobs);
1096 // Note that at this point the MockHostResolverProc is blocked, so any
1097 // requests we make will not complete.
1099 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req0", 80, LOWEST)->Resolve());
1100 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req1", 80, HIGHEST)->Resolve());
1101 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req2", 80, MEDIUM)->Resolve());
1102 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req3", 80, MEDIUM)->Resolve());
1104 // At this point, there are 3 enqueued jobs.
1105 // Insertion of subsequent requests will cause evictions
1106 // based on priority.
1108 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE,
1109 CreateRequest("req4", 80, LOW)->Resolve()); // Evicts itself!
1111 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req5", 80, MEDIUM)->Resolve());
1112 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[2]->result());
1113 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req6", 80, HIGHEST)->Resolve());
1114 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[3]->result());
1115 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req7", 80, MEDIUM)->Resolve());
1116 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[5]->result());
1118 // Unblock the resolver thread so the requests can run.
1119 proc_->SignalMultiple(4u);
1121 // The rest should succeed.
1122 EXPECT_EQ(OK, requests_[7]->WaitForResult());
1123 EXPECT_EQ(OK, requests_[0]->result());
1124 EXPECT_EQ(OK, requests_[1]->result());
1125 EXPECT_EQ(OK, requests_[6]->result());
1127 // Verify that they called out the the resolver proc (which runs on the
1128 // resolver thread) in the expected order.
1129 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1130 ASSERT_EQ(4u, capture_list.size());
1132 EXPECT_EQ("req0", capture_list[0].hostname);
1133 EXPECT_EQ("req1", capture_list[1].hostname);
1134 EXPECT_EQ("req6", capture_list[2].hostname);
1135 EXPECT_EQ("req7", capture_list[3].hostname);
1137 // Verify that the evicted (incomplete) requests were not cached.
1138 EXPECT_EQ(4u, resolver_->GetHostCache()->size());
1140 for (size_t i = 0; i < requests_.size(); ++i) {
1141 EXPECT_TRUE(requests_[i]->completed()) << i;
1145 // Tests that after changing the default AddressFamily to IPV4, requests
1146 // with UNSPECIFIED address family map to IPV4.
1147 TEST_F(HostResolverImplTest, SetDefaultAddressFamily_IPv4) {
1148 CreateSerialResolver(); // To guarantee order of resolutions.
1150 proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1");
1151 proc_->AddRule("h1", ADDRESS_FAMILY_IPV6, "::2");
1153 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1155 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1156 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1157 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1159 // Start all of the requests.
1160 for (size_t i = 0; i < requests_.size(); ++i) {
1161 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1164 proc_->SignalMultiple(requests_.size());
1166 // Wait for all the requests to complete.
1167 for (size_t i = 0u; i < requests_.size(); ++i) {
1168 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1171 // Since the requests all had the same priority and we limited the thread
1172 // count to 1, they should have completed in the same order as they were
1173 // requested. Moreover, request0 and request1 will have been serviced by
1174 // the same job.
1176 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1177 ASSERT_EQ(2u, capture_list.size());
1179 EXPECT_EQ("h1", capture_list[0].hostname);
1180 EXPECT_EQ(ADDRESS_FAMILY_IPV4, capture_list[0].address_family);
1182 EXPECT_EQ("h1", capture_list[1].hostname);
1183 EXPECT_EQ(ADDRESS_FAMILY_IPV6, capture_list[1].address_family);
1185 // Now check that the correct resolved IP addresses were returned.
1186 EXPECT_TRUE(requests_[0]->HasOneAddress("1.0.0.1", 80));
1187 EXPECT_TRUE(requests_[1]->HasOneAddress("1.0.0.1", 80));
1188 EXPECT_TRUE(requests_[2]->HasOneAddress("::2", 80));
1191 // This is the exact same test as SetDefaultAddressFamily_IPv4, except the
1192 // default family is set to IPv6 and the family of requests is flipped where
1193 // specified.
1194 TEST_F(HostResolverImplTest, SetDefaultAddressFamily_IPv6) {
1195 CreateSerialResolver(); // To guarantee order of resolutions.
1197 // Don't use IPv6 replacements here since some systems don't support it.
1198 proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1");
1199 proc_->AddRule("h1", ADDRESS_FAMILY_IPV6, "::2");
1201 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV6);
1203 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1204 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1205 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1207 // Start all of the requests.
1208 for (size_t i = 0; i < requests_.size(); ++i) {
1209 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1212 proc_->SignalMultiple(requests_.size());
1214 // Wait for all the requests to complete.
1215 for (size_t i = 0u; i < requests_.size(); ++i) {
1216 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1219 // Since the requests all had the same priority and we limited the thread
1220 // count to 1, they should have completed in the same order as they were
1221 // requested. Moreover, request0 and request1 will have been serviced by
1222 // the same job.
1224 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1225 ASSERT_EQ(2u, capture_list.size());
1227 EXPECT_EQ("h1", capture_list[0].hostname);
1228 EXPECT_EQ(ADDRESS_FAMILY_IPV6, capture_list[0].address_family);
1230 EXPECT_EQ("h1", capture_list[1].hostname);
1231 EXPECT_EQ(ADDRESS_FAMILY_IPV4, capture_list[1].address_family);
1233 // Now check that the correct resolved IP addresses were returned.
1234 EXPECT_TRUE(requests_[0]->HasOneAddress("::2", 80));
1235 EXPECT_TRUE(requests_[1]->HasOneAddress("::2", 80));
1236 EXPECT_TRUE(requests_[2]->HasOneAddress("1.0.0.1", 80));
1239 TEST_F(HostResolverImplTest, ResolveFromCache) {
1240 proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
1241 proc_->SignalMultiple(1u); // Need only one.
1243 HostResolver::RequestInfo info(HostPortPair("just.testing", 80));
1245 // First hit will miss the cache.
1246 EXPECT_EQ(ERR_DNS_CACHE_MISS,
1247 CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache());
1249 // This time, we fetch normally.
1250 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info, DEFAULT_PRIORITY)->Resolve());
1251 EXPECT_EQ(OK, requests_[1]->WaitForResult());
1253 // Now we should be able to fetch from the cache.
1254 EXPECT_EQ(OK, CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache());
1255 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.1.42", 80));
1258 // Test the retry attempts simulating host resolver proc that takes too long.
1259 TEST_F(HostResolverImplTest, MultipleAttempts) {
1260 // Total number of attempts would be 3 and we want the 3rd attempt to resolve
1261 // the host. First and second attempt will be forced to sleep until they get
1262 // word that a resolution has completed. The 3rd resolution attempt will try
1263 // to get done ASAP, and won't sleep..
1264 int kAttemptNumberToResolve = 3;
1265 int kTotalAttempts = 3;
1267 scoped_refptr<LookupAttemptHostResolverProc> resolver_proc(
1268 new LookupAttemptHostResolverProc(
1269 NULL, kAttemptNumberToResolve, kTotalAttempts));
1271 HostResolverImpl::ProcTaskParams params = DefaultParams(resolver_proc.get());
1273 // Specify smaller interval for unresponsive_delay_ for HostResolverImpl so
1274 // that unit test runs faster. For example, this test finishes in 1.5 secs
1275 // (500ms * 3).
1276 params.unresponsive_delay = base::TimeDelta::FromMilliseconds(500);
1278 resolver_.reset(new HostResolverImpl(DefaultOptions(), NULL));
1279 resolver_->set_proc_params_for_test(params);
1281 // Resolve "host1".
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);
1300 EXPECT_TRUE(rv);
1302 DnsConfig config;
1303 config.nameservers.push_back(IPEndPoint(dns_ip, dns_protocol::kDefaultPort));
1304 EXPECT_TRUE(config.IsValid());
1305 return config;
1308 // Specialized fixture for tests of DnsTask.
1309 class HostResolverImplDnsTest : public HostResolverImplTest {
1310 public:
1311 HostResolverImplDnsTest() : dns_client_(NULL) {}
1313 protected:
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,
1328 false);
1330 AddDnsRule("slow_nx", dns_protocol::kTypeA, MockDnsClientRule::FAIL, true);
1331 AddDnsRule("slow_nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL,
1332 true);
1334 AddDnsRule("4slow_ok", dns_protocol::kTypeA, MockDnsClientRule::OK, true);
1335 AddDnsRule("4slow_ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1336 false);
1337 AddDnsRule("6slow_ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1338 AddDnsRule("6slow_ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1339 true);
1340 AddDnsRule("4slow_4ok", dns_protocol::kTypeA, MockDnsClientRule::OK, true);
1341 AddDnsRule("4slow_4ok", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY,
1342 false);
1343 AddDnsRule("4slow_4timeout", dns_protocol::kTypeA,
1344 MockDnsClientRule::TIMEOUT, true);
1345 AddDnsRule("4slow_4timeout", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1346 false);
1347 AddDnsRule("4slow_6timeout", dns_protocol::kTypeA,
1348 MockDnsClientRule::OK, true);
1349 AddDnsRule("4slow_6timeout", dns_protocol::kTypeAAAA,
1350 MockDnsClientRule::TIMEOUT, false);
1351 CreateResolver();
1354 // HostResolverImplTest implementation:
1355 virtual void CreateResolverWithLimitsAndParams(
1356 size_t max_concurrent_resolves,
1357 const HostResolverImpl::ProcTaskParams& params) OVERRIDE {
1358 HostResolverImpl::Options options = DefaultOptions();
1359 options.max_concurrent_resolves = max_concurrent_resolves;
1360 resolver_.reset(new HostResolverImpl(options, NULL));
1361 resolver_->set_proc_params_for_test(params);
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,
1370 uint16 qtype,
1371 MockDnsClientRule::Result result,
1372 bool delay) {
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.
1478 CreateResolver();
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.
1491 CreateResolver();
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));
1542 DnsHosts hosts;
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(DefaultOptions(), NULL));
1692 resolver_->set_proc_params_for_test(DefaultParams(proc.get()));
1694 resolver_->SetDnsClient(
1695 scoped_ptr<DnsClient>(new MockDnsClient(DnsConfig(), dns_rules_)));
1696 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1698 // Get the expected output.
1699 AddressList addrlist;
1700 int rv = proc->Resolve("localhost", ADDRESS_FAMILY_UNSPECIFIED, 0, &addrlist,
1701 NULL);
1702 if (rv != OK)
1703 return;
1705 for (unsigned i = 0; i < addrlist.size(); ++i)
1706 LOG(WARNING) << addrlist[i].ToString();
1708 bool saw_ipv4 = AddressListContains(addrlist, "127.0.0.1", 0);
1709 bool saw_ipv6 = AddressListContains(addrlist, "::1", 0);
1710 if (!saw_ipv4 && !saw_ipv6)
1711 return;
1713 HostResolver::RequestInfo info(HostPortPair("localhost", 80));
1714 info.set_address_family(ADDRESS_FAMILY_UNSPECIFIED);
1715 info.set_host_resolver_flags(HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6);
1717 // Try without DnsClient.
1718 ChangeDnsConfig(DnsConfig());
1719 Request* req = CreateRequest(info, DEFAULT_PRIORITY);
1720 // It is resolved via getaddrinfo, so expect asynchronous result.
1721 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1722 EXPECT_EQ(OK, req->WaitForResult());
1724 EXPECT_EQ(saw_ipv4, req->HasAddress("127.0.0.1", 80));
1725 EXPECT_EQ(saw_ipv6, req->HasAddress("::1", 80));
1727 // Configure DnsClient with dual-host HOSTS file.
1728 DnsConfig config = CreateValidDnsConfig();
1729 DnsHosts hosts;
1730 IPAddressNumber local_ipv4, local_ipv6;
1731 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4));
1732 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6));
1733 if (saw_ipv4)
1734 hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4)] = local_ipv4;
1735 if (saw_ipv6)
1736 hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV6)] = local_ipv6;
1737 config.hosts = hosts;
1739 ChangeDnsConfig(config);
1740 req = CreateRequest(info, DEFAULT_PRIORITY);
1741 // Expect synchronous resolution from DnsHosts.
1742 EXPECT_EQ(OK, req->Resolve());
1744 EXPECT_EQ(saw_ipv4, req->HasAddress("127.0.0.1", 80));
1745 EXPECT_EQ(saw_ipv6, req->HasAddress("::1", 80));
1748 // Cancel a request with a single DNS transaction active.
1749 TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActive) {
1750 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4);
1751 ChangeDnsConfig(CreateValidDnsConfig());
1753 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1754 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1755 requests_[0]->Cancel();
1757 // Dispatcher state checked in TearDown.
1760 // Cancel a request with a single DNS transaction active and another pending.
1761 TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActiveOnePending) {
1762 CreateSerialResolver();
1763 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1764 ChangeDnsConfig(CreateValidDnsConfig());
1766 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1767 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1768 requests_[0]->Cancel();
1770 // Dispatcher state checked in TearDown.
1773 // Cancel a request with two DNS transactions active.
1774 TEST_F(HostResolverImplDnsTest, CancelWithTwoTransactionsActive) {
1775 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1776 ChangeDnsConfig(CreateValidDnsConfig());
1778 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1779 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1780 requests_[0]->Cancel();
1782 // Dispatcher state checked in TearDown.
1785 // Delete a resolver with some active requests and some queued requests.
1786 TEST_F(HostResolverImplDnsTest, DeleteWithActiveTransactions) {
1787 // At most 10 Jobs active at once.
1788 CreateResolverWithLimitsAndParams(10u, DefaultParams(proc_.get()));
1790 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1791 ChangeDnsConfig(CreateValidDnsConfig());
1793 // First active job is an IPv4 request.
1794 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM,
1795 ADDRESS_FAMILY_IPV4)->Resolve());
1797 // Add 10 more DNS lookups for different hostnames. First 4 should have two
1798 // active jobs, next one has a single active job, and one pending. Others
1799 // should all be queued.
1800 for (int i = 0; i < 10; ++i) {
1801 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(
1802 base::StringPrintf("ok%i", i))->Resolve());
1804 EXPECT_EQ(10u, num_running_dispatcher_jobs());
1806 resolver_.reset();
1809 // Cancel a request with only the IPv6 transaction active.
1810 TEST_F(HostResolverImplDnsTest, CancelWithIPv6TransactionActive) {
1811 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1812 ChangeDnsConfig(CreateValidDnsConfig());
1814 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("6slow_ok", 80)->Resolve());
1815 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1817 // The IPv4 request should complete, the IPv6 request is still pending.
1818 base::RunLoop().RunUntilIdle();
1819 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1820 requests_[0]->Cancel();
1822 // Dispatcher state checked in TearDown.
1825 // Cancel a request with only the IPv4 transaction pending.
1826 TEST_F(HostResolverImplDnsTest, CancelWithIPv4TransactionPending) {
1827 set_fallback_to_proctask(false);
1828 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1829 ChangeDnsConfig(CreateValidDnsConfig());
1831 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_ok", 80)->Resolve());
1832 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1834 // The IPv6 request should complete, the IPv4 request is still pending.
1835 base::RunLoop().RunUntilIdle();
1836 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1838 requests_[0]->Cancel();
1841 // Test cases where AAAA completes first.
1842 TEST_F(HostResolverImplDnsTest, AAAACompletesFirst) {
1843 set_fallback_to_proctask(false);
1844 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1845 ChangeDnsConfig(CreateValidDnsConfig());
1847 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_ok", 80)->Resolve());
1848 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_4ok", 80)->Resolve());
1849 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_4timeout", 80)->Resolve());
1850 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_6timeout", 80)->Resolve());
1852 base::RunLoop().RunUntilIdle();
1853 EXPECT_FALSE(requests_[0]->completed());
1854 EXPECT_FALSE(requests_[1]->completed());
1855 EXPECT_FALSE(requests_[2]->completed());
1856 // The IPv6 of the third request should have failed and resulted in cancelling
1857 // the IPv4 request.
1858 EXPECT_TRUE(requests_[3]->completed());
1859 EXPECT_EQ(ERR_DNS_TIMED_OUT, requests_[3]->result());
1860 EXPECT_EQ(3u, num_running_dispatcher_jobs());
1862 dns_client_->CompleteDelayedTransactions();
1863 EXPECT_TRUE(requests_[0]->completed());
1864 EXPECT_EQ(OK, requests_[0]->result());
1865 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses());
1866 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80));
1867 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80));
1869 EXPECT_TRUE(requests_[1]->completed());
1870 EXPECT_EQ(OK, requests_[1]->result());
1871 EXPECT_EQ(1u, requests_[1]->NumberOfAddresses());
1872 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80));
1874 EXPECT_TRUE(requests_[2]->completed());
1875 EXPECT_EQ(ERR_DNS_TIMED_OUT, requests_[2]->result());
1878 // Test the case where only a single transaction slot is available.
1879 TEST_F(HostResolverImplDnsTest, SerialResolver) {
1880 CreateSerialResolver();
1881 set_fallback_to_proctask(false);
1882 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1883 ChangeDnsConfig(CreateValidDnsConfig());
1885 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1886 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1888 base::RunLoop().RunUntilIdle();
1889 EXPECT_TRUE(requests_[0]->completed());
1890 EXPECT_EQ(OK, requests_[0]->result());
1891 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses());
1892 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80));
1893 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80));
1896 // Test the case where the AAAA query is started when another transaction
1897 // completes.
1898 TEST_F(HostResolverImplDnsTest, AAAAStartsAfterOtherJobFinishes) {
1899 CreateResolverWithLimitsAndParams(2u, DefaultParams(proc_.get()));
1900 set_fallback_to_proctask(false);
1901 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1902 ChangeDnsConfig(CreateValidDnsConfig());
1904 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM,
1905 ADDRESS_FAMILY_IPV4)->Resolve());
1906 EXPECT_EQ(ERR_IO_PENDING,
1907 CreateRequest("4slow_ok", 80, MEDIUM)->Resolve());
1908 // An IPv4 request should have been started pending for each job.
1909 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1911 // Request 0's IPv4 request should complete, starting Request 1's IPv6
1912 // request, which should also complete.
1913 base::RunLoop().RunUntilIdle();
1914 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1915 EXPECT_TRUE(requests_[0]->completed());
1916 EXPECT_FALSE(requests_[1]->completed());
1918 dns_client_->CompleteDelayedTransactions();
1919 EXPECT_TRUE(requests_[1]->completed());
1920 EXPECT_EQ(OK, requests_[1]->result());
1921 EXPECT_EQ(2u, requests_[1]->NumberOfAddresses());
1922 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80));
1923 EXPECT_TRUE(requests_[1]->HasAddress("::1", 80));
1926 // Tests the case that a Job with a single transaction receives an empty address
1927 // list, triggering fallback to ProcTask.
1928 TEST_F(HostResolverImplDnsTest, IPv4EmptyFallback) {
1929 ChangeDnsConfig(CreateValidDnsConfig());
1930 proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
1931 proc_->SignalMultiple(1u);
1932 EXPECT_EQ(ERR_IO_PENDING,
1933 CreateRequest("empty_fallback", 80, MEDIUM,
1934 ADDRESS_FAMILY_IPV4)->Resolve());
1935 EXPECT_EQ(OK, requests_[0]->WaitForResult());
1936 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
1939 // Tests the case that a Job with two transactions receives two empty address
1940 // lists, triggering fallback to ProcTask.
1941 TEST_F(HostResolverImplDnsTest, UnspecEmptyFallback) {
1942 ChangeDnsConfig(CreateValidDnsConfig());
1943 proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
1944 proc_->SignalMultiple(1u);
1945 EXPECT_EQ(ERR_IO_PENDING,
1946 CreateRequest("empty_fallback", 80, MEDIUM,
1947 ADDRESS_FAMILY_UNSPECIFIED)->Resolve());
1948 EXPECT_EQ(OK, requests_[0]->WaitForResult());
1949 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
1952 // Tests getting a new invalid DnsConfig while there are active DnsTasks.
1953 TEST_F(HostResolverImplDnsTest, InvalidDnsConfigWithPendingRequests) {
1954 // At most 3 jobs active at once. This number is important, since we want to
1955 // make sure that aborting the first HostResolverImpl::Job does not trigger
1956 // another DnsTransaction on the second Job when it releases its second
1957 // prioritized dispatcher slot.
1958 CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_.get()));
1960 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
1961 ChangeDnsConfig(CreateValidDnsConfig());
1963 proc_->AddRuleForAllFamilies("slow_nx1", "192.168.0.1");
1964 proc_->AddRuleForAllFamilies("slow_nx2", "192.168.0.2");
1965 proc_->AddRuleForAllFamilies("ok", "192.168.0.3");
1967 // First active job gets two slots.
1968 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_nx1")->Resolve());
1969 // Next job gets one slot, and waits on another.
1970 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_nx2")->Resolve());
1971 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok")->Resolve());
1973 EXPECT_EQ(3u, num_running_dispatcher_jobs());
1975 // Clear DNS config. Two in-progress jobs should be aborted, and the next one
1976 // should use a ProcTask.
1977 ChangeDnsConfig(DnsConfig());
1978 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->WaitForResult());
1979 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[1]->WaitForResult());
1981 // Finish up the third job. Should bypass the DnsClient, and get its results
1982 // from MockHostResolverProc.
1983 EXPECT_FALSE(requests_[2]->completed());
1984 proc_->SignalMultiple(1u);
1985 EXPECT_EQ(OK, requests_[2]->WaitForResult());
1986 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80));
1989 // Tests the case that DnsClient is automatically disabled due to failures
1990 // while there are active DnsTasks.
1991 TEST_F(HostResolverImplDnsTest,
1992 AutomaticallyDisableDnsClientWithPendingRequests) {
1993 // Trying different limits is important for this test: Different limits
1994 // result in different behavior when aborting in-progress DnsTasks. Having
1995 // a DnsTask that has one job active and one in the queue when another job
1996 // occupying two slots has its DnsTask aborted is the case most likely to run
1997 // into problems.
1998 for (size_t limit = 1u; limit < 6u; ++limit) {
1999 CreateResolverWithLimitsAndParams(limit, DefaultParams(proc_.get()));
2001 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
2002 ChangeDnsConfig(CreateValidDnsConfig());
2004 // Queue up enough failures to disable DnsTasks. These will all fall back
2005 // to ProcTasks, and succeed there.
2006 for (unsigned i = 0u; i < maximum_dns_failures(); ++i) {
2007 std::string host = base::StringPrintf("nx%u", i);
2008 proc_->AddRuleForAllFamilies(host, "192.168.0.1");
2009 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(host)->Resolve());
2012 // These requests should all bypass DnsTasks, due to the above failures,
2013 // so should end up using ProcTasks.
2014 proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.2");
2015 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok1")->Resolve());
2016 proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.3");
2017 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok2")->Resolve());
2018 proc_->AddRuleForAllFamilies("slow_ok3", "192.168.0.4");
2019 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok3")->Resolve());
2020 proc_->SignalMultiple(maximum_dns_failures() + 3);
2022 for (size_t i = 0u; i < maximum_dns_failures(); ++i) {
2023 EXPECT_EQ(OK, requests_[i]->WaitForResult());
2024 EXPECT_TRUE(requests_[i]->HasOneAddress("192.168.0.1", 80));
2027 EXPECT_EQ(OK, requests_[maximum_dns_failures()]->WaitForResult());
2028 EXPECT_TRUE(requests_[maximum_dns_failures()]->HasOneAddress(
2029 "192.168.0.2", 80));
2030 EXPECT_EQ(OK, requests_[maximum_dns_failures() + 1]->WaitForResult());
2031 EXPECT_TRUE(requests_[maximum_dns_failures() + 1]->HasOneAddress(
2032 "192.168.0.3", 80));
2033 EXPECT_EQ(OK, requests_[maximum_dns_failures() + 2]->WaitForResult());
2034 EXPECT_TRUE(requests_[maximum_dns_failures() + 2]->HasOneAddress(
2035 "192.168.0.4", 80));
2036 requests_.clear();
2040 // Tests a call to SetDnsClient while there are active DnsTasks.
2041 TEST_F(HostResolverImplDnsTest, ManuallyDisableDnsClientWithPendingRequests) {
2042 // At most 3 jobs active at once. This number is important, since we want to
2043 // make sure that aborting the first HostResolverImpl::Job does not trigger
2044 // another DnsTransaction on the second Job when it releases its second
2045 // prioritized dispatcher slot.
2046 CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_.get()));
2048 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED);
2049 ChangeDnsConfig(CreateValidDnsConfig());
2051 proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.1");
2052 proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.2");
2053 proc_->AddRuleForAllFamilies("ok", "192.168.0.3");
2055 // First active job gets two slots.
2056 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok1")->Resolve());
2057 // Next job gets one slot, and waits on another.
2058 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok2")->Resolve());
2059 // Next one is queued.
2060 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok")->Resolve());
2062 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2064 // Clear DnsClient. The two in-progress jobs should fall back to a ProcTask,
2065 // and the next one should be started with a ProcTask.
2066 resolver_->SetDnsClient(scoped_ptr<DnsClient>());
2068 // All three in-progress requests should now be running a ProcTask.
2069 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2070 proc_->SignalMultiple(3u);
2072 EXPECT_EQ(OK, requests_[0]->WaitForResult());
2073 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
2074 EXPECT_EQ(OK, requests_[1]->WaitForResult());
2075 EXPECT_TRUE(requests_[1]->HasOneAddress("192.168.0.2", 80));
2076 EXPECT_EQ(OK, requests_[2]->WaitForResult());
2077 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80));
2080 } // namespace net