Switch global error menu icon to vectorized MD asset
[chromium-blink-merge.git] / net / dns / host_resolver_impl_unittest.cc
blob2ab20b71378c5ca957a48d1a14679a236e5e8281
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/location.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_vector.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/run_loop.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/synchronization/condition_variable.h"
21 #include "base/synchronization/lock.h"
22 #include "base/test/test_timeouts.h"
23 #include "base/thread_task_runner_handle.h"
24 #include "base/time/time.h"
25 #include "net/base/address_list.h"
26 #include "net/base/net_errors.h"
27 #include "net/base/net_util.h"
28 #include "net/dns/dns_client.h"
29 #include "net/dns/dns_test_util.h"
30 #include "net/dns/mock_host_resolver.h"
31 #include "net/log/test_net_log.h"
32 #include "testing/gtest/include/gtest/gtest.h"
34 namespace net {
36 namespace {
38 const size_t kMaxJobs = 10u;
39 const size_t kMaxRetryAttempts = 4u;
41 HostResolver::Options DefaultOptions() {
42 HostResolver::Options options;
43 options.max_concurrent_resolves = kMaxJobs;
44 options.max_retry_attempts = kMaxRetryAttempts;
45 options.enable_caching = true;
46 return options;
49 HostResolverImpl::ProcTaskParams DefaultParams(
50 HostResolverProc* resolver_proc) {
51 return HostResolverImpl::ProcTaskParams(resolver_proc, kMaxRetryAttempts);
54 // A HostResolverProc that pushes each host mapped into a list and allows
55 // waiting for a specific number of requests. Unlike RuleBasedHostResolverProc
56 // it never calls SystemHostResolverCall. By default resolves all hostnames to
57 // "127.0.0.1". After AddRule(), it resolves only names explicitly specified.
58 class MockHostResolverProc : public HostResolverProc {
59 public:
60 struct ResolveKey {
61 ResolveKey(const std::string& hostname, AddressFamily address_family)
62 : hostname(hostname), address_family(address_family) {}
63 bool operator<(const ResolveKey& other) const {
64 return address_family < other.address_family ||
65 (address_family == other.address_family && hostname < other.hostname);
67 std::string hostname;
68 AddressFamily address_family;
71 typedef std::vector<ResolveKey> CaptureList;
73 MockHostResolverProc()
74 : HostResolverProc(NULL),
75 num_requests_waiting_(0),
76 num_slots_available_(0),
77 requests_waiting_(&lock_),
78 slots_available_(&lock_) {
81 // Waits until |count| calls to |Resolve| are blocked. Returns false when
82 // timed out.
83 bool WaitFor(unsigned count) {
84 base::AutoLock lock(lock_);
85 base::Time start_time = base::Time::Now();
86 while (num_requests_waiting_ < count) {
87 requests_waiting_.TimedWait(TestTimeouts::action_timeout());
88 if (base::Time::Now() > start_time + TestTimeouts::action_timeout())
89 return false;
91 return true;
94 // Signals |count| waiting calls to |Resolve|. First come first served.
95 void SignalMultiple(unsigned count) {
96 base::AutoLock lock(lock_);
97 num_slots_available_ += count;
98 slots_available_.Broadcast();
101 // Signals all waiting calls to |Resolve|. Beware of races.
102 void SignalAll() {
103 base::AutoLock lock(lock_);
104 num_slots_available_ = num_requests_waiting_;
105 slots_available_.Broadcast();
108 void AddRule(const std::string& hostname, AddressFamily family,
109 const AddressList& result) {
110 base::AutoLock lock(lock_);
111 rules_[ResolveKey(hostname, family)] = result;
114 void AddRule(const std::string& hostname, AddressFamily family,
115 const std::string& ip_list) {
116 AddressList result;
117 int rv = ParseAddressList(ip_list, std::string(), &result);
118 DCHECK_EQ(OK, rv);
119 AddRule(hostname, family, result);
122 void AddRuleForAllFamilies(const std::string& hostname,
123 const std::string& ip_list) {
124 AddressList result;
125 int rv = ParseAddressList(ip_list, std::string(), &result);
126 DCHECK_EQ(OK, rv);
127 AddRule(hostname, ADDRESS_FAMILY_UNSPECIFIED, result);
128 AddRule(hostname, ADDRESS_FAMILY_IPV4, result);
129 AddRule(hostname, ADDRESS_FAMILY_IPV6, result);
132 int Resolve(const std::string& hostname,
133 AddressFamily address_family,
134 HostResolverFlags host_resolver_flags,
135 AddressList* addrlist,
136 int* os_error) override {
137 base::AutoLock lock(lock_);
138 capture_list_.push_back(ResolveKey(hostname, address_family));
139 ++num_requests_waiting_;
140 requests_waiting_.Broadcast();
141 while (!num_slots_available_)
142 slots_available_.Wait();
143 DCHECK_GT(num_requests_waiting_, 0u);
144 --num_slots_available_;
145 --num_requests_waiting_;
146 if (rules_.empty()) {
147 int rv = ParseAddressList("127.0.0.1", std::string(), addrlist);
148 DCHECK_EQ(OK, rv);
149 return OK;
151 ResolveKey key(hostname, address_family);
152 if (rules_.count(key) == 0)
153 return ERR_NAME_NOT_RESOLVED;
154 *addrlist = rules_[key];
155 return OK;
158 CaptureList GetCaptureList() const {
159 CaptureList copy;
161 base::AutoLock lock(lock_);
162 copy = capture_list_;
164 return copy;
167 bool HasBlockedRequests() const {
168 base::AutoLock lock(lock_);
169 return num_requests_waiting_ > num_slots_available_;
172 protected:
173 ~MockHostResolverProc() override {}
175 private:
176 mutable base::Lock lock_;
177 std::map<ResolveKey, AddressList> rules_;
178 CaptureList capture_list_;
179 unsigned num_requests_waiting_;
180 unsigned num_slots_available_;
181 base::ConditionVariable requests_waiting_;
182 base::ConditionVariable slots_available_;
184 DISALLOW_COPY_AND_ASSIGN(MockHostResolverProc);
187 bool AddressListContains(const AddressList& list, const std::string& address,
188 uint16 port) {
189 IPAddressNumber ip;
190 bool rv = ParseIPLiteralToNumber(address, &ip);
191 DCHECK(rv);
192 return std::find(list.begin(),
193 list.end(),
194 IPEndPoint(ip, port)) != list.end();
197 // A wrapper for requests to a HostResolver.
198 class Request {
199 public:
200 // Base class of handlers to be executed on completion of requests.
201 struct Handler {
202 virtual ~Handler() {}
203 virtual void Handle(Request* request) = 0;
206 Request(const HostResolver::RequestInfo& info,
207 RequestPriority priority,
208 size_t index,
209 HostResolver* resolver,
210 Handler* handler)
211 : info_(info),
212 priority_(priority),
213 index_(index),
214 resolver_(resolver),
215 handler_(handler),
216 quit_on_complete_(false),
217 result_(ERR_UNEXPECTED),
218 handle_(NULL) {}
220 int Resolve() {
221 DCHECK(resolver_);
222 DCHECK(!handle_);
223 list_ = AddressList();
224 result_ = resolver_->Resolve(
225 info_,
226 priority_,
227 &list_,
228 base::Bind(&Request::OnComplete, base::Unretained(this)),
229 &handle_,
230 BoundNetLog());
231 if (!list_.empty())
232 EXPECT_EQ(OK, result_);
233 return result_;
236 int ResolveFromCache() {
237 DCHECK(resolver_);
238 DCHECK(!handle_);
239 return resolver_->ResolveFromCache(info_, &list_, BoundNetLog());
242 void Cancel() {
243 DCHECK(resolver_);
244 DCHECK(handle_);
245 resolver_->CancelRequest(handle_);
246 handle_ = NULL;
249 const HostResolver::RequestInfo& info() const { return info_; }
250 size_t index() const { return index_; }
251 const AddressList& list() const { return list_; }
252 int result() const { return result_; }
253 bool completed() const { return result_ != ERR_IO_PENDING; }
254 bool pending() const { return handle_ != NULL; }
256 bool HasAddress(const std::string& address, uint16 port) const {
257 return AddressListContains(list_, address, port);
260 // Returns the number of addresses in |list_|.
261 unsigned NumberOfAddresses() const {
262 return list_.size();
265 bool HasOneAddress(const std::string& address, uint16 port) const {
266 return HasAddress(address, port) && (NumberOfAddresses() == 1u);
269 // Returns ERR_UNEXPECTED if timed out.
270 int WaitForResult() {
271 if (completed())
272 return result_;
273 base::CancelableClosure closure(base::MessageLoop::QuitClosure());
274 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
275 FROM_HERE, closure.callback(), TestTimeouts::action_max_timeout());
276 quit_on_complete_ = true;
277 base::MessageLoop::current()->Run();
278 bool did_quit = !quit_on_complete_;
279 quit_on_complete_ = false;
280 closure.Cancel();
281 if (did_quit)
282 return result_;
283 else
284 return ERR_UNEXPECTED;
287 private:
288 void OnComplete(int rv) {
289 EXPECT_TRUE(pending());
290 EXPECT_EQ(ERR_IO_PENDING, result_);
291 EXPECT_NE(ERR_IO_PENDING, rv);
292 result_ = rv;
293 handle_ = NULL;
294 if (!list_.empty()) {
295 EXPECT_EQ(OK, result_);
296 EXPECT_EQ(info_.port(), list_.front().port());
298 if (handler_)
299 handler_->Handle(this);
300 if (quit_on_complete_) {
301 base::MessageLoop::current()->Quit();
302 quit_on_complete_ = false;
306 HostResolver::RequestInfo info_;
307 RequestPriority priority_;
308 size_t index_;
309 HostResolver* resolver_;
310 Handler* handler_;
311 bool quit_on_complete_;
313 AddressList list_;
314 int result_;
315 HostResolver::RequestHandle handle_;
317 DISALLOW_COPY_AND_ASSIGN(Request);
320 // Using LookupAttemptHostResolverProc simulate very long lookups, and control
321 // which attempt resolves the host.
322 class LookupAttemptHostResolverProc : public HostResolverProc {
323 public:
324 LookupAttemptHostResolverProc(HostResolverProc* previous,
325 int attempt_number_to_resolve,
326 int total_attempts)
327 : HostResolverProc(previous),
328 attempt_number_to_resolve_(attempt_number_to_resolve),
329 current_attempt_number_(0),
330 total_attempts_(total_attempts),
331 total_attempts_resolved_(0),
332 resolved_attempt_number_(0),
333 all_done_(&lock_) {
336 // Test harness will wait for all attempts to finish before checking the
337 // results.
338 void WaitForAllAttemptsToFinish(const base::TimeDelta& wait_time) {
339 base::TimeTicks end_time = base::TimeTicks::Now() + wait_time;
341 base::AutoLock auto_lock(lock_);
342 while (total_attempts_resolved_ != total_attempts_ &&
343 base::TimeTicks::Now() < end_time) {
344 all_done_.TimedWait(end_time - base::TimeTicks::Now());
349 // All attempts will wait for an attempt to resolve the host.
350 void WaitForAnAttemptToComplete() {
351 base::TimeDelta wait_time = base::TimeDelta::FromSeconds(60);
352 base::TimeTicks end_time = base::TimeTicks::Now() + wait_time;
354 base::AutoLock auto_lock(lock_);
355 while (resolved_attempt_number_ == 0 && base::TimeTicks::Now() < end_time)
356 all_done_.TimedWait(end_time - base::TimeTicks::Now());
358 all_done_.Broadcast(); // Tell all waiting attempts to proceed.
361 // Returns the number of attempts that have finished the Resolve() method.
362 int total_attempts_resolved() { return total_attempts_resolved_; }
364 // Returns the first attempt that that has resolved the host.
365 int resolved_attempt_number() { return resolved_attempt_number_; }
367 // HostResolverProc methods.
368 int Resolve(const std::string& host,
369 AddressFamily address_family,
370 HostResolverFlags host_resolver_flags,
371 AddressList* addrlist,
372 int* os_error) override {
373 bool wait_for_right_attempt_to_complete = true;
375 base::AutoLock auto_lock(lock_);
376 ++current_attempt_number_;
377 if (current_attempt_number_ == attempt_number_to_resolve_) {
378 resolved_attempt_number_ = current_attempt_number_;
379 wait_for_right_attempt_to_complete = false;
383 if (wait_for_right_attempt_to_complete)
384 // Wait for the attempt_number_to_resolve_ attempt to resolve.
385 WaitForAnAttemptToComplete();
387 int result = ResolveUsingPrevious(host, address_family, host_resolver_flags,
388 addrlist, os_error);
391 base::AutoLock auto_lock(lock_);
392 ++total_attempts_resolved_;
395 all_done_.Broadcast(); // Tell all attempts to proceed.
397 // Since any negative number is considered a network error, with -1 having
398 // special meaning (ERR_IO_PENDING). We could return the attempt that has
399 // resolved the host as a negative number. For example, if attempt number 3
400 // resolves the host, then this method returns -4.
401 if (result == OK)
402 return -1 - resolved_attempt_number_;
403 else
404 return result;
407 protected:
408 ~LookupAttemptHostResolverProc() override {}
410 private:
411 int attempt_number_to_resolve_;
412 int current_attempt_number_; // Incremented whenever Resolve is called.
413 int total_attempts_;
414 int total_attempts_resolved_;
415 int resolved_attempt_number_;
417 // All attempts wait for right attempt to be resolve.
418 base::Lock lock_;
419 base::ConditionVariable all_done_;
422 // TestHostResolverImpl's sole purpose is to mock the IPv6 reachability test.
423 // By default, this pretends that IPv6 is globally reachable.
424 // This class is necessary so unit tests run the same on dual-stack machines as
425 // well as IPv4 only machines.
426 class TestHostResolverImpl : public HostResolverImpl {
427 public:
428 TestHostResolverImpl(const Options& options, NetLog* net_log)
429 : TestHostResolverImpl(options, net_log, true) {}
431 TestHostResolverImpl(const Options& options,
432 NetLog* net_log,
433 bool ipv6_reachable)
434 : HostResolverImpl(options, net_log), ipv6_reachable_(ipv6_reachable) {}
436 ~TestHostResolverImpl() override {}
438 private:
439 const bool ipv6_reachable_;
441 bool IsIPv6Reachable(const BoundNetLog& net_log) override {
442 return ipv6_reachable_;
446 } // namespace
448 class HostResolverImplTest : public testing::Test {
449 public:
450 static const int kDefaultPort = 80;
452 HostResolverImplTest() : proc_(new MockHostResolverProc()) {}
454 void CreateResolver() {
455 CreateResolverWithLimitsAndParams(kMaxJobs,
456 DefaultParams(proc_.get()));
459 // This HostResolverImpl will only allow 1 outstanding resolve at a time and
460 // perform no retries.
461 void CreateSerialResolver() {
462 HostResolverImpl::ProcTaskParams params = DefaultParams(proc_.get());
463 params.max_retry_attempts = 0u;
464 CreateResolverWithLimitsAndParams(1u, params);
467 protected:
468 // A Request::Handler which is a proxy to the HostResolverImplTest fixture.
469 struct Handler : public Request::Handler {
470 ~Handler() override {}
472 // Proxy functions so that classes derived from Handler can access them.
473 Request* CreateRequest(const HostResolver::RequestInfo& info,
474 RequestPriority priority) {
475 return test->CreateRequest(info, priority);
477 Request* CreateRequest(const std::string& hostname, int port) {
478 return test->CreateRequest(hostname, port);
480 Request* CreateRequest(const std::string& hostname) {
481 return test->CreateRequest(hostname);
483 ScopedVector<Request>& requests() { return test->requests_; }
485 void DeleteResolver() { test->resolver_.reset(); }
487 HostResolverImplTest* test;
490 // testing::Test implementation:
491 void SetUp() override { CreateResolver(); }
493 void TearDown() override {
494 if (resolver_.get())
495 EXPECT_EQ(0u, resolver_->num_running_dispatcher_jobs_for_tests());
496 EXPECT_FALSE(proc_->HasBlockedRequests());
499 virtual void CreateResolverWithLimitsAndParams(
500 size_t max_concurrent_resolves,
501 const HostResolverImpl::ProcTaskParams& params) {
502 HostResolverImpl::Options options = DefaultOptions();
503 options.max_concurrent_resolves = max_concurrent_resolves;
504 resolver_.reset(new TestHostResolverImpl(options, NULL));
505 resolver_->set_proc_params_for_test(params);
508 // The Request will not be made until a call to |Resolve()|, and the Job will
509 // not start until released by |proc_->SignalXXX|.
510 Request* CreateRequest(const HostResolver::RequestInfo& info,
511 RequestPriority priority) {
512 Request* req = new Request(
513 info, priority, requests_.size(), resolver_.get(), handler_.get());
514 requests_.push_back(req);
515 return req;
518 Request* CreateRequest(const std::string& hostname,
519 int port,
520 RequestPriority priority,
521 AddressFamily family) {
522 HostResolver::RequestInfo info(HostPortPair(hostname, port));
523 info.set_address_family(family);
524 return CreateRequest(info, priority);
527 Request* CreateRequest(const std::string& hostname,
528 int port,
529 RequestPriority priority) {
530 return CreateRequest(hostname, port, priority, ADDRESS_FAMILY_UNSPECIFIED);
533 Request* CreateRequest(const std::string& hostname, int port) {
534 return CreateRequest(hostname, port, MEDIUM);
537 Request* CreateRequest(const std::string& hostname) {
538 return CreateRequest(hostname, kDefaultPort);
541 void set_handler(Handler* handler) {
542 handler_.reset(handler);
543 handler_->test = this;
546 // Friendship is not inherited, so use proxies to access those.
547 size_t num_running_dispatcher_jobs() const {
548 DCHECK(resolver_.get());
549 return resolver_->num_running_dispatcher_jobs_for_tests();
552 void set_fallback_to_proctask(bool fallback_to_proctask) {
553 DCHECK(resolver_.get());
554 resolver_->fallback_to_proctask_ = fallback_to_proctask;
557 static unsigned maximum_dns_failures() {
558 return HostResolverImpl::kMaximumDnsFailures;
561 bool IsIPv6Reachable(const BoundNetLog& net_log) {
562 return resolver_->IsIPv6Reachable(net_log);
565 scoped_refptr<MockHostResolverProc> proc_;
566 scoped_ptr<HostResolverImpl> resolver_;
567 ScopedVector<Request> requests_;
569 scoped_ptr<Handler> handler_;
572 TEST_F(HostResolverImplTest, AsynchronousLookup) {
573 proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
574 proc_->SignalMultiple(1u);
576 Request* req = CreateRequest("just.testing", 80);
577 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
578 EXPECT_EQ(OK, req->WaitForResult());
580 EXPECT_TRUE(req->HasOneAddress("192.168.1.42", 80));
582 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
585 // RFC 6761 localhost names should always resolve to loopback.
586 TEST_F(HostResolverImplTest, LocalhostLookup) {
587 // Add a rule resolving localhost names to a non-loopback IP and test
588 // that they still resolves to loopback.
589 proc_->AddRuleForAllFamilies("foo.localhost", "192.168.1.42");
590 proc_->AddRuleForAllFamilies("localhost", "192.168.1.42");
591 proc_->AddRuleForAllFamilies("localhost.", "192.168.1.42");
593 Request* req0 = CreateRequest("foo.localhost", 80);
594 EXPECT_EQ(OK, req0->Resolve());
595 EXPECT_TRUE(req0->HasAddress("127.0.0.1", 80));
596 EXPECT_TRUE(req0->HasAddress("::1", 80));
598 Request* req1 = CreateRequest("localhost", 80);
599 EXPECT_EQ(OK, req1->Resolve());
600 EXPECT_TRUE(req1->HasAddress("127.0.0.1", 80));
601 EXPECT_TRUE(req1->HasAddress("::1", 80));
603 Request* req2 = CreateRequest("localhost.", 80);
604 EXPECT_EQ(OK, req2->Resolve());
605 EXPECT_TRUE(req2->HasAddress("127.0.0.1", 80));
606 EXPECT_TRUE(req2->HasAddress("::1", 80));
609 TEST_F(HostResolverImplTest, LocalhostIPV4IPV6Lookup) {
610 Request* req1 = CreateRequest("localhost6", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
611 EXPECT_EQ(OK, req1->Resolve());
612 EXPECT_EQ(0u, req1->NumberOfAddresses());
614 Request* req2 = CreateRequest("localhost6", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
615 EXPECT_EQ(OK, req2->Resolve());
616 EXPECT_TRUE(req2->HasOneAddress("::1", 80));
618 Request* req3 =
619 CreateRequest("localhost6", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
620 EXPECT_EQ(OK, req3->Resolve());
621 EXPECT_TRUE(req3->HasOneAddress("::1", 80));
623 Request* req4 = CreateRequest("localhost", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
624 EXPECT_EQ(OK, req4->Resolve());
625 EXPECT_TRUE(req4->HasOneAddress("127.0.0.1", 80));
627 Request* req5 = CreateRequest("localhost", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
628 EXPECT_EQ(OK, req5->Resolve());
629 EXPECT_TRUE(req5->HasOneAddress("::1", 80));
632 TEST_F(HostResolverImplTest, EmptyListMeansNameNotResolved) {
633 proc_->AddRuleForAllFamilies("just.testing", "");
634 proc_->SignalMultiple(1u);
636 Request* req = CreateRequest("just.testing", 80);
637 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
638 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult());
639 EXPECT_EQ(0u, req->NumberOfAddresses());
640 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
643 TEST_F(HostResolverImplTest, FailedAsynchronousLookup) {
644 proc_->AddRuleForAllFamilies(std::string(),
645 "0.0.0.0"); // Default to failures.
646 proc_->SignalMultiple(1u);
648 Request* req = CreateRequest("just.testing", 80);
649 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
650 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult());
652 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname);
654 // Also test that the error is not cached.
655 EXPECT_EQ(ERR_DNS_CACHE_MISS, req->ResolveFromCache());
658 TEST_F(HostResolverImplTest, AbortedAsynchronousLookup) {
659 Request* req0 = CreateRequest("just.testing", 80);
660 EXPECT_EQ(ERR_IO_PENDING, req0->Resolve());
662 EXPECT_TRUE(proc_->WaitFor(1u));
664 // Resolver is destroyed while job is running on WorkerPool.
665 resolver_.reset();
667 proc_->SignalAll();
669 // To ensure there was no spurious callback, complete with a new resolver.
670 CreateResolver();
671 Request* req1 = CreateRequest("just.testing", 80);
672 EXPECT_EQ(ERR_IO_PENDING, req1->Resolve());
674 proc_->SignalMultiple(2u);
676 EXPECT_EQ(OK, req1->WaitForResult());
678 // This request was canceled.
679 EXPECT_FALSE(req0->completed());
682 #if defined(THREAD_SANITIZER)
683 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
684 #define MAYBE_NumericIPv4Address DISABLED_NumericIPv4Address
685 #else
686 #define MAYBE_NumericIPv4Address NumericIPv4Address
687 #endif
688 TEST_F(HostResolverImplTest, MAYBE_NumericIPv4Address) {
689 // Stevens says dotted quads with AI_UNSPEC resolve to a single sockaddr_in.
690 Request* req = CreateRequest("127.1.2.3", 5555);
691 EXPECT_EQ(OK, req->Resolve());
693 EXPECT_TRUE(req->HasOneAddress("127.1.2.3", 5555));
696 #if defined(THREAD_SANITIZER)
697 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
698 #define MAYBE_NumericIPv6Address DISABLED_NumericIPv6Address
699 #else
700 #define MAYBE_NumericIPv6Address NumericIPv6Address
701 #endif
702 TEST_F(HostResolverImplTest, MAYBE_NumericIPv6Address) {
703 // Resolve a plain IPv6 address. Don't worry about [brackets], because
704 // the caller should have removed them.
705 Request* req = CreateRequest("2001:db8::1", 5555);
706 EXPECT_EQ(OK, req->Resolve());
708 EXPECT_TRUE(req->HasOneAddress("2001:db8::1", 5555));
711 #if defined(THREAD_SANITIZER)
712 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
713 #define MAYBE_EmptyHost DISABLED_EmptyHost
714 #else
715 #define MAYBE_EmptyHost EmptyHost
716 #endif
717 TEST_F(HostResolverImplTest, MAYBE_EmptyHost) {
718 Request* req = CreateRequest(std::string(), 5555);
719 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
722 #if defined(THREAD_SANITIZER)
723 // There's a data race in this test that may lead to use-after-free.
724 // If the test starts to crash without ThreadSanitizer it needs to be disabled
725 // globally. See http://crbug.com/268946 (stacks for this test in
726 // crbug.com/333567).
727 #define MAYBE_EmptyDotsHost DISABLED_EmptyDotsHost
728 #else
729 #define MAYBE_EmptyDotsHost EmptyDotsHost
730 #endif
731 TEST_F(HostResolverImplTest, MAYBE_EmptyDotsHost) {
732 for (int i = 0; i < 16; ++i) {
733 Request* req = CreateRequest(std::string(i, '.'), 5555);
734 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
738 #if defined(THREAD_SANITIZER)
739 // There's a data race in this test that may lead to use-after-free.
740 // If the test starts to crash without ThreadSanitizer it needs to be disabled
741 // globally. See http://crbug.com/268946.
742 #define MAYBE_LongHost DISABLED_LongHost
743 #else
744 #define MAYBE_LongHost LongHost
745 #endif
746 TEST_F(HostResolverImplTest, MAYBE_LongHost) {
747 Request* req = CreateRequest(std::string(4097, 'a'), 5555);
748 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve());
751 TEST_F(HostResolverImplTest, DeDupeRequests) {
752 // Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is
753 // blocked, these should all pile up until we signal it.
754 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
755 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 80)->Resolve());
756 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 81)->Resolve());
757 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 82)->Resolve());
758 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve());
760 proc_->SignalMultiple(2u); // One for "a", one for "b".
762 for (size_t i = 0; i < requests_.size(); ++i) {
763 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
767 TEST_F(HostResolverImplTest, CancelMultipleRequests) {
768 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
769 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 80)->Resolve());
770 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 81)->Resolve());
771 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 82)->Resolve());
772 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve());
774 // Cancel everything except request for ("a", 82).
775 requests_[0]->Cancel();
776 requests_[1]->Cancel();
777 requests_[2]->Cancel();
778 requests_[4]->Cancel();
780 proc_->SignalMultiple(2u); // One for "a", one for "b".
782 EXPECT_EQ(OK, requests_[3]->WaitForResult());
785 TEST_F(HostResolverImplTest, CanceledRequestsReleaseJobSlots) {
786 // Fill up the dispatcher and queue.
787 for (unsigned i = 0; i < kMaxJobs + 1; ++i) {
788 std::string hostname = "a_";
789 hostname[1] = 'a' + i;
790 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve());
791 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 81)->Resolve());
794 EXPECT_TRUE(proc_->WaitFor(kMaxJobs));
796 // Cancel all but last two.
797 for (unsigned i = 0; i < requests_.size() - 2; ++i) {
798 requests_[i]->Cancel();
801 EXPECT_TRUE(proc_->WaitFor(kMaxJobs + 1));
803 proc_->SignalAll();
805 size_t num_requests = requests_.size();
806 EXPECT_EQ(OK, requests_[num_requests - 1]->WaitForResult());
807 EXPECT_EQ(OK, requests_[num_requests - 2]->result());
810 TEST_F(HostResolverImplTest, CancelWithinCallback) {
811 struct MyHandler : public Handler {
812 void Handle(Request* req) override {
813 // Port 80 is the first request that the callback will be invoked for.
814 // While we are executing within that callback, cancel the other requests
815 // in the job and start another request.
816 if (req->index() == 0) {
817 // Once "a:80" completes, it will cancel "a:81" and "a:82".
818 requests()[1]->Cancel();
819 requests()[2]->Cancel();
823 set_handler(new MyHandler());
825 for (size_t i = 0; i < 4; ++i) {
826 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
829 proc_->SignalMultiple(2u); // One for "a". One for "finalrequest".
831 EXPECT_EQ(OK, requests_[0]->WaitForResult());
833 Request* final_request = CreateRequest("finalrequest", 70);
834 EXPECT_EQ(ERR_IO_PENDING, final_request->Resolve());
835 EXPECT_EQ(OK, final_request->WaitForResult());
836 EXPECT_TRUE(requests_[3]->completed());
839 TEST_F(HostResolverImplTest, DeleteWithinCallback) {
840 struct MyHandler : public Handler {
841 void Handle(Request* req) override {
842 EXPECT_EQ("a", req->info().hostname());
843 EXPECT_EQ(80, req->info().port());
845 DeleteResolver();
847 // Quit after returning from OnCompleted (to give it a chance at
848 // incorrectly running the cancelled tasks).
849 base::ThreadTaskRunnerHandle::Get()->PostTask(
850 FROM_HERE, base::MessageLoop::QuitClosure());
853 set_handler(new MyHandler());
855 for (size_t i = 0; i < 4; ++i) {
856 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
859 proc_->SignalMultiple(1u); // One for "a".
861 // |MyHandler| will send quit message once all the requests have finished.
862 base::MessageLoop::current()->Run();
865 TEST_F(HostResolverImplTest, DeleteWithinAbortedCallback) {
866 struct MyHandler : public Handler {
867 void Handle(Request* req) override {
868 EXPECT_EQ("a", req->info().hostname());
869 EXPECT_EQ(80, req->info().port());
871 DeleteResolver();
873 // Quit after returning from OnCompleted (to give it a chance at
874 // incorrectly running the cancelled tasks).
875 base::ThreadTaskRunnerHandle::Get()->PostTask(
876 FROM_HERE, base::MessageLoop::QuitClosure());
879 set_handler(new MyHandler());
881 // This test assumes that the Jobs will be Aborted in order ["a", "b"]
882 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
883 // HostResolverImpl will be deleted before later Requests can complete.
884 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 81)->Resolve());
885 // Job for 'b' will be aborted before it can complete.
886 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 82)->Resolve());
887 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve());
889 EXPECT_TRUE(proc_->WaitFor(1u));
891 // Triggering an IP address change.
892 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
894 // |MyHandler| will send quit message once all the requests have finished.
895 base::MessageLoop::current()->Run();
897 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->result());
898 EXPECT_EQ(ERR_IO_PENDING, requests_[1]->result());
899 EXPECT_EQ(ERR_IO_PENDING, requests_[2]->result());
900 EXPECT_EQ(ERR_IO_PENDING, requests_[3]->result());
901 // Clean up.
902 proc_->SignalMultiple(requests_.size());
905 TEST_F(HostResolverImplTest, StartWithinCallback) {
906 struct MyHandler : public Handler {
907 void Handle(Request* req) override {
908 if (req->index() == 0) {
909 // On completing the first request, start another request for "a".
910 // Since caching is disabled, this will result in another async request.
911 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 70)->Resolve());
915 set_handler(new MyHandler());
917 // Turn off caching for this host resolver.
918 HostResolver::Options options = DefaultOptions();
919 options.enable_caching = false;
920 resolver_.reset(new TestHostResolverImpl(options, NULL));
921 resolver_->set_proc_params_for_test(DefaultParams(proc_.get()));
923 for (size_t i = 0; i < 4; ++i) {
924 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i;
927 proc_->SignalMultiple(2u); // One for "a". One for the second "a".
929 EXPECT_EQ(OK, requests_[0]->WaitForResult());
930 ASSERT_EQ(5u, requests_.size());
931 EXPECT_EQ(OK, requests_.back()->WaitForResult());
933 EXPECT_EQ(2u, proc_->GetCaptureList().size());
936 TEST_F(HostResolverImplTest, BypassCache) {
937 struct MyHandler : public Handler {
938 void Handle(Request* req) override {
939 if (req->index() == 0) {
940 // On completing the first request, start another request for "a".
941 // Since caching is enabled, this should complete synchronously.
942 std::string hostname = req->info().hostname();
943 EXPECT_EQ(OK, CreateRequest(hostname, 70)->Resolve());
944 EXPECT_EQ(OK, CreateRequest(hostname, 75)->ResolveFromCache());
946 // Ok good. Now make sure that if we ask to bypass the cache, it can no
947 // longer service the request synchronously.
948 HostResolver::RequestInfo info(HostPortPair(hostname, 71));
949 info.set_allow_cached_response(false);
950 EXPECT_EQ(ERR_IO_PENDING,
951 CreateRequest(info, DEFAULT_PRIORITY)->Resolve());
952 } else if (71 == req->info().port()) {
953 // Test is done.
954 base::MessageLoop::current()->Quit();
955 } else {
956 FAIL() << "Unexpected request";
960 set_handler(new MyHandler());
962 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve());
963 proc_->SignalMultiple(3u); // Only need two, but be generous.
965 // |verifier| will send quit message once all the requests have finished.
966 base::MessageLoop::current()->Run();
967 EXPECT_EQ(2u, proc_->GetCaptureList().size());
970 // Test that IP address changes flush the cache but initial DNS config reads do
971 // not.
972 TEST_F(HostResolverImplTest, FlushCacheOnIPAddressChange) {
973 proc_->SignalMultiple(2u); // One before the flush, one after.
975 Request* req = CreateRequest("host1", 70);
976 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
977 EXPECT_EQ(OK, req->WaitForResult());
979 req = CreateRequest("host1", 75);
980 EXPECT_EQ(OK, req->Resolve()); // Should complete synchronously.
982 // Verify initial DNS config read does not flush cache.
983 NetworkChangeNotifier::NotifyObserversOfInitialDNSConfigReadForTests();
984 req = CreateRequest("host1", 75);
985 EXPECT_EQ(OK, req->Resolve()); // Should complete synchronously.
987 // Flush cache by triggering an IP address change.
988 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
989 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
991 // Resolve "host1" again -- this time it won't be served from cache, so it
992 // will complete asynchronously.
993 req = CreateRequest("host1", 80);
994 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
995 EXPECT_EQ(OK, req->WaitForResult());
998 // Test that IP address changes send ERR_NETWORK_CHANGED to pending requests.
999 TEST_F(HostResolverImplTest, AbortOnIPAddressChanged) {
1000 Request* req = CreateRequest("host1", 70);
1001 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1003 EXPECT_TRUE(proc_->WaitFor(1u));
1004 // Triggering an IP address change.
1005 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1006 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1007 proc_->SignalAll();
1009 EXPECT_EQ(ERR_NETWORK_CHANGED, req->WaitForResult());
1010 EXPECT_EQ(0u, resolver_->GetHostCache()->size());
1013 // Test that initial DNS config read signals do not abort pending requests.
1014 TEST_F(HostResolverImplTest, DontAbortOnInitialDNSConfigRead) {
1015 Request* req = CreateRequest("host1", 70);
1016 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1018 EXPECT_TRUE(proc_->WaitFor(1u));
1019 // Triggering initial DNS config read signal.
1020 NetworkChangeNotifier::NotifyObserversOfInitialDNSConfigReadForTests();
1021 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1022 proc_->SignalAll();
1024 EXPECT_EQ(OK, req->WaitForResult());
1027 // Obey pool constraints after IP address has changed.
1028 TEST_F(HostResolverImplTest, ObeyPoolConstraintsAfterIPAddressChange) {
1029 // Runs at most one job at a time.
1030 CreateSerialResolver();
1031 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a")->Resolve());
1032 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b")->Resolve());
1033 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("c")->Resolve());
1035 EXPECT_TRUE(proc_->WaitFor(1u));
1036 // Triggering an IP address change.
1037 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1038 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1039 proc_->SignalMultiple(3u); // Let the false-start go so that we can catch it.
1041 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->WaitForResult());
1043 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1045 EXPECT_FALSE(requests_[1]->completed());
1046 EXPECT_FALSE(requests_[2]->completed());
1048 EXPECT_EQ(OK, requests_[2]->WaitForResult());
1049 EXPECT_EQ(OK, requests_[1]->result());
1052 // Tests that a new Request made from the callback of a previously aborted one
1053 // will not be aborted.
1054 TEST_F(HostResolverImplTest, AbortOnlyExistingRequestsOnIPAddressChange) {
1055 struct MyHandler : public Handler {
1056 void Handle(Request* req) override {
1057 // Start new request for a different hostname to ensure that the order
1058 // of jobs in HostResolverImpl is not stable.
1059 std::string hostname;
1060 if (req->index() == 0)
1061 hostname = "zzz";
1062 else if (req->index() == 1)
1063 hostname = "aaa";
1064 else if (req->index() == 2)
1065 hostname = "eee";
1066 else
1067 return; // A request started from within MyHandler.
1068 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname)->Resolve()) << hostname;
1071 set_handler(new MyHandler());
1073 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("bbb")->Resolve());
1074 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("eee")->Resolve());
1075 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ccc")->Resolve());
1077 // Wait until all are blocked;
1078 EXPECT_TRUE(proc_->WaitFor(3u));
1079 // Trigger an IP address change.
1080 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1081 // This should abort all running jobs.
1082 base::MessageLoop::current()->RunUntilIdle();
1083 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->result());
1084 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[1]->result());
1085 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[2]->result());
1086 ASSERT_EQ(6u, requests_.size());
1087 // Unblock all calls to proc.
1088 proc_->SignalMultiple(requests_.size());
1089 // Run until the re-started requests finish.
1090 EXPECT_EQ(OK, requests_[3]->WaitForResult());
1091 EXPECT_EQ(OK, requests_[4]->WaitForResult());
1092 EXPECT_EQ(OK, requests_[5]->WaitForResult());
1093 // Verify that results of aborted Jobs were not cached.
1094 EXPECT_EQ(6u, proc_->GetCaptureList().size());
1095 EXPECT_EQ(3u, resolver_->GetHostCache()->size());
1098 // Tests that when the maximum threads is set to 1, requests are dequeued
1099 // in order of priority.
1100 TEST_F(HostResolverImplTest, HigherPriorityRequestsStartedFirst) {
1101 CreateSerialResolver();
1103 // Note that at this point the MockHostResolverProc is blocked, so any
1104 // requests we make will not complete.
1105 CreateRequest("req0", 80, LOW);
1106 CreateRequest("req1", 80, MEDIUM);
1107 CreateRequest("req2", 80, MEDIUM);
1108 CreateRequest("req3", 80, LOW);
1109 CreateRequest("req4", 80, HIGHEST);
1110 CreateRequest("req5", 80, LOW);
1111 CreateRequest("req6", 80, LOW);
1112 CreateRequest("req5", 80, HIGHEST);
1114 for (size_t i = 0; i < requests_.size(); ++i) {
1115 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1118 // Unblock the resolver thread so the requests can run.
1119 proc_->SignalMultiple(requests_.size()); // More than needed.
1121 // Wait for all the requests to complete succesfully.
1122 for (size_t i = 0; i < requests_.size(); ++i) {
1123 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1126 // Since we have restricted to a single concurrent thread in the jobpool,
1127 // the requests should complete in order of priority (with the exception
1128 // of the first request, which gets started right away, since there is
1129 // nothing outstanding).
1130 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1131 ASSERT_EQ(7u, capture_list.size());
1133 EXPECT_EQ("req0", capture_list[0].hostname);
1134 EXPECT_EQ("req4", capture_list[1].hostname);
1135 EXPECT_EQ("req5", capture_list[2].hostname);
1136 EXPECT_EQ("req1", capture_list[3].hostname);
1137 EXPECT_EQ("req2", capture_list[4].hostname);
1138 EXPECT_EQ("req3", capture_list[5].hostname);
1139 EXPECT_EQ("req6", capture_list[6].hostname);
1142 // Try cancelling a job which has not started yet.
1143 TEST_F(HostResolverImplTest, CancelPendingRequest) {
1144 CreateSerialResolver();
1146 CreateRequest("req0", 80, LOWEST);
1147 CreateRequest("req1", 80, HIGHEST); // Will cancel.
1148 CreateRequest("req2", 80, MEDIUM);
1149 CreateRequest("req3", 80, LOW);
1150 CreateRequest("req4", 80, HIGHEST); // Will cancel.
1151 CreateRequest("req5", 80, LOWEST); // Will cancel.
1152 CreateRequest("req6", 80, MEDIUM);
1154 // Start all of the requests.
1155 for (size_t i = 0; i < requests_.size(); ++i) {
1156 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i;
1159 // Cancel some requests
1160 requests_[1]->Cancel();
1161 requests_[4]->Cancel();
1162 requests_[5]->Cancel();
1164 // Unblock the resolver thread so the requests can run.
1165 proc_->SignalMultiple(requests_.size()); // More than needed.
1167 // Wait for all the requests to complete succesfully.
1168 for (size_t i = 0; i < requests_.size(); ++i) {
1169 if (!requests_[i]->pending())
1170 continue; // Don't wait for the requests we cancelled.
1171 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1174 // Verify that they called out the the resolver proc (which runs on the
1175 // resolver thread) in the expected order.
1176 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1177 ASSERT_EQ(4u, capture_list.size());
1179 EXPECT_EQ("req0", capture_list[0].hostname);
1180 EXPECT_EQ("req2", capture_list[1].hostname);
1181 EXPECT_EQ("req6", capture_list[2].hostname);
1182 EXPECT_EQ("req3", capture_list[3].hostname);
1185 // Test that when too many requests are enqueued, old ones start to be aborted.
1186 TEST_F(HostResolverImplTest, QueueOverflow) {
1187 CreateSerialResolver();
1189 // Allow only 3 queued jobs.
1190 const size_t kMaxPendingJobs = 3u;
1191 resolver_->SetMaxQueuedJobs(kMaxPendingJobs);
1193 // Note that at this point the MockHostResolverProc is blocked, so any
1194 // requests we make will not complete.
1196 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req0", 80, LOWEST)->Resolve());
1197 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req1", 80, HIGHEST)->Resolve());
1198 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req2", 80, MEDIUM)->Resolve());
1199 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req3", 80, MEDIUM)->Resolve());
1201 // At this point, there are 3 enqueued jobs.
1202 // Insertion of subsequent requests will cause evictions
1203 // based on priority.
1205 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE,
1206 CreateRequest("req4", 80, LOW)->Resolve()); // Evicts itself!
1208 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req5", 80, MEDIUM)->Resolve());
1209 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[2]->result());
1210 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req6", 80, HIGHEST)->Resolve());
1211 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[3]->result());
1212 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req7", 80, MEDIUM)->Resolve());
1213 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[5]->result());
1215 // Unblock the resolver thread so the requests can run.
1216 proc_->SignalMultiple(4u);
1218 // The rest should succeed.
1219 EXPECT_EQ(OK, requests_[7]->WaitForResult());
1220 EXPECT_EQ(OK, requests_[0]->result());
1221 EXPECT_EQ(OK, requests_[1]->result());
1222 EXPECT_EQ(OK, requests_[6]->result());
1224 // Verify that they called out the the resolver proc (which runs on the
1225 // resolver thread) in the expected order.
1226 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList();
1227 ASSERT_EQ(4u, capture_list.size());
1229 EXPECT_EQ("req0", capture_list[0].hostname);
1230 EXPECT_EQ("req1", capture_list[1].hostname);
1231 EXPECT_EQ("req6", capture_list[2].hostname);
1232 EXPECT_EQ("req7", capture_list[3].hostname);
1234 // Verify that the evicted (incomplete) requests were not cached.
1235 EXPECT_EQ(4u, resolver_->GetHostCache()->size());
1237 for (size_t i = 0; i < requests_.size(); ++i) {
1238 EXPECT_TRUE(requests_[i]->completed()) << i;
1242 // Make sure that the address family parameter is respected when raw IPs are
1243 // passed in.
1244 TEST_F(HostResolverImplTest, AddressFamilyWithRawIPs) {
1245 Request* request =
1246 CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1247 EXPECT_EQ(OK, request->Resolve());
1248 EXPECT_TRUE(request->HasOneAddress("127.0.0.1", 80));
1250 request = CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1251 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, request->Resolve());
1253 request = CreateRequest("127.0.0.1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1254 EXPECT_EQ(OK, request->Resolve());
1255 EXPECT_TRUE(request->HasOneAddress("127.0.0.1", 80));
1257 request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1258 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, request->Resolve());
1260 request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1261 EXPECT_EQ(OK, request->Resolve());
1262 EXPECT_TRUE(request->HasOneAddress("::1", 80));
1264 request = CreateRequest("::1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED);
1265 EXPECT_EQ(OK, request->Resolve());
1266 EXPECT_TRUE(request->HasOneAddress("::1", 80));
1269 TEST_F(HostResolverImplTest, ResolveFromCache) {
1270 proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42");
1271 proc_->SignalMultiple(1u); // Need only one.
1273 HostResolver::RequestInfo info(HostPortPair("just.testing", 80));
1275 // First hit will miss the cache.
1276 EXPECT_EQ(ERR_DNS_CACHE_MISS,
1277 CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache());
1279 // This time, we fetch normally.
1280 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info, DEFAULT_PRIORITY)->Resolve());
1281 EXPECT_EQ(OK, requests_[1]->WaitForResult());
1283 // Now we should be able to fetch from the cache.
1284 EXPECT_EQ(OK, CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache());
1285 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.1.42", 80));
1288 // Test the retry attempts simulating host resolver proc that takes too long.
1289 TEST_F(HostResolverImplTest, MultipleAttempts) {
1290 // Total number of attempts would be 3 and we want the 3rd attempt to resolve
1291 // the host. First and second attempt will be forced to sleep until they get
1292 // word that a resolution has completed. The 3rd resolution attempt will try
1293 // to get done ASAP, and won't sleep..
1294 int kAttemptNumberToResolve = 3;
1295 int kTotalAttempts = 3;
1297 scoped_refptr<LookupAttemptHostResolverProc> resolver_proc(
1298 new LookupAttemptHostResolverProc(
1299 NULL, kAttemptNumberToResolve, kTotalAttempts));
1301 HostResolverImpl::ProcTaskParams params = DefaultParams(resolver_proc.get());
1303 // Specify smaller interval for unresponsive_delay_ for HostResolverImpl so
1304 // that unit test runs faster. For example, this test finishes in 1.5 secs
1305 // (500ms * 3).
1306 params.unresponsive_delay = base::TimeDelta::FromMilliseconds(500);
1308 resolver_.reset(new TestHostResolverImpl(DefaultOptions(), NULL));
1309 resolver_->set_proc_params_for_test(params);
1311 // Resolve "host1".
1312 HostResolver::RequestInfo info(HostPortPair("host1", 70));
1313 Request* req = CreateRequest(info, DEFAULT_PRIORITY);
1314 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1316 // Resolve returns -4 to indicate that 3rd attempt has resolved the host.
1317 EXPECT_EQ(-4, req->WaitForResult());
1319 resolver_proc->WaitForAllAttemptsToFinish(
1320 base::TimeDelta::FromMilliseconds(60000));
1321 base::MessageLoop::current()->RunUntilIdle();
1323 EXPECT_EQ(resolver_proc->total_attempts_resolved(), kTotalAttempts);
1324 EXPECT_EQ(resolver_proc->resolved_attempt_number(), kAttemptNumberToResolve);
1327 // If a host resolves to a list that includes 127.0.53.53, this is treated as
1328 // an error. 127.0.53.53 is a localhost address, however it has been given a
1329 // special significance by ICANN to help surfance name collision resulting from
1330 // the new gTLDs.
1331 TEST_F(HostResolverImplTest, NameCollision127_0_53_53) {
1332 proc_->AddRuleForAllFamilies("single", "127.0.53.53");
1333 proc_->AddRuleForAllFamilies("multiple", "127.0.0.1,127.0.53.53");
1334 proc_->AddRuleForAllFamilies("ipv6", "::127.0.53.53");
1335 proc_->AddRuleForAllFamilies("not_reserved1", "53.53.0.127");
1336 proc_->AddRuleForAllFamilies("not_reserved2", "127.0.53.54");
1337 proc_->AddRuleForAllFamilies("not_reserved3", "10.0.53.53");
1338 proc_->SignalMultiple(6u);
1340 Request* request;
1342 request = CreateRequest("single");
1343 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1344 EXPECT_EQ(ERR_ICANN_NAME_COLLISION, request->WaitForResult());
1346 request = CreateRequest("multiple");
1347 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1348 EXPECT_EQ(ERR_ICANN_NAME_COLLISION, request->WaitForResult());
1350 // Resolving an IP literal of 127.0.53.53 however is allowed.
1351 EXPECT_EQ(OK, CreateRequest("127.0.53.53")->Resolve());
1353 // Moreover the address should not be recognized when embedded in an IPv6
1354 // address.
1355 request = CreateRequest("ipv6");
1356 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1357 EXPECT_EQ(OK, request->WaitForResult());
1359 // Try some other IPs which are similar, but NOT an exact match on
1360 // 127.0.53.53.
1361 request = CreateRequest("not_reserved1");
1362 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1363 EXPECT_EQ(OK, request->WaitForResult());
1365 request = CreateRequest("not_reserved2");
1366 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1367 EXPECT_EQ(OK, request->WaitForResult());
1369 request = CreateRequest("not_reserved3");
1370 EXPECT_EQ(ERR_IO_PENDING, request->Resolve());
1371 EXPECT_EQ(OK, request->WaitForResult());
1374 TEST_F(HostResolverImplTest, IsIPv6Reachable) {
1375 // The real HostResolverImpl is needed since TestHostResolverImpl will
1376 // bypass the IPv6 reachability tests.
1377 resolver_.reset(new HostResolverImpl(DefaultOptions(), nullptr));
1379 // Verify that two consecutive calls return the same value.
1380 TestNetLog net_log;
1381 BoundNetLog bound_net_log = BoundNetLog::Make(&net_log, NetLog::SOURCE_NONE);
1382 bool result1 = IsIPv6Reachable(bound_net_log);
1383 bool result2 = IsIPv6Reachable(bound_net_log);
1384 EXPECT_EQ(result1, result2);
1386 // Filter reachability check events and verify that there are two of them.
1387 TestNetLogEntry::List event_list;
1388 net_log.GetEntries(&event_list);
1389 TestNetLogEntry::List probe_event_list;
1390 for (const auto& event : event_list) {
1391 if (event.type == NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK) {
1392 probe_event_list.push_back(event);
1395 ASSERT_EQ(2U, probe_event_list.size());
1397 // Verify that the first request was not cached and the second one was.
1398 bool cached;
1399 EXPECT_TRUE(probe_event_list[0].GetBooleanValue("cached", &cached));
1400 EXPECT_FALSE(cached);
1401 EXPECT_TRUE(probe_event_list[1].GetBooleanValue("cached", &cached));
1402 EXPECT_TRUE(cached);
1405 DnsConfig CreateValidDnsConfig() {
1406 IPAddressNumber dns_ip;
1407 bool rv = ParseIPLiteralToNumber("192.168.1.0", &dns_ip);
1408 EXPECT_TRUE(rv);
1410 DnsConfig config;
1411 config.nameservers.push_back(IPEndPoint(dns_ip, dns_protocol::kDefaultPort));
1412 EXPECT_TRUE(config.IsValid());
1413 return config;
1416 // Specialized fixture for tests of DnsTask.
1417 class HostResolverImplDnsTest : public HostResolverImplTest {
1418 public:
1419 HostResolverImplDnsTest() : dns_client_(NULL) {}
1421 protected:
1422 // testing::Test implementation:
1423 void SetUp() override {
1424 AddDnsRule("nx", dns_protocol::kTypeA, MockDnsClientRule::FAIL, false);
1425 AddDnsRule("nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL, false);
1426 AddDnsRule("ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1427 AddDnsRule("ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK, false);
1428 AddDnsRule("4ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1429 AddDnsRule("4ok", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY, false);
1430 AddDnsRule("6ok", dns_protocol::kTypeA, MockDnsClientRule::EMPTY, false);
1431 AddDnsRule("6ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK, false);
1432 AddDnsRule("4nx", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1433 AddDnsRule("4nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL, false);
1434 AddDnsRule("empty", dns_protocol::kTypeA, MockDnsClientRule::EMPTY, false);
1435 AddDnsRule("empty", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY,
1436 false);
1438 AddDnsRule("slow_nx", dns_protocol::kTypeA, MockDnsClientRule::FAIL, true);
1439 AddDnsRule("slow_nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL,
1440 true);
1442 AddDnsRule("4slow_ok", dns_protocol::kTypeA, MockDnsClientRule::OK, true);
1443 AddDnsRule("4slow_ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1444 false);
1445 AddDnsRule("6slow_ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false);
1446 AddDnsRule("6slow_ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1447 true);
1448 AddDnsRule("4slow_4ok", dns_protocol::kTypeA, MockDnsClientRule::OK, true);
1449 AddDnsRule("4slow_4ok", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY,
1450 false);
1451 AddDnsRule("4slow_4timeout", dns_protocol::kTypeA,
1452 MockDnsClientRule::TIMEOUT, true);
1453 AddDnsRule("4slow_4timeout", dns_protocol::kTypeAAAA, MockDnsClientRule::OK,
1454 false);
1455 AddDnsRule("4slow_6timeout", dns_protocol::kTypeA,
1456 MockDnsClientRule::OK, true);
1457 AddDnsRule("4slow_6timeout", dns_protocol::kTypeAAAA,
1458 MockDnsClientRule::TIMEOUT, false);
1459 CreateResolver();
1462 // HostResolverImplTest implementation:
1463 void CreateResolverWithLimitsAndParams(
1464 size_t max_concurrent_resolves,
1465 const HostResolverImpl::ProcTaskParams& params) override {
1466 HostResolverImpl::Options options = DefaultOptions();
1467 options.max_concurrent_resolves = max_concurrent_resolves;
1468 resolver_.reset(new TestHostResolverImpl(options, NULL));
1469 resolver_->set_proc_params_for_test(params);
1470 dns_client_ = new MockDnsClient(DnsConfig(), dns_rules_);
1471 resolver_->SetDnsClient(scoped_ptr<DnsClient>(dns_client_));
1474 // Adds a rule to |dns_rules_|. Must be followed by |CreateResolver| to apply.
1475 void AddDnsRule(const std::string& prefix,
1476 uint16 qtype,
1477 MockDnsClientRule::Result result,
1478 bool delay) {
1479 dns_rules_.push_back(MockDnsClientRule(prefix, qtype, result, delay));
1482 void ChangeDnsConfig(const DnsConfig& config) {
1483 NetworkChangeNotifier::SetDnsConfig(config);
1484 // Notification is delivered asynchronously.
1485 base::MessageLoop::current()->RunUntilIdle();
1488 MockDnsClientRuleList dns_rules_;
1489 // Owned by |resolver_|.
1490 MockDnsClient* dns_client_;
1493 // TODO(szym): Test AbortAllInProgressJobs due to DnsConfig change.
1495 // TODO(cbentzel): Test a mix of requests with different HostResolverFlags.
1497 // Test successful and fallback resolutions in HostResolverImpl::DnsTask.
1498 TEST_F(HostResolverImplDnsTest, DnsTask) {
1499 proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
1500 // All other hostnames will fail in proc_.
1502 // Initially there is no config, so client should not be invoked.
1503 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve());
1504 proc_->SignalMultiple(requests_.size());
1506 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult());
1508 ChangeDnsConfig(CreateValidDnsConfig());
1510 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80, MEDIUM,
1511 ADDRESS_FAMILY_IPV4)->Resolve());
1512 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_fail", 80, MEDIUM,
1513 ADDRESS_FAMILY_IPV4)->Resolve());
1514 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_succeed", 80, MEDIUM,
1515 ADDRESS_FAMILY_IPV4)->Resolve());
1517 proc_->SignalMultiple(requests_.size());
1519 for (size_t i = 1; i < requests_.size(); ++i)
1520 EXPECT_NE(ERR_UNEXPECTED, requests_[i]->WaitForResult()) << i;
1522 EXPECT_EQ(OK, requests_[1]->result());
1523 // Resolved by MockDnsClient.
1524 EXPECT_TRUE(requests_[1]->HasOneAddress("127.0.0.1", 80));
1525 // Fallback to ProcTask.
1526 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[2]->result());
1527 EXPECT_EQ(OK, requests_[3]->result());
1528 EXPECT_TRUE(requests_[3]->HasOneAddress("192.168.1.102", 80));
1531 // Test successful and failing resolutions in HostResolverImpl::DnsTask when
1532 // fallback to ProcTask is disabled.
1533 TEST_F(HostResolverImplDnsTest, NoFallbackToProcTask) {
1534 set_fallback_to_proctask(false);
1536 proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
1537 // All other hostnames will fail in proc_.
1539 // Set empty DnsConfig.
1540 ChangeDnsConfig(DnsConfig());
1541 // Initially there is no config, so client should not be invoked.
1542 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve());
1543 // There is no config, so fallback to ProcTask must work.
1544 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_succeed", 80)->Resolve());
1545 proc_->SignalMultiple(requests_.size());
1547 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult());
1548 EXPECT_EQ(OK, requests_[1]->WaitForResult());
1549 EXPECT_TRUE(requests_[1]->HasOneAddress("192.168.1.102", 80));
1551 ChangeDnsConfig(CreateValidDnsConfig());
1553 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_abort", 80, MEDIUM,
1554 ADDRESS_FAMILY_IPV4)->Resolve());
1555 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80, MEDIUM,
1556 ADDRESS_FAMILY_IPV4)->Resolve());
1558 // Simulate the case when the preference or policy has disabled the DNS client
1559 // causing AbortDnsTasks.
1560 resolver_->SetDnsClient(
1561 scoped_ptr<DnsClient>(new MockDnsClient(DnsConfig(), dns_rules_)));
1562 ChangeDnsConfig(CreateValidDnsConfig());
1564 // First request is resolved by MockDnsClient, others should fail due to
1565 // disabled fallback to ProcTask.
1566 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80, MEDIUM,
1567 ADDRESS_FAMILY_IPV4)->Resolve());
1568 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_fail", 80, MEDIUM,
1569 ADDRESS_FAMILY_IPV4)->Resolve());
1570 proc_->SignalMultiple(requests_.size());
1572 // Aborted due to Network Change.
1573 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[2]->WaitForResult());
1574 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[3]->WaitForResult());
1575 // Resolved by MockDnsClient.
1576 EXPECT_EQ(OK, requests_[4]->WaitForResult());
1577 EXPECT_TRUE(requests_[4]->HasOneAddress("127.0.0.1", 80));
1578 // Fallback to ProcTask is disabled.
1579 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[5]->WaitForResult());
1582 // Test behavior of OnDnsTaskFailure when Job is aborted.
1583 TEST_F(HostResolverImplDnsTest, OnDnsTaskFailureAbortedJob) {
1584 ChangeDnsConfig(CreateValidDnsConfig());
1585 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80)->Resolve());
1586 // Abort all jobs here.
1587 CreateResolver();
1588 proc_->SignalMultiple(requests_.size());
1589 // Run to completion.
1590 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1591 // It shouldn't crash during OnDnsTaskFailure callbacks.
1592 EXPECT_EQ(ERR_IO_PENDING, requests_[0]->result());
1594 // Repeat test with Fallback to ProcTask disabled
1595 set_fallback_to_proctask(false);
1596 ChangeDnsConfig(CreateValidDnsConfig());
1597 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80)->Resolve());
1598 // Abort all jobs here.
1599 CreateResolver();
1600 // Run to completion.
1601 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1602 // It shouldn't crash during OnDnsTaskFailure callbacks.
1603 EXPECT_EQ(ERR_IO_PENDING, requests_[1]->result());
1606 TEST_F(HostResolverImplDnsTest, DnsTaskUnspec) {
1607 ChangeDnsConfig(CreateValidDnsConfig());
1609 proc_->AddRuleForAllFamilies("4nx", "192.168.1.101");
1610 // All other hostnames will fail in proc_.
1612 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1613 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4ok", 80)->Resolve());
1614 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("6ok", 80)->Resolve());
1615 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4nx", 80)->Resolve());
1617 proc_->SignalMultiple(requests_.size());
1619 for (size_t i = 0; i < requests_.size(); ++i)
1620 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1622 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses());
1623 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80));
1624 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80));
1625 EXPECT_EQ(1u, requests_[1]->NumberOfAddresses());
1626 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80));
1627 EXPECT_EQ(1u, requests_[2]->NumberOfAddresses());
1628 EXPECT_TRUE(requests_[2]->HasAddress("::1", 80));
1629 EXPECT_EQ(1u, requests_[3]->NumberOfAddresses());
1630 EXPECT_TRUE(requests_[3]->HasAddress("192.168.1.101", 80));
1633 TEST_F(HostResolverImplDnsTest, ServeFromHosts) {
1634 // Initially, use empty HOSTS file.
1635 DnsConfig config = CreateValidDnsConfig();
1636 ChangeDnsConfig(config);
1638 proc_->AddRuleForAllFamilies(std::string(),
1639 std::string()); // Default to failures.
1640 proc_->SignalMultiple(1u); // For the first request which misses.
1642 Request* req0 = CreateRequest("nx_ipv4", 80);
1643 EXPECT_EQ(ERR_IO_PENDING, req0->Resolve());
1644 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req0->WaitForResult());
1646 IPAddressNumber local_ipv4, local_ipv6;
1647 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4));
1648 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6));
1650 DnsHosts hosts;
1651 hosts[DnsHostsKey("nx_ipv4", ADDRESS_FAMILY_IPV4)] = local_ipv4;
1652 hosts[DnsHostsKey("nx_ipv6", ADDRESS_FAMILY_IPV6)] = local_ipv6;
1653 hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV4)] = local_ipv4;
1654 hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV6)] = local_ipv6;
1656 // Update HOSTS file.
1657 config.hosts = hosts;
1658 ChangeDnsConfig(config);
1660 Request* req1 = CreateRequest("nx_ipv4", 80);
1661 EXPECT_EQ(OK, req1->Resolve());
1662 EXPECT_TRUE(req1->HasOneAddress("127.0.0.1", 80));
1664 Request* req2 = CreateRequest("nx_ipv6", 80);
1665 EXPECT_EQ(OK, req2->Resolve());
1666 EXPECT_TRUE(req2->HasOneAddress("::1", 80));
1668 Request* req3 = CreateRequest("nx_both", 80);
1669 EXPECT_EQ(OK, req3->Resolve());
1670 EXPECT_TRUE(req3->HasAddress("127.0.0.1", 80) &&
1671 req3->HasAddress("::1", 80));
1673 // Requests with specified AddressFamily.
1674 Request* req4 = CreateRequest("nx_ipv4", 80, MEDIUM, ADDRESS_FAMILY_IPV4);
1675 EXPECT_EQ(OK, req4->Resolve());
1676 EXPECT_TRUE(req4->HasOneAddress("127.0.0.1", 80));
1678 Request* req5 = CreateRequest("nx_ipv6", 80, MEDIUM, ADDRESS_FAMILY_IPV6);
1679 EXPECT_EQ(OK, req5->Resolve());
1680 EXPECT_TRUE(req5->HasOneAddress("::1", 80));
1682 // Request with upper case.
1683 Request* req6 = CreateRequest("nx_IPV4", 80);
1684 EXPECT_EQ(OK, req6->Resolve());
1685 EXPECT_TRUE(req6->HasOneAddress("127.0.0.1", 80));
1688 TEST_F(HostResolverImplDnsTest, BypassDnsTask) {
1689 ChangeDnsConfig(CreateValidDnsConfig());
1691 proc_->AddRuleForAllFamilies(std::string(),
1692 std::string()); // Default to failures.
1694 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok.local", 80)->Resolve());
1695 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok.local.", 80)->Resolve());
1696 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("oklocal", 80)->Resolve());
1697 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("oklocal.", 80)->Resolve());
1698 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1700 proc_->SignalMultiple(requests_.size());
1702 for (size_t i = 0; i < 2; ++i)
1703 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[i]->WaitForResult()) << i;
1705 for (size_t i = 2; i < requests_.size(); ++i)
1706 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1709 TEST_F(HostResolverImplDnsTest, SystemOnlyBypassesDnsTask) {
1710 ChangeDnsConfig(CreateValidDnsConfig());
1712 proc_->AddRuleForAllFamilies(std::string(), std::string());
1714 HostResolver::RequestInfo info_bypass(HostPortPair("ok", 80));
1715 info_bypass.set_host_resolver_flags(HOST_RESOLVER_SYSTEM_ONLY);
1716 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info_bypass, MEDIUM)->Resolve());
1718 HostResolver::RequestInfo info(HostPortPair("ok", 80));
1719 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info, MEDIUM)->Resolve());
1721 proc_->SignalMultiple(requests_.size());
1723 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult());
1724 EXPECT_EQ(OK, requests_[1]->WaitForResult());
1727 TEST_F(HostResolverImplDnsTest, DisableDnsClientOnPersistentFailure) {
1728 ChangeDnsConfig(CreateValidDnsConfig());
1730 proc_->AddRuleForAllFamilies(std::string(),
1731 std::string()); // Default to failures.
1733 // Check that DnsTask works.
1734 Request* req = CreateRequest("ok_1", 80);
1735 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1736 EXPECT_EQ(OK, req->WaitForResult());
1738 for (unsigned i = 0; i < maximum_dns_failures(); ++i) {
1739 // Use custom names to require separate Jobs.
1740 std::string hostname = base::StringPrintf("nx_%u", i);
1741 // Ensure fallback to ProcTask succeeds.
1742 proc_->AddRuleForAllFamilies(hostname, "192.168.1.101");
1743 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve()) << i;
1746 proc_->SignalMultiple(requests_.size());
1748 for (size_t i = 0; i < requests_.size(); ++i)
1749 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1751 ASSERT_FALSE(proc_->HasBlockedRequests());
1753 // DnsTask should be disabled by now.
1754 req = CreateRequest("ok_2", 80);
1755 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1756 proc_->SignalMultiple(1u);
1757 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult());
1759 // Check that it is re-enabled after DNS change.
1760 ChangeDnsConfig(CreateValidDnsConfig());
1761 req = CreateRequest("ok_3", 80);
1762 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1763 EXPECT_EQ(OK, req->WaitForResult());
1766 TEST_F(HostResolverImplDnsTest, DontDisableDnsClientOnSporadicFailure) {
1767 ChangeDnsConfig(CreateValidDnsConfig());
1769 // |proc_| defaults to successes.
1771 // 20 failures interleaved with 20 successes.
1772 for (unsigned i = 0; i < 40; ++i) {
1773 // Use custom names to require separate Jobs.
1774 std::string hostname = (i % 2) == 0 ? base::StringPrintf("nx_%u", i)
1775 : base::StringPrintf("ok_%u", i);
1776 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve()) << i;
1779 proc_->SignalMultiple(requests_.size());
1781 for (size_t i = 0; i < requests_.size(); ++i)
1782 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i;
1784 // Make |proc_| default to failures.
1785 proc_->AddRuleForAllFamilies(std::string(), std::string());
1787 // DnsTask should still be enabled.
1788 Request* req = CreateRequest("ok_last", 80);
1789 EXPECT_EQ(ERR_IO_PENDING, req->Resolve());
1790 EXPECT_EQ(OK, req->WaitForResult());
1793 // Confirm that resolving "localhost" is unrestricted even if there are no
1794 // global IPv6 address. See SystemHostResolverCall for rationale.
1795 // Test both the DnsClient and system host resolver paths.
1796 TEST_F(HostResolverImplDnsTest, DualFamilyLocalhost) {
1797 // Use regular SystemHostResolverCall!
1798 scoped_refptr<HostResolverProc> proc(new SystemHostResolverProc());
1799 resolver_.reset(new TestHostResolverImpl(DefaultOptions(), NULL, false));
1800 resolver_->set_proc_params_for_test(DefaultParams(proc.get()));
1802 resolver_->SetDnsClient(
1803 scoped_ptr<DnsClient>(new MockDnsClient(DnsConfig(), dns_rules_)));
1805 // Get the expected output.
1806 AddressList addrlist;
1807 int rv = proc->Resolve("localhost", ADDRESS_FAMILY_UNSPECIFIED, 0, &addrlist,
1808 NULL);
1809 if (rv != OK)
1810 return;
1812 for (unsigned i = 0; i < addrlist.size(); ++i)
1813 LOG(WARNING) << addrlist[i].ToString();
1815 bool saw_ipv4 = AddressListContains(addrlist, "127.0.0.1", 0);
1816 bool saw_ipv6 = AddressListContains(addrlist, "::1", 0);
1817 if (!saw_ipv4 && !saw_ipv6)
1818 return;
1820 // Try without DnsClient.
1821 DnsConfig config = CreateValidDnsConfig();
1822 config.use_local_ipv6 = false;
1823 ChangeDnsConfig(config);
1824 HostResolver::RequestInfo info_proc(HostPortPair("localhost", 80));
1825 info_proc.set_address_family(ADDRESS_FAMILY_UNSPECIFIED);
1826 info_proc.set_host_resolver_flags(HOST_RESOLVER_SYSTEM_ONLY);
1827 Request* req = CreateRequest(info_proc, DEFAULT_PRIORITY);
1829 EXPECT_EQ(OK, req->Resolve());
1831 EXPECT_TRUE(req->HasAddress("127.0.0.1", 80));
1832 EXPECT_TRUE(req->HasAddress("::1", 80));
1834 // Configure DnsClient with dual-host HOSTS file.
1835 DnsConfig config_hosts = CreateValidDnsConfig();
1836 DnsHosts hosts;
1837 IPAddressNumber local_ipv4, local_ipv6;
1838 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4));
1839 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6));
1840 if (saw_ipv4)
1841 hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4)] = local_ipv4;
1842 if (saw_ipv6)
1843 hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV6)] = local_ipv6;
1844 config_hosts.hosts = hosts;
1846 ChangeDnsConfig(config_hosts);
1847 HostResolver::RequestInfo info_hosts(HostPortPair("localhost", 80));
1848 info_hosts.set_address_family(ADDRESS_FAMILY_UNSPECIFIED);
1849 req = CreateRequest(info_hosts, DEFAULT_PRIORITY);
1850 // Expect synchronous resolution from DnsHosts.
1851 EXPECT_EQ(OK, req->Resolve());
1853 EXPECT_EQ(saw_ipv4, req->HasAddress("127.0.0.1", 80));
1854 EXPECT_EQ(saw_ipv6, req->HasAddress("::1", 80));
1857 // Cancel a request with a single DNS transaction active.
1858 TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActive) {
1859 ChangeDnsConfig(CreateValidDnsConfig());
1861 EXPECT_EQ(ERR_IO_PENDING,
1862 CreateRequest("ok", 80, MEDIUM, ADDRESS_FAMILY_IPV4)->Resolve());
1863 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1864 requests_[0]->Cancel();
1866 // Dispatcher state checked in TearDown.
1869 // Cancel a request with a single DNS transaction active and another pending.
1870 TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActiveOnePending) {
1871 CreateSerialResolver();
1872 ChangeDnsConfig(CreateValidDnsConfig());
1874 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1875 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1876 requests_[0]->Cancel();
1878 // Dispatcher state checked in TearDown.
1881 // Cancel a request with two DNS transactions active.
1882 TEST_F(HostResolverImplDnsTest, CancelWithTwoTransactionsActive) {
1883 ChangeDnsConfig(CreateValidDnsConfig());
1885 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1886 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1887 requests_[0]->Cancel();
1889 // Dispatcher state checked in TearDown.
1892 // Delete a resolver with some active requests and some queued requests.
1893 TEST_F(HostResolverImplDnsTest, DeleteWithActiveTransactions) {
1894 // At most 10 Jobs active at once.
1895 CreateResolverWithLimitsAndParams(10u, DefaultParams(proc_.get()));
1897 ChangeDnsConfig(CreateValidDnsConfig());
1899 // First active job is an IPv4 request.
1900 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM,
1901 ADDRESS_FAMILY_IPV4)->Resolve());
1903 // Add 10 more DNS lookups for different hostnames. First 4 should have two
1904 // active jobs, next one has a single active job, and one pending. Others
1905 // should all be queued.
1906 for (int i = 0; i < 10; ++i) {
1907 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(
1908 base::StringPrintf("ok%i", i))->Resolve());
1910 EXPECT_EQ(10u, num_running_dispatcher_jobs());
1912 resolver_.reset();
1915 // Cancel a request with only the IPv6 transaction active.
1916 TEST_F(HostResolverImplDnsTest, CancelWithIPv6TransactionActive) {
1917 ChangeDnsConfig(CreateValidDnsConfig());
1919 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("6slow_ok", 80)->Resolve());
1920 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1922 // The IPv4 request should complete, the IPv6 request is still pending.
1923 base::RunLoop().RunUntilIdle();
1924 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1925 requests_[0]->Cancel();
1927 // Dispatcher state checked in TearDown.
1930 // Cancel a request with only the IPv4 transaction pending.
1931 TEST_F(HostResolverImplDnsTest, CancelWithIPv4TransactionPending) {
1932 set_fallback_to_proctask(false);
1933 ChangeDnsConfig(CreateValidDnsConfig());
1935 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_ok", 80)->Resolve());
1936 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1938 // The IPv6 request should complete, the IPv4 request is still pending.
1939 base::RunLoop().RunUntilIdle();
1940 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1942 requests_[0]->Cancel();
1945 // Test cases where AAAA completes first.
1946 TEST_F(HostResolverImplDnsTest, AAAACompletesFirst) {
1947 set_fallback_to_proctask(false);
1948 ChangeDnsConfig(CreateValidDnsConfig());
1950 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_ok", 80)->Resolve());
1951 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_4ok", 80)->Resolve());
1952 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_4timeout", 80)->Resolve());
1953 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_6timeout", 80)->Resolve());
1955 base::RunLoop().RunUntilIdle();
1956 EXPECT_FALSE(requests_[0]->completed());
1957 EXPECT_FALSE(requests_[1]->completed());
1958 EXPECT_FALSE(requests_[2]->completed());
1959 // The IPv6 of the third request should have failed and resulted in cancelling
1960 // the IPv4 request.
1961 EXPECT_TRUE(requests_[3]->completed());
1962 EXPECT_EQ(ERR_DNS_TIMED_OUT, requests_[3]->result());
1963 EXPECT_EQ(3u, num_running_dispatcher_jobs());
1965 dns_client_->CompleteDelayedTransactions();
1966 EXPECT_TRUE(requests_[0]->completed());
1967 EXPECT_EQ(OK, requests_[0]->result());
1968 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses());
1969 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80));
1970 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80));
1972 EXPECT_TRUE(requests_[1]->completed());
1973 EXPECT_EQ(OK, requests_[1]->result());
1974 EXPECT_EQ(1u, requests_[1]->NumberOfAddresses());
1975 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80));
1977 EXPECT_TRUE(requests_[2]->completed());
1978 EXPECT_EQ(ERR_DNS_TIMED_OUT, requests_[2]->result());
1981 // Test the case where only a single transaction slot is available.
1982 TEST_F(HostResolverImplDnsTest, SerialResolver) {
1983 CreateSerialResolver();
1984 set_fallback_to_proctask(false);
1985 ChangeDnsConfig(CreateValidDnsConfig());
1987 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve());
1988 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1990 base::RunLoop().RunUntilIdle();
1991 EXPECT_TRUE(requests_[0]->completed());
1992 EXPECT_EQ(OK, requests_[0]->result());
1993 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses());
1994 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80));
1995 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80));
1998 // Test the case where the AAAA query is started when another transaction
1999 // completes.
2000 TEST_F(HostResolverImplDnsTest, AAAAStartsAfterOtherJobFinishes) {
2001 CreateResolverWithLimitsAndParams(2u, DefaultParams(proc_.get()));
2002 set_fallback_to_proctask(false);
2003 ChangeDnsConfig(CreateValidDnsConfig());
2005 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM,
2006 ADDRESS_FAMILY_IPV4)->Resolve());
2007 EXPECT_EQ(ERR_IO_PENDING,
2008 CreateRequest("4slow_ok", 80, MEDIUM)->Resolve());
2009 // An IPv4 request should have been started pending for each job.
2010 EXPECT_EQ(2u, num_running_dispatcher_jobs());
2012 // Request 0's IPv4 request should complete, starting Request 1's IPv6
2013 // request, which should also complete.
2014 base::RunLoop().RunUntilIdle();
2015 EXPECT_EQ(1u, num_running_dispatcher_jobs());
2016 EXPECT_TRUE(requests_[0]->completed());
2017 EXPECT_FALSE(requests_[1]->completed());
2019 dns_client_->CompleteDelayedTransactions();
2020 EXPECT_TRUE(requests_[1]->completed());
2021 EXPECT_EQ(OK, requests_[1]->result());
2022 EXPECT_EQ(2u, requests_[1]->NumberOfAddresses());
2023 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80));
2024 EXPECT_TRUE(requests_[1]->HasAddress("::1", 80));
2027 // Tests the case that a Job with a single transaction receives an empty address
2028 // list, triggering fallback to ProcTask.
2029 TEST_F(HostResolverImplDnsTest, IPv4EmptyFallback) {
2030 ChangeDnsConfig(CreateValidDnsConfig());
2031 proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
2032 proc_->SignalMultiple(1u);
2033 EXPECT_EQ(ERR_IO_PENDING,
2034 CreateRequest("empty_fallback", 80, MEDIUM,
2035 ADDRESS_FAMILY_IPV4)->Resolve());
2036 EXPECT_EQ(OK, requests_[0]->WaitForResult());
2037 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
2040 // Tests the case that a Job with two transactions receives two empty address
2041 // lists, triggering fallback to ProcTask.
2042 TEST_F(HostResolverImplDnsTest, UnspecEmptyFallback) {
2043 ChangeDnsConfig(CreateValidDnsConfig());
2044 proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
2045 proc_->SignalMultiple(1u);
2046 EXPECT_EQ(ERR_IO_PENDING,
2047 CreateRequest("empty_fallback", 80, MEDIUM,
2048 ADDRESS_FAMILY_UNSPECIFIED)->Resolve());
2049 EXPECT_EQ(OK, requests_[0]->WaitForResult());
2050 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
2053 // Tests getting a new invalid DnsConfig while there are active DnsTasks.
2054 TEST_F(HostResolverImplDnsTest, InvalidDnsConfigWithPendingRequests) {
2055 // At most 3 jobs active at once. This number is important, since we want to
2056 // make sure that aborting the first HostResolverImpl::Job does not trigger
2057 // another DnsTransaction on the second Job when it releases its second
2058 // prioritized dispatcher slot.
2059 CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_.get()));
2061 ChangeDnsConfig(CreateValidDnsConfig());
2063 proc_->AddRuleForAllFamilies("slow_nx1", "192.168.0.1");
2064 proc_->AddRuleForAllFamilies("slow_nx2", "192.168.0.2");
2065 proc_->AddRuleForAllFamilies("ok", "192.168.0.3");
2067 // First active job gets two slots.
2068 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_nx1")->Resolve());
2069 // Next job gets one slot, and waits on another.
2070 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_nx2")->Resolve());
2071 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok")->Resolve());
2073 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2075 // Clear DNS config. Two in-progress jobs should be aborted, and the next one
2076 // should use a ProcTask.
2077 ChangeDnsConfig(DnsConfig());
2078 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->WaitForResult());
2079 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[1]->WaitForResult());
2081 // Finish up the third job. Should bypass the DnsClient, and get its results
2082 // from MockHostResolverProc.
2083 EXPECT_FALSE(requests_[2]->completed());
2084 proc_->SignalMultiple(1u);
2085 EXPECT_EQ(OK, requests_[2]->WaitForResult());
2086 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80));
2089 // Tests the case that DnsClient is automatically disabled due to failures
2090 // while there are active DnsTasks.
2091 TEST_F(HostResolverImplDnsTest,
2092 AutomaticallyDisableDnsClientWithPendingRequests) {
2093 // Trying different limits is important for this test: Different limits
2094 // result in different behavior when aborting in-progress DnsTasks. Having
2095 // a DnsTask that has one job active and one in the queue when another job
2096 // occupying two slots has its DnsTask aborted is the case most likely to run
2097 // into problems.
2098 for (size_t limit = 1u; limit < 6u; ++limit) {
2099 CreateResolverWithLimitsAndParams(limit, DefaultParams(proc_.get()));
2101 ChangeDnsConfig(CreateValidDnsConfig());
2103 // Queue up enough failures to disable DnsTasks. These will all fall back
2104 // to ProcTasks, and succeed there.
2105 for (unsigned i = 0u; i < maximum_dns_failures(); ++i) {
2106 std::string host = base::StringPrintf("nx%u", i);
2107 proc_->AddRuleForAllFamilies(host, "192.168.0.1");
2108 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(host)->Resolve());
2111 // These requests should all bypass DnsTasks, due to the above failures,
2112 // so should end up using ProcTasks.
2113 proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.2");
2114 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok1")->Resolve());
2115 proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.3");
2116 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok2")->Resolve());
2117 proc_->AddRuleForAllFamilies("slow_ok3", "192.168.0.4");
2118 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok3")->Resolve());
2119 proc_->SignalMultiple(maximum_dns_failures() + 3);
2121 for (size_t i = 0u; i < maximum_dns_failures(); ++i) {
2122 EXPECT_EQ(OK, requests_[i]->WaitForResult());
2123 EXPECT_TRUE(requests_[i]->HasOneAddress("192.168.0.1", 80));
2126 EXPECT_EQ(OK, requests_[maximum_dns_failures()]->WaitForResult());
2127 EXPECT_TRUE(requests_[maximum_dns_failures()]->HasOneAddress(
2128 "192.168.0.2", 80));
2129 EXPECT_EQ(OK, requests_[maximum_dns_failures() + 1]->WaitForResult());
2130 EXPECT_TRUE(requests_[maximum_dns_failures() + 1]->HasOneAddress(
2131 "192.168.0.3", 80));
2132 EXPECT_EQ(OK, requests_[maximum_dns_failures() + 2]->WaitForResult());
2133 EXPECT_TRUE(requests_[maximum_dns_failures() + 2]->HasOneAddress(
2134 "192.168.0.4", 80));
2135 requests_.clear();
2139 // Tests a call to SetDnsClient while there are active DnsTasks.
2140 TEST_F(HostResolverImplDnsTest, ManuallyDisableDnsClientWithPendingRequests) {
2141 // At most 3 jobs active at once. This number is important, since we want to
2142 // make sure that aborting the first HostResolverImpl::Job does not trigger
2143 // another DnsTransaction on the second Job when it releases its second
2144 // prioritized dispatcher slot.
2145 CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_.get()));
2147 ChangeDnsConfig(CreateValidDnsConfig());
2149 proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.1");
2150 proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.2");
2151 proc_->AddRuleForAllFamilies("ok", "192.168.0.3");
2153 // First active job gets two slots.
2154 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok1")->Resolve());
2155 // Next job gets one slot, and waits on another.
2156 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok2")->Resolve());
2157 // Next one is queued.
2158 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok")->Resolve());
2160 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2162 // Clear DnsClient. The two in-progress jobs should fall back to a ProcTask,
2163 // and the next one should be started with a ProcTask.
2164 resolver_->SetDnsClient(scoped_ptr<DnsClient>());
2166 // All three in-progress requests should now be running a ProcTask.
2167 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2168 proc_->SignalMultiple(3u);
2170 EXPECT_EQ(OK, requests_[0]->WaitForResult());
2171 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80));
2172 EXPECT_EQ(OK, requests_[1]->WaitForResult());
2173 EXPECT_TRUE(requests_[1]->HasOneAddress("192.168.0.2", 80));
2174 EXPECT_EQ(OK, requests_[2]->WaitForResult());
2175 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80));
2178 } // namespace net