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. 4 5 #include "net/dns/host_resolver_impl.h" 6 7 #include <algorithm> 8 #include <string> 9 10 #include "base/bind.h" 11 #include "base/bind_helpers.h" 12 #include "base/memory/ref_counted.h" 13 #include "base/memory/scoped_vector.h" 14 #include "base/message_loop/message_loop.h" 15 #include "base/run_loop.h" 16 #include "base/strings/string_util.h" 17 #include "base/strings/stringprintf.h" 18 #include "base/synchronization/condition_variable.h" 19 #include "base/synchronization/lock.h" 20 #include "base/test/test_timeouts.h" 21 #include "base/time/time.h" 22 #include "net/base/address_list.h" 23 #include "net/base/net_errors.h" 24 #include "net/base/net_util.h" 25 #include "net/dns/dns_client.h" 26 #include "net/dns/dns_test_util.h" 27 #include "net/dns/host_cache.h" 28 #include "net/dns/mock_host_resolver.h" 29 #include "testing/gtest/include/gtest/gtest.h" 30 31 namespace net { 32 33 namespace { 34 35 const size_t kMaxJobs = 10u; 36 const size_t kMaxRetryAttempts = 4u; 37 38 PrioritizedDispatcher::Limits DefaultLimits() { 39 PrioritizedDispatcher::Limits limits(NUM_PRIORITIES, kMaxJobs); 40 return limits; 41 } 42 43 HostResolverImpl::ProcTaskParams DefaultParams( 44 HostResolverProc* resolver_proc) { 45 return HostResolverImpl::ProcTaskParams(resolver_proc, kMaxRetryAttempts); 46 } 47 48 // A HostResolverProc that pushes each host mapped into a list and allows 49 // waiting for a specific number of requests. Unlike RuleBasedHostResolverProc 50 // it never calls SystemHostResolverCall. By default resolves all hostnames to 51 // "127.0.0.1". After AddRule(), it resolves only names explicitly specified. 52 class MockHostResolverProc : public HostResolverProc { 53 public: 54 struct ResolveKey { 55 ResolveKey(const std::string& hostname, AddressFamily address_family) 56 : hostname(hostname), address_family(address_family) {} 57 bool operator<(const ResolveKey& other) const { 58 return address_family < other.address_family || 59 (address_family == other.address_family && hostname < other.hostname); 60 } 61 std::string hostname; 62 AddressFamily address_family; 63 }; 64 65 typedef std::vector<ResolveKey> CaptureList; 66 67 MockHostResolverProc() 68 : HostResolverProc(NULL), 69 num_requests_waiting_(0), 70 num_slots_available_(0), 71 requests_waiting_(&lock_), 72 slots_available_(&lock_) { 73 } 74 75 // Waits until |count| calls to |Resolve| are blocked. Returns false when 76 // timed out. 77 bool WaitFor(unsigned count) { 78 base::AutoLock lock(lock_); 79 base::Time start_time = base::Time::Now(); 80 while (num_requests_waiting_ < count) { 81 requests_waiting_.TimedWait(TestTimeouts::action_timeout()); 82 if (base::Time::Now() > start_time + TestTimeouts::action_timeout()) 83 return false; 84 } 85 return true; 86 } 87 88 // Signals |count| waiting calls to |Resolve|. First come first served. 89 void SignalMultiple(unsigned count) { 90 base::AutoLock lock(lock_); 91 num_slots_available_ += count; 92 slots_available_.Broadcast(); 93 } 94 95 // Signals all waiting calls to |Resolve|. Beware of races. 96 void SignalAll() { 97 base::AutoLock lock(lock_); 98 num_slots_available_ = num_requests_waiting_; 99 slots_available_.Broadcast(); 100 } 101 102 void AddRule(const std::string& hostname, AddressFamily family, 103 const AddressList& result) { 104 base::AutoLock lock(lock_); 105 rules_[ResolveKey(hostname, family)] = result; 106 } 107 108 void AddRule(const std::string& hostname, AddressFamily family, 109 const std::string& ip_list) { 110 AddressList result; 111 int rv = ParseAddressList(ip_list, std::string(), &result); 112 DCHECK_EQ(OK, rv); 113 AddRule(hostname, family, result); 114 } 115 116 void AddRuleForAllFamilies(const std::string& hostname, 117 const std::string& ip_list) { 118 AddressList result; 119 int rv = ParseAddressList(ip_list, std::string(), &result); 120 DCHECK_EQ(OK, rv); 121 AddRule(hostname, ADDRESS_FAMILY_UNSPECIFIED, result); 122 AddRule(hostname, ADDRESS_FAMILY_IPV4, result); 123 AddRule(hostname, ADDRESS_FAMILY_IPV6, result); 124 } 125 126 virtual int Resolve(const std::string& hostname, 127 AddressFamily address_family, 128 HostResolverFlags host_resolver_flags, 129 AddressList* addrlist, 130 int* os_error) OVERRIDE { 131 base::AutoLock lock(lock_); 132 capture_list_.push_back(ResolveKey(hostname, address_family)); 133 ++num_requests_waiting_; 134 requests_waiting_.Broadcast(); 135 while (!num_slots_available_) 136 slots_available_.Wait(); 137 DCHECK_GT(num_requests_waiting_, 0u); 138 --num_slots_available_; 139 --num_requests_waiting_; 140 if (rules_.empty()) { 141 int rv = ParseAddressList("127.0.0.1", std::string(), addrlist); 142 DCHECK_EQ(OK, rv); 143 return OK; 144 } 145 ResolveKey key(hostname, address_family); 146 if (rules_.count(key) == 0) 147 return ERR_NAME_NOT_RESOLVED; 148 *addrlist = rules_[key]; 149 return OK; 150 } 151 152 CaptureList GetCaptureList() const { 153 CaptureList copy; 154 { 155 base::AutoLock lock(lock_); 156 copy = capture_list_; 157 } 158 return copy; 159 } 160 161 bool HasBlockedRequests() const { 162 base::AutoLock lock(lock_); 163 return num_requests_waiting_ > num_slots_available_; 164 } 165 166 protected: 167 virtual ~MockHostResolverProc() {} 168 169 private: 170 mutable base::Lock lock_; 171 std::map<ResolveKey, AddressList> rules_; 172 CaptureList capture_list_; 173 unsigned num_requests_waiting_; 174 unsigned num_slots_available_; 175 base::ConditionVariable requests_waiting_; 176 base::ConditionVariable slots_available_; 177 178 DISALLOW_COPY_AND_ASSIGN(MockHostResolverProc); 179 }; 180 181 bool AddressListContains(const AddressList& list, const std::string& address, 182 int port) { 183 IPAddressNumber ip; 184 bool rv = ParseIPLiteralToNumber(address, &ip); 185 DCHECK(rv); 186 return std::find(list.begin(), 187 list.end(), 188 IPEndPoint(ip, port)) != list.end(); 189 } 190 191 // A wrapper for requests to a HostResolver. 192 class Request { 193 public: 194 // Base class of handlers to be executed on completion of requests. 195 struct Handler { 196 virtual ~Handler() {} 197 virtual void Handle(Request* request) = 0; 198 }; 199 200 Request(const HostResolver::RequestInfo& info, 201 RequestPriority priority, 202 size_t index, 203 HostResolver* resolver, 204 Handler* handler) 205 : info_(info), 206 priority_(priority), 207 index_(index), 208 resolver_(resolver), 209 handler_(handler), 210 quit_on_complete_(false), 211 result_(ERR_UNEXPECTED), 212 handle_(NULL) {} 213 214 int Resolve() { 215 DCHECK(resolver_); 216 DCHECK(!handle_); 217 list_ = AddressList(); 218 result_ = resolver_->Resolve( 219 info_, 220 priority_, 221 &list_, 222 base::Bind(&Request::OnComplete, base::Unretained(this)), 223 &handle_, 224 BoundNetLog()); 225 if (!list_.empty()) 226 EXPECT_EQ(OK, result_); 227 return result_; 228 } 229 230 int ResolveFromCache() { 231 DCHECK(resolver_); 232 DCHECK(!handle_); 233 return resolver_->ResolveFromCache(info_, &list_, BoundNetLog()); 234 } 235 236 void Cancel() { 237 DCHECK(resolver_); 238 DCHECK(handle_); 239 resolver_->CancelRequest(handle_); 240 handle_ = NULL; 241 } 242 243 const HostResolver::RequestInfo& info() const { return info_; } 244 size_t index() const { return index_; } 245 const AddressList& list() const { return list_; } 246 int result() const { return result_; } 247 bool completed() const { return result_ != ERR_IO_PENDING; } 248 bool pending() const { return handle_ != NULL; } 249 250 bool HasAddress(const std::string& address, int port) const { 251 return AddressListContains(list_, address, port); 252 } 253 254 // Returns the number of addresses in |list_|. 255 unsigned NumberOfAddresses() const { 256 return list_.size(); 257 } 258 259 bool HasOneAddress(const std::string& address, int port) const { 260 return HasAddress(address, port) && (NumberOfAddresses() == 1u); 261 } 262 263 // Returns ERR_UNEXPECTED if timed out. 264 int WaitForResult() { 265 if (completed()) 266 return result_; 267 base::CancelableClosure closure(base::MessageLoop::QuitClosure()); 268 base::MessageLoop::current()->PostDelayedTask( 269 FROM_HERE, closure.callback(), TestTimeouts::action_max_timeout()); 270 quit_on_complete_ = true; 271 base::MessageLoop::current()->Run(); 272 bool did_quit = !quit_on_complete_; 273 quit_on_complete_ = false; 274 closure.Cancel(); 275 if (did_quit) 276 return result_; 277 else 278 return ERR_UNEXPECTED; 279 } 280 281 private: 282 void OnComplete(int rv) { 283 EXPECT_TRUE(pending()); 284 EXPECT_EQ(ERR_IO_PENDING, result_); 285 EXPECT_NE(ERR_IO_PENDING, rv); 286 result_ = rv; 287 handle_ = NULL; 288 if (!list_.empty()) { 289 EXPECT_EQ(OK, result_); 290 EXPECT_EQ(info_.port(), list_.front().port()); 291 } 292 if (handler_) 293 handler_->Handle(this); 294 if (quit_on_complete_) { 295 base::MessageLoop::current()->Quit(); 296 quit_on_complete_ = false; 297 } 298 } 299 300 HostResolver::RequestInfo info_; 301 RequestPriority priority_; 302 size_t index_; 303 HostResolver* resolver_; 304 Handler* handler_; 305 bool quit_on_complete_; 306 307 AddressList list_; 308 int result_; 309 HostResolver::RequestHandle handle_; 310 311 DISALLOW_COPY_AND_ASSIGN(Request); 312 }; 313 314 // Using LookupAttemptHostResolverProc simulate very long lookups, and control 315 // which attempt resolves the host. 316 class LookupAttemptHostResolverProc : public HostResolverProc { 317 public: 318 LookupAttemptHostResolverProc(HostResolverProc* previous, 319 int attempt_number_to_resolve, 320 int total_attempts) 321 : HostResolverProc(previous), 322 attempt_number_to_resolve_(attempt_number_to_resolve), 323 current_attempt_number_(0), 324 total_attempts_(total_attempts), 325 total_attempts_resolved_(0), 326 resolved_attempt_number_(0), 327 all_done_(&lock_) { 328 } 329 330 // Test harness will wait for all attempts to finish before checking the 331 // results. 332 void WaitForAllAttemptsToFinish(const base::TimeDelta& wait_time) { 333 base::TimeTicks end_time = base::TimeTicks::Now() + wait_time; 334 { 335 base::AutoLock auto_lock(lock_); 336 while (total_attempts_resolved_ != total_attempts_ && 337 base::TimeTicks::Now() < end_time) { 338 all_done_.TimedWait(end_time - base::TimeTicks::Now()); 339 } 340 } 341 } 342 343 // All attempts will wait for an attempt to resolve the host. 344 void WaitForAnAttemptToComplete() { 345 base::TimeDelta wait_time = base::TimeDelta::FromSeconds(60); 346 base::TimeTicks end_time = base::TimeTicks::Now() + wait_time; 347 { 348 base::AutoLock auto_lock(lock_); 349 while (resolved_attempt_number_ == 0 && base::TimeTicks::Now() < end_time) 350 all_done_.TimedWait(end_time - base::TimeTicks::Now()); 351 } 352 all_done_.Broadcast(); // Tell all waiting attempts to proceed. 353 } 354 355 // Returns the number of attempts that have finished the Resolve() method. 356 int total_attempts_resolved() { return total_attempts_resolved_; } 357 358 // Returns the first attempt that that has resolved the host. 359 int resolved_attempt_number() { return resolved_attempt_number_; } 360 361 // HostResolverProc methods. 362 virtual int Resolve(const std::string& host, 363 AddressFamily address_family, 364 HostResolverFlags host_resolver_flags, 365 AddressList* addrlist, 366 int* os_error) OVERRIDE { 367 bool wait_for_right_attempt_to_complete = true; 368 { 369 base::AutoLock auto_lock(lock_); 370 ++current_attempt_number_; 371 if (current_attempt_number_ == attempt_number_to_resolve_) { 372 resolved_attempt_number_ = current_attempt_number_; 373 wait_for_right_attempt_to_complete = false; 374 } 375 } 376 377 if (wait_for_right_attempt_to_complete) 378 // Wait for the attempt_number_to_resolve_ attempt to resolve. 379 WaitForAnAttemptToComplete(); 380 381 int result = ResolveUsingPrevious(host, address_family, host_resolver_flags, 382 addrlist, os_error); 383 384 { 385 base::AutoLock auto_lock(lock_); 386 ++total_attempts_resolved_; 387 } 388 389 all_done_.Broadcast(); // Tell all attempts to proceed. 390 391 // Since any negative number is considered a network error, with -1 having 392 // special meaning (ERR_IO_PENDING). We could return the attempt that has 393 // resolved the host as a negative number. For example, if attempt number 3 394 // resolves the host, then this method returns -4. 395 if (result == OK) 396 return -1 - resolved_attempt_number_; 397 else 398 return result; 399 } 400 401 protected: 402 virtual ~LookupAttemptHostResolverProc() {} 403 404 private: 405 int attempt_number_to_resolve_; 406 int current_attempt_number_; // Incremented whenever Resolve is called. 407 int total_attempts_; 408 int total_attempts_resolved_; 409 int resolved_attempt_number_; 410 411 // All attempts wait for right attempt to be resolve. 412 base::Lock lock_; 413 base::ConditionVariable all_done_; 414 }; 415 416 } // namespace 417 418 class HostResolverImplTest : public testing::Test { 419 public: 420 static const int kDefaultPort = 80; 421 422 HostResolverImplTest() : proc_(new MockHostResolverProc()) {} 423 424 void CreateResolver() { 425 CreateResolverWithLimitsAndParams(DefaultLimits(), 426 DefaultParams(proc_.get())); 427 } 428 429 // This HostResolverImpl will only allow 1 outstanding resolve at a time and 430 // perform no retries. 431 void CreateSerialResolver() { 432 HostResolverImpl::ProcTaskParams params = DefaultParams(proc_.get()); 433 params.max_retry_attempts = 0u; 434 PrioritizedDispatcher::Limits limits(NUM_PRIORITIES, 1); 435 CreateResolverWithLimitsAndParams(limits, params); 436 } 437 438 protected: 439 // A Request::Handler which is a proxy to the HostResolverImplTest fixture. 440 struct Handler : public Request::Handler { 441 virtual ~Handler() {} 442 443 // Proxy functions so that classes derived from Handler can access them. 444 Request* CreateRequest(const HostResolver::RequestInfo& info, 445 RequestPriority priority) { 446 return test->CreateRequest(info, priority); 447 } 448 Request* CreateRequest(const std::string& hostname, int port) { 449 return test->CreateRequest(hostname, port); 450 } 451 Request* CreateRequest(const std::string& hostname) { 452 return test->CreateRequest(hostname); 453 } 454 ScopedVector<Request>& requests() { return test->requests_; } 455 456 void DeleteResolver() { test->resolver_.reset(); } 457 458 HostResolverImplTest* test; 459 }; 460 461 // testing::Test implementation: 462 virtual void SetUp() OVERRIDE { 463 CreateResolver(); 464 } 465 466 virtual void TearDown() OVERRIDE { 467 if (resolver_.get()) 468 EXPECT_EQ(0u, resolver_->num_running_dispatcher_jobs_for_tests()); 469 EXPECT_FALSE(proc_->HasBlockedRequests()); 470 } 471 472 virtual void CreateResolverWithLimitsAndParams( 473 const PrioritizedDispatcher::Limits& limits, 474 const HostResolverImpl::ProcTaskParams& params) { 475 resolver_.reset(new HostResolverImpl(HostCache::CreateDefaultCache(), 476 limits, params, NULL)); 477 } 478 479 // The Request will not be made until a call to |Resolve()|, and the Job will 480 // not start until released by |proc_->SignalXXX|. 481 Request* CreateRequest(const HostResolver::RequestInfo& info, 482 RequestPriority priority) { 483 Request* req = new Request( 484 info, priority, requests_.size(), resolver_.get(), handler_.get()); 485 requests_.push_back(req); 486 return req; 487 } 488 489 Request* CreateRequest(const std::string& hostname, 490 int port, 491 RequestPriority priority, 492 AddressFamily family) { 493 HostResolver::RequestInfo info(HostPortPair(hostname, port)); 494 info.set_address_family(family); 495 return CreateRequest(info, priority); 496 } 497 498 Request* CreateRequest(const std::string& hostname, 499 int port, 500 RequestPriority priority) { 501 return CreateRequest(hostname, port, priority, ADDRESS_FAMILY_UNSPECIFIED); 502 } 503 504 Request* CreateRequest(const std::string& hostname, int port) { 505 return CreateRequest(hostname, port, MEDIUM); 506 } 507 508 Request* CreateRequest(const std::string& hostname) { 509 return CreateRequest(hostname, kDefaultPort); 510 } 511 512 void set_handler(Handler* handler) { 513 handler_.reset(handler); 514 handler_->test = this; 515 } 516 517 // Friendship is not inherited, so use proxies to access those. 518 size_t num_running_dispatcher_jobs() const { 519 DCHECK(resolver_.get()); 520 return resolver_->num_running_dispatcher_jobs_for_tests(); 521 } 522 523 void set_fallback_to_proctask(bool fallback_to_proctask) { 524 DCHECK(resolver_.get()); 525 resolver_->fallback_to_proctask_ = fallback_to_proctask; 526 } 527 528 static unsigned maximum_dns_failures() { 529 return HostResolverImpl::kMaximumDnsFailures; 530 } 531 532 scoped_refptr<MockHostResolverProc> proc_; 533 scoped_ptr<HostResolverImpl> resolver_; 534 ScopedVector<Request> requests_; 535 536 scoped_ptr<Handler> handler_; 537 }; 538 539 TEST_F(HostResolverImplTest, AsynchronousLookup) { 540 proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); 541 proc_->SignalMultiple(1u); 542 543 Request* req = CreateRequest("just.testing", 80); 544 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 545 EXPECT_EQ(OK, req->WaitForResult()); 546 547 EXPECT_TRUE(req->HasOneAddress("192.168.1.42", 80)); 548 549 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname); 550 } 551 552 TEST_F(HostResolverImplTest, EmptyListMeansNameNotResolved) { 553 proc_->AddRuleForAllFamilies("just.testing", ""); 554 proc_->SignalMultiple(1u); 555 556 Request* req = CreateRequest("just.testing", 80); 557 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 558 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult()); 559 EXPECT_EQ(0u, req->NumberOfAddresses()); 560 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname); 561 } 562 563 TEST_F(HostResolverImplTest, FailedAsynchronousLookup) { 564 proc_->AddRuleForAllFamilies(std::string(), 565 "0.0.0.0"); // Default to failures. 566 proc_->SignalMultiple(1u); 567 568 Request* req = CreateRequest("just.testing", 80); 569 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 570 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult()); 571 572 EXPECT_EQ("just.testing", proc_->GetCaptureList()[0].hostname); 573 574 // Also test that the error is not cached. 575 EXPECT_EQ(ERR_DNS_CACHE_MISS, req->ResolveFromCache()); 576 } 577 578 TEST_F(HostResolverImplTest, AbortedAsynchronousLookup) { 579 Request* req0 = CreateRequest("just.testing", 80); 580 EXPECT_EQ(ERR_IO_PENDING, req0->Resolve()); 581 582 EXPECT_TRUE(proc_->WaitFor(1u)); 583 584 // Resolver is destroyed while job is running on WorkerPool. 585 resolver_.reset(); 586 587 proc_->SignalAll(); 588 589 // To ensure there was no spurious callback, complete with a new resolver. 590 CreateResolver(); 591 Request* req1 = CreateRequest("just.testing", 80); 592 EXPECT_EQ(ERR_IO_PENDING, req1->Resolve()); 593 594 proc_->SignalMultiple(2u); 595 596 EXPECT_EQ(OK, req1->WaitForResult()); 597 598 // This request was canceled. 599 EXPECT_FALSE(req0->completed()); 600 } 601 602 TEST_F(HostResolverImplTest, NumericIPv4Address) { 603 // Stevens says dotted quads with AI_UNSPEC resolve to a single sockaddr_in. 604 Request* req = CreateRequest("127.1.2.3", 5555); 605 EXPECT_EQ(OK, req->Resolve()); 606 607 EXPECT_TRUE(req->HasOneAddress("127.1.2.3", 5555)); 608 } 609 610 TEST_F(HostResolverImplTest, NumericIPv6Address) { 611 // Resolve a plain IPv6 address. Don't worry about [brackets], because 612 // the caller should have removed them. 613 Request* req = CreateRequest("2001:db8::1", 5555); 614 EXPECT_EQ(OK, req->Resolve()); 615 616 EXPECT_TRUE(req->HasOneAddress("2001:db8::1", 5555)); 617 } 618 619 TEST_F(HostResolverImplTest, EmptyHost) { 620 Request* req = CreateRequest(std::string(), 5555); 621 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve()); 622 } 623 624 TEST_F(HostResolverImplTest, EmptyDotsHost) { 625 for (int i = 0; i < 16; ++i) { 626 Request* req = CreateRequest(std::string(i, '.'), 5555); 627 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve()); 628 } 629 } 630 631 #if defined(THREAD_SANITIZER) 632 // There's a data race in this test that may lead to use-after-free. 633 // If the test starts to crash without ThreadSanitizer it needs to be disabled 634 // globally. See http://crbug.com/268946. 635 #define MAYBE_LongHost DISABLED_LongHost 636 #else 637 #define MAYBE_LongHost LongHost 638 #endif 639 TEST_F(HostResolverImplTest, MAYBE_LongHost) { 640 Request* req = CreateRequest(std::string(4097, 'a'), 5555); 641 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->Resolve()); 642 } 643 644 TEST_F(HostResolverImplTest, DeDupeRequests) { 645 // Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is 646 // blocked, these should all pile up until we signal it. 647 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve()); 648 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 80)->Resolve()); 649 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 81)->Resolve()); 650 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 82)->Resolve()); 651 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve()); 652 653 proc_->SignalMultiple(2u); // One for "a", one for "b". 654 655 for (size_t i = 0; i < requests_.size(); ++i) { 656 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; 657 } 658 } 659 660 TEST_F(HostResolverImplTest, CancelMultipleRequests) { 661 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve()); 662 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 80)->Resolve()); 663 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 81)->Resolve()); 664 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 82)->Resolve()); 665 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve()); 666 667 // Cancel everything except request for ("a", 82). 668 requests_[0]->Cancel(); 669 requests_[1]->Cancel(); 670 requests_[2]->Cancel(); 671 requests_[4]->Cancel(); 672 673 proc_->SignalMultiple(2u); // One for "a", one for "b". 674 675 EXPECT_EQ(OK, requests_[3]->WaitForResult()); 676 } 677 678 TEST_F(HostResolverImplTest, CanceledRequestsReleaseJobSlots) { 679 // Fill up the dispatcher and queue. 680 for (unsigned i = 0; i < kMaxJobs + 1; ++i) { 681 std::string hostname = "a_"; 682 hostname[1] = 'a' + i; 683 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve()); 684 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 81)->Resolve()); 685 } 686 687 EXPECT_TRUE(proc_->WaitFor(kMaxJobs)); 688 689 // Cancel all but last two. 690 for (unsigned i = 0; i < requests_.size() - 2; ++i) { 691 requests_[i]->Cancel(); 692 } 693 694 EXPECT_TRUE(proc_->WaitFor(kMaxJobs + 1)); 695 696 proc_->SignalAll(); 697 698 size_t num_requests = requests_.size(); 699 EXPECT_EQ(OK, requests_[num_requests - 1]->WaitForResult()); 700 EXPECT_EQ(OK, requests_[num_requests - 2]->result()); 701 } 702 703 TEST_F(HostResolverImplTest, CancelWithinCallback) { 704 struct MyHandler : public Handler { 705 virtual void Handle(Request* req) OVERRIDE { 706 // Port 80 is the first request that the callback will be invoked for. 707 // While we are executing within that callback, cancel the other requests 708 // in the job and start another request. 709 if (req->index() == 0) { 710 // Once "a:80" completes, it will cancel "a:81" and "a:82". 711 requests()[1]->Cancel(); 712 requests()[2]->Cancel(); 713 } 714 } 715 }; 716 set_handler(new MyHandler()); 717 718 for (size_t i = 0; i < 4; ++i) { 719 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i; 720 } 721 722 proc_->SignalMultiple(2u); // One for "a". One for "finalrequest". 723 724 EXPECT_EQ(OK, requests_[0]->WaitForResult()); 725 726 Request* final_request = CreateRequest("finalrequest", 70); 727 EXPECT_EQ(ERR_IO_PENDING, final_request->Resolve()); 728 EXPECT_EQ(OK, final_request->WaitForResult()); 729 EXPECT_TRUE(requests_[3]->completed()); 730 } 731 732 TEST_F(HostResolverImplTest, DeleteWithinCallback) { 733 struct MyHandler : public Handler { 734 virtual void Handle(Request* req) OVERRIDE { 735 EXPECT_EQ("a", req->info().hostname()); 736 EXPECT_EQ(80, req->info().port()); 737 738 DeleteResolver(); 739 740 // Quit after returning from OnCompleted (to give it a chance at 741 // incorrectly running the cancelled tasks). 742 base::MessageLoop::current()->PostTask(FROM_HERE, 743 base::MessageLoop::QuitClosure()); 744 } 745 }; 746 set_handler(new MyHandler()); 747 748 for (size_t i = 0; i < 4; ++i) { 749 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i; 750 } 751 752 proc_->SignalMultiple(1u); // One for "a". 753 754 // |MyHandler| will send quit message once all the requests have finished. 755 base::MessageLoop::current()->Run(); 756 } 757 758 TEST_F(HostResolverImplTest, DeleteWithinAbortedCallback) { 759 struct MyHandler : public Handler { 760 virtual void Handle(Request* req) OVERRIDE { 761 EXPECT_EQ("a", req->info().hostname()); 762 EXPECT_EQ(80, req->info().port()); 763 764 DeleteResolver(); 765 766 // Quit after returning from OnCompleted (to give it a chance at 767 // incorrectly running the cancelled tasks). 768 base::MessageLoop::current()->PostTask(FROM_HERE, 769 base::MessageLoop::QuitClosure()); 770 } 771 }; 772 set_handler(new MyHandler()); 773 774 // This test assumes that the Jobs will be Aborted in order ["a", "b"] 775 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve()); 776 // HostResolverImpl will be deleted before later Requests can complete. 777 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 81)->Resolve()); 778 // Job for 'b' will be aborted before it can complete. 779 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 82)->Resolve()); 780 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b", 83)->Resolve()); 781 782 EXPECT_TRUE(proc_->WaitFor(1u)); 783 784 // Triggering an IP address change. 785 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests(); 786 787 // |MyHandler| will send quit message once all the requests have finished. 788 base::MessageLoop::current()->Run(); 789 790 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->result()); 791 EXPECT_EQ(ERR_IO_PENDING, requests_[1]->result()); 792 EXPECT_EQ(ERR_IO_PENDING, requests_[2]->result()); 793 EXPECT_EQ(ERR_IO_PENDING, requests_[3]->result()); 794 // Clean up. 795 proc_->SignalMultiple(requests_.size()); 796 } 797 798 TEST_F(HostResolverImplTest, StartWithinCallback) { 799 struct MyHandler : public Handler { 800 virtual void Handle(Request* req) OVERRIDE { 801 if (req->index() == 0) { 802 // On completing the first request, start another request for "a". 803 // Since caching is disabled, this will result in another async request. 804 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 70)->Resolve()); 805 } 806 } 807 }; 808 set_handler(new MyHandler()); 809 810 // Turn off caching for this host resolver. 811 resolver_.reset(new HostResolverImpl(scoped_ptr<HostCache>(), 812 DefaultLimits(), 813 DefaultParams(proc_.get()), 814 NULL)); 815 816 for (size_t i = 0; i < 4; ++i) { 817 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80 + i)->Resolve()) << i; 818 } 819 820 proc_->SignalMultiple(2u); // One for "a". One for the second "a". 821 822 EXPECT_EQ(OK, requests_[0]->WaitForResult()); 823 ASSERT_EQ(5u, requests_.size()); 824 EXPECT_EQ(OK, requests_.back()->WaitForResult()); 825 826 EXPECT_EQ(2u, proc_->GetCaptureList().size()); 827 } 828 829 TEST_F(HostResolverImplTest, BypassCache) { 830 struct MyHandler : public Handler { 831 virtual void Handle(Request* req) OVERRIDE { 832 if (req->index() == 0) { 833 // On completing the first request, start another request for "a". 834 // Since caching is enabled, this should complete synchronously. 835 std::string hostname = req->info().hostname(); 836 EXPECT_EQ(OK, CreateRequest(hostname, 70)->Resolve()); 837 EXPECT_EQ(OK, CreateRequest(hostname, 75)->ResolveFromCache()); 838 839 // Ok good. Now make sure that if we ask to bypass the cache, it can no 840 // longer service the request synchronously. 841 HostResolver::RequestInfo info(HostPortPair(hostname, 71)); 842 info.set_allow_cached_response(false); 843 EXPECT_EQ(ERR_IO_PENDING, 844 CreateRequest(info, DEFAULT_PRIORITY)->Resolve()); 845 } else if (71 == req->info().port()) { 846 // Test is done. 847 base::MessageLoop::current()->Quit(); 848 } else { 849 FAIL() << "Unexpected request"; 850 } 851 } 852 }; 853 set_handler(new MyHandler()); 854 855 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a", 80)->Resolve()); 856 proc_->SignalMultiple(3u); // Only need two, but be generous. 857 858 // |verifier| will send quit message once all the requests have finished. 859 base::MessageLoop::current()->Run(); 860 EXPECT_EQ(2u, proc_->GetCaptureList().size()); 861 } 862 863 // Test that IP address changes flush the cache. 864 TEST_F(HostResolverImplTest, FlushCacheOnIPAddressChange) { 865 proc_->SignalMultiple(2u); // One before the flush, one after. 866 867 Request* req = CreateRequest("host1", 70); 868 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 869 EXPECT_EQ(OK, req->WaitForResult()); 870 871 req = CreateRequest("host1", 75); 872 EXPECT_EQ(OK, req->Resolve()); // Should complete synchronously. 873 874 // Flush cache by triggering an IP address change. 875 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests(); 876 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async. 877 878 // Resolve "host1" again -- this time it won't be served from cache, so it 879 // will complete asynchronously. 880 req = CreateRequest("host1", 80); 881 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 882 EXPECT_EQ(OK, req->WaitForResult()); 883 } 884 885 // Test that IP address changes send ERR_NETWORK_CHANGED to pending requests. 886 TEST_F(HostResolverImplTest, AbortOnIPAddressChanged) { 887 Request* req = CreateRequest("host1", 70); 888 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 889 890 EXPECT_TRUE(proc_->WaitFor(1u)); 891 // Triggering an IP address change. 892 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests(); 893 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async. 894 proc_->SignalAll(); 895 896 EXPECT_EQ(ERR_NETWORK_CHANGED, req->WaitForResult()); 897 EXPECT_EQ(0u, resolver_->GetHostCache()->size()); 898 } 899 900 // Obey pool constraints after IP address has changed. 901 TEST_F(HostResolverImplTest, ObeyPoolConstraintsAfterIPAddressChange) { 902 // Runs at most one job at a time. 903 CreateSerialResolver(); 904 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("a")->Resolve()); 905 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("b")->Resolve()); 906 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("c")->Resolve()); 907 908 EXPECT_TRUE(proc_->WaitFor(1u)); 909 // Triggering an IP address change. 910 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests(); 911 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async. 912 proc_->SignalMultiple(3u); // Let the false-start go so that we can catch it. 913 914 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->WaitForResult()); 915 916 EXPECT_EQ(1u, num_running_dispatcher_jobs()); 917 918 EXPECT_FALSE(requests_[1]->completed()); 919 EXPECT_FALSE(requests_[2]->completed()); 920 921 EXPECT_EQ(OK, requests_[2]->WaitForResult()); 922 EXPECT_EQ(OK, requests_[1]->result()); 923 } 924 925 // Tests that a new Request made from the callback of a previously aborted one 926 // will not be aborted. 927 TEST_F(HostResolverImplTest, AbortOnlyExistingRequestsOnIPAddressChange) { 928 struct MyHandler : public Handler { 929 virtual void Handle(Request* req) OVERRIDE { 930 // Start new request for a different hostname to ensure that the order 931 // of jobs in HostResolverImpl is not stable. 932 std::string hostname; 933 if (req->index() == 0) 934 hostname = "zzz"; 935 else if (req->index() == 1) 936 hostname = "aaa"; 937 else if (req->index() == 2) 938 hostname = "eee"; 939 else 940 return; // A request started from within MyHandler. 941 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname)->Resolve()) << hostname; 942 } 943 }; 944 set_handler(new MyHandler()); 945 946 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("bbb")->Resolve()); 947 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("eee")->Resolve()); 948 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ccc")->Resolve()); 949 950 // Wait until all are blocked; 951 EXPECT_TRUE(proc_->WaitFor(3u)); 952 // Trigger an IP address change. 953 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests(); 954 // This should abort all running jobs. 955 base::MessageLoop::current()->RunUntilIdle(); 956 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->result()); 957 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[1]->result()); 958 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[2]->result()); 959 ASSERT_EQ(6u, requests_.size()); 960 // Unblock all calls to proc. 961 proc_->SignalMultiple(requests_.size()); 962 // Run until the re-started requests finish. 963 EXPECT_EQ(OK, requests_[3]->WaitForResult()); 964 EXPECT_EQ(OK, requests_[4]->WaitForResult()); 965 EXPECT_EQ(OK, requests_[5]->WaitForResult()); 966 // Verify that results of aborted Jobs were not cached. 967 EXPECT_EQ(6u, proc_->GetCaptureList().size()); 968 EXPECT_EQ(3u, resolver_->GetHostCache()->size()); 969 } 970 971 // Tests that when the maximum threads is set to 1, requests are dequeued 972 // in order of priority. 973 TEST_F(HostResolverImplTest, HigherPriorityRequestsStartedFirst) { 974 CreateSerialResolver(); 975 976 // Note that at this point the MockHostResolverProc is blocked, so any 977 // requests we make will not complete. 978 CreateRequest("req0", 80, LOW); 979 CreateRequest("req1", 80, MEDIUM); 980 CreateRequest("req2", 80, MEDIUM); 981 CreateRequest("req3", 80, LOW); 982 CreateRequest("req4", 80, HIGHEST); 983 CreateRequest("req5", 80, LOW); 984 CreateRequest("req6", 80, LOW); 985 CreateRequest("req5", 80, HIGHEST); 986 987 for (size_t i = 0; i < requests_.size(); ++i) { 988 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i; 989 } 990 991 // Unblock the resolver thread so the requests can run. 992 proc_->SignalMultiple(requests_.size()); // More than needed. 993 994 // Wait for all the requests to complete succesfully. 995 for (size_t i = 0; i < requests_.size(); ++i) { 996 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; 997 } 998 999 // Since we have restricted to a single concurrent thread in the jobpool, 1000 // the requests should complete in order of priority (with the exception 1001 // of the first request, which gets started right away, since there is 1002 // nothing outstanding). 1003 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList(); 1004 ASSERT_EQ(7u, capture_list.size()); 1005 1006 EXPECT_EQ("req0", capture_list[0].hostname); 1007 EXPECT_EQ("req4", capture_list[1].hostname); 1008 EXPECT_EQ("req5", capture_list[2].hostname); 1009 EXPECT_EQ("req1", capture_list[3].hostname); 1010 EXPECT_EQ("req2", capture_list[4].hostname); 1011 EXPECT_EQ("req3", capture_list[5].hostname); 1012 EXPECT_EQ("req6", capture_list[6].hostname); 1013 } 1014 1015 // Try cancelling a job which has not started yet. 1016 TEST_F(HostResolverImplTest, CancelPendingRequest) { 1017 CreateSerialResolver(); 1018 1019 CreateRequest("req0", 80, LOWEST); 1020 CreateRequest("req1", 80, HIGHEST); // Will cancel. 1021 CreateRequest("req2", 80, MEDIUM); 1022 CreateRequest("req3", 80, LOW); 1023 CreateRequest("req4", 80, HIGHEST); // Will cancel. 1024 CreateRequest("req5", 80, LOWEST); // Will cancel. 1025 CreateRequest("req6", 80, MEDIUM); 1026 1027 // Start all of the requests. 1028 for (size_t i = 0; i < requests_.size(); ++i) { 1029 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i; 1030 } 1031 1032 // Cancel some requests 1033 requests_[1]->Cancel(); 1034 requests_[4]->Cancel(); 1035 requests_[5]->Cancel(); 1036 1037 // Unblock the resolver thread so the requests can run. 1038 proc_->SignalMultiple(requests_.size()); // More than needed. 1039 1040 // Wait for all the requests to complete succesfully. 1041 for (size_t i = 0; i < requests_.size(); ++i) { 1042 if (!requests_[i]->pending()) 1043 continue; // Don't wait for the requests we cancelled. 1044 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; 1045 } 1046 1047 // Verify that they called out the the resolver proc (which runs on the 1048 // resolver thread) in the expected order. 1049 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList(); 1050 ASSERT_EQ(4u, capture_list.size()); 1051 1052 EXPECT_EQ("req0", capture_list[0].hostname); 1053 EXPECT_EQ("req2", capture_list[1].hostname); 1054 EXPECT_EQ("req6", capture_list[2].hostname); 1055 EXPECT_EQ("req3", capture_list[3].hostname); 1056 } 1057 1058 // Test that when too many requests are enqueued, old ones start to be aborted. 1059 TEST_F(HostResolverImplTest, QueueOverflow) { 1060 CreateSerialResolver(); 1061 1062 // Allow only 3 queued jobs. 1063 const size_t kMaxPendingJobs = 3u; 1064 resolver_->SetMaxQueuedJobs(kMaxPendingJobs); 1065 1066 // Note that at this point the MockHostResolverProc is blocked, so any 1067 // requests we make will not complete. 1068 1069 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req0", 80, LOWEST)->Resolve()); 1070 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req1", 80, HIGHEST)->Resolve()); 1071 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req2", 80, MEDIUM)->Resolve()); 1072 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req3", 80, MEDIUM)->Resolve()); 1073 1074 // At this point, there are 3 enqueued jobs. 1075 // Insertion of subsequent requests will cause evictions 1076 // based on priority. 1077 1078 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, 1079 CreateRequest("req4", 80, LOW)->Resolve()); // Evicts itself! 1080 1081 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req5", 80, MEDIUM)->Resolve()); 1082 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[2]->result()); 1083 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req6", 80, HIGHEST)->Resolve()); 1084 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[3]->result()); 1085 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("req7", 80, MEDIUM)->Resolve()); 1086 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE, requests_[5]->result()); 1087 1088 // Unblock the resolver thread so the requests can run. 1089 proc_->SignalMultiple(4u); 1090 1091 // The rest should succeed. 1092 EXPECT_EQ(OK, requests_[7]->WaitForResult()); 1093 EXPECT_EQ(OK, requests_[0]->result()); 1094 EXPECT_EQ(OK, requests_[1]->result()); 1095 EXPECT_EQ(OK, requests_[6]->result()); 1096 1097 // Verify that they called out the the resolver proc (which runs on the 1098 // resolver thread) in the expected order. 1099 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList(); 1100 ASSERT_EQ(4u, capture_list.size()); 1101 1102 EXPECT_EQ("req0", capture_list[0].hostname); 1103 EXPECT_EQ("req1", capture_list[1].hostname); 1104 EXPECT_EQ("req6", capture_list[2].hostname); 1105 EXPECT_EQ("req7", capture_list[3].hostname); 1106 1107 // Verify that the evicted (incomplete) requests were not cached. 1108 EXPECT_EQ(4u, resolver_->GetHostCache()->size()); 1109 1110 for (size_t i = 0; i < requests_.size(); ++i) { 1111 EXPECT_TRUE(requests_[i]->completed()) << i; 1112 } 1113 } 1114 1115 // Tests that after changing the default AddressFamily to IPV4, requests 1116 // with UNSPECIFIED address family map to IPV4. 1117 TEST_F(HostResolverImplTest, SetDefaultAddressFamily_IPv4) { 1118 CreateSerialResolver(); // To guarantee order of resolutions. 1119 1120 proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1"); 1121 proc_->AddRule("h1", ADDRESS_FAMILY_IPV6, "::2"); 1122 1123 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4); 1124 1125 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED); 1126 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV4); 1127 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV6); 1128 1129 // Start all of the requests. 1130 for (size_t i = 0; i < requests_.size(); ++i) { 1131 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i; 1132 } 1133 1134 proc_->SignalMultiple(requests_.size()); 1135 1136 // Wait for all the requests to complete. 1137 for (size_t i = 0u; i < requests_.size(); ++i) { 1138 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; 1139 } 1140 1141 // Since the requests all had the same priority and we limited the thread 1142 // count to 1, they should have completed in the same order as they were 1143 // requested. Moreover, request0 and request1 will have been serviced by 1144 // the same job. 1145 1146 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList(); 1147 ASSERT_EQ(2u, capture_list.size()); 1148 1149 EXPECT_EQ("h1", capture_list[0].hostname); 1150 EXPECT_EQ(ADDRESS_FAMILY_IPV4, capture_list[0].address_family); 1151 1152 EXPECT_EQ("h1", capture_list[1].hostname); 1153 EXPECT_EQ(ADDRESS_FAMILY_IPV6, capture_list[1].address_family); 1154 1155 // Now check that the correct resolved IP addresses were returned. 1156 EXPECT_TRUE(requests_[0]->HasOneAddress("1.0.0.1", 80)); 1157 EXPECT_TRUE(requests_[1]->HasOneAddress("1.0.0.1", 80)); 1158 EXPECT_TRUE(requests_[2]->HasOneAddress("::2", 80)); 1159 } 1160 1161 // This is the exact same test as SetDefaultAddressFamily_IPv4, except the 1162 // default family is set to IPv6 and the family of requests is flipped where 1163 // specified. 1164 TEST_F(HostResolverImplTest, SetDefaultAddressFamily_IPv6) { 1165 CreateSerialResolver(); // To guarantee order of resolutions. 1166 1167 // Don't use IPv6 replacements here since some systems don't support it. 1168 proc_->AddRule("h1", ADDRESS_FAMILY_IPV4, "1.0.0.1"); 1169 proc_->AddRule("h1", ADDRESS_FAMILY_IPV6, "::2"); 1170 1171 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV6); 1172 1173 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_UNSPECIFIED); 1174 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV6); 1175 CreateRequest("h1", 80, MEDIUM, ADDRESS_FAMILY_IPV4); 1176 1177 // Start all of the requests. 1178 for (size_t i = 0; i < requests_.size(); ++i) { 1179 EXPECT_EQ(ERR_IO_PENDING, requests_[i]->Resolve()) << i; 1180 } 1181 1182 proc_->SignalMultiple(requests_.size()); 1183 1184 // Wait for all the requests to complete. 1185 for (size_t i = 0u; i < requests_.size(); ++i) { 1186 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; 1187 } 1188 1189 // Since the requests all had the same priority and we limited the thread 1190 // count to 1, they should have completed in the same order as they were 1191 // requested. Moreover, request0 and request1 will have been serviced by 1192 // the same job. 1193 1194 MockHostResolverProc::CaptureList capture_list = proc_->GetCaptureList(); 1195 ASSERT_EQ(2u, capture_list.size()); 1196 1197 EXPECT_EQ("h1", capture_list[0].hostname); 1198 EXPECT_EQ(ADDRESS_FAMILY_IPV6, capture_list[0].address_family); 1199 1200 EXPECT_EQ("h1", capture_list[1].hostname); 1201 EXPECT_EQ(ADDRESS_FAMILY_IPV4, capture_list[1].address_family); 1202 1203 // Now check that the correct resolved IP addresses were returned. 1204 EXPECT_TRUE(requests_[0]->HasOneAddress("::2", 80)); 1205 EXPECT_TRUE(requests_[1]->HasOneAddress("::2", 80)); 1206 EXPECT_TRUE(requests_[2]->HasOneAddress("1.0.0.1", 80)); 1207 } 1208 1209 TEST_F(HostResolverImplTest, ResolveFromCache) { 1210 proc_->AddRuleForAllFamilies("just.testing", "192.168.1.42"); 1211 proc_->SignalMultiple(1u); // Need only one. 1212 1213 HostResolver::RequestInfo info(HostPortPair("just.testing", 80)); 1214 1215 // First hit will miss the cache. 1216 EXPECT_EQ(ERR_DNS_CACHE_MISS, 1217 CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache()); 1218 1219 // This time, we fetch normally. 1220 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info, DEFAULT_PRIORITY)->Resolve()); 1221 EXPECT_EQ(OK, requests_[1]->WaitForResult()); 1222 1223 // Now we should be able to fetch from the cache. 1224 EXPECT_EQ(OK, CreateRequest(info, DEFAULT_PRIORITY)->ResolveFromCache()); 1225 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.1.42", 80)); 1226 } 1227 1228 // Test the retry attempts simulating host resolver proc that takes too long. 1229 TEST_F(HostResolverImplTest, MultipleAttempts) { 1230 // Total number of attempts would be 3 and we want the 3rd attempt to resolve 1231 // the host. First and second attempt will be forced to sleep until they get 1232 // word that a resolution has completed. The 3rd resolution attempt will try 1233 // to get done ASAP, and won't sleep.. 1234 int kAttemptNumberToResolve = 3; 1235 int kTotalAttempts = 3; 1236 1237 scoped_refptr<LookupAttemptHostResolverProc> resolver_proc( 1238 new LookupAttemptHostResolverProc( 1239 NULL, kAttemptNumberToResolve, kTotalAttempts)); 1240 1241 HostResolverImpl::ProcTaskParams params = DefaultParams(resolver_proc.get()); 1242 1243 // Specify smaller interval for unresponsive_delay_ for HostResolverImpl so 1244 // that unit test runs faster. For example, this test finishes in 1.5 secs 1245 // (500ms * 3). 1246 params.unresponsive_delay = base::TimeDelta::FromMilliseconds(500); 1247 1248 resolver_.reset( 1249 new HostResolverImpl(HostCache::CreateDefaultCache(), 1250 DefaultLimits(), 1251 params, 1252 NULL)); 1253 1254 // Resolve "host1". 1255 HostResolver::RequestInfo info(HostPortPair("host1", 70)); 1256 Request* req = CreateRequest(info, DEFAULT_PRIORITY); 1257 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 1258 1259 // Resolve returns -4 to indicate that 3rd attempt has resolved the host. 1260 EXPECT_EQ(-4, req->WaitForResult()); 1261 1262 resolver_proc->WaitForAllAttemptsToFinish( 1263 base::TimeDelta::FromMilliseconds(60000)); 1264 base::MessageLoop::current()->RunUntilIdle(); 1265 1266 EXPECT_EQ(resolver_proc->total_attempts_resolved(), kTotalAttempts); 1267 EXPECT_EQ(resolver_proc->resolved_attempt_number(), kAttemptNumberToResolve); 1268 } 1269 1270 DnsConfig CreateValidDnsConfig() { 1271 IPAddressNumber dns_ip; 1272 bool rv = ParseIPLiteralToNumber("192.168.1.0", &dns_ip); 1273 EXPECT_TRUE(rv); 1274 1275 DnsConfig config; 1276 config.nameservers.push_back(IPEndPoint(dns_ip, dns_protocol::kDefaultPort)); 1277 EXPECT_TRUE(config.IsValid()); 1278 return config; 1279 } 1280 1281 // Specialized fixture for tests of DnsTask. 1282 class HostResolverImplDnsTest : public HostResolverImplTest { 1283 public: 1284 HostResolverImplDnsTest() : dns_client_(NULL) {} 1285 1286 protected: 1287 // testing::Test implementation: 1288 virtual void SetUp() OVERRIDE { 1289 AddDnsRule("nx", dns_protocol::kTypeA, MockDnsClientRule::FAIL, false); 1290 AddDnsRule("nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL, false); 1291 AddDnsRule("ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false); 1292 AddDnsRule("ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK, false); 1293 AddDnsRule("4ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false); 1294 AddDnsRule("4ok", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY, false); 1295 AddDnsRule("6ok", dns_protocol::kTypeA, MockDnsClientRule::EMPTY, false); 1296 AddDnsRule("6ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK, false); 1297 AddDnsRule("4nx", dns_protocol::kTypeA, MockDnsClientRule::OK, false); 1298 AddDnsRule("4nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL, false); 1299 AddDnsRule("empty", dns_protocol::kTypeA, MockDnsClientRule::EMPTY, false); 1300 AddDnsRule("empty", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY, 1301 false); 1302 1303 AddDnsRule("slow_nx", dns_protocol::kTypeA, MockDnsClientRule::FAIL, true); 1304 AddDnsRule("slow_nx", dns_protocol::kTypeAAAA, MockDnsClientRule::FAIL, 1305 true); 1306 1307 AddDnsRule("4slow_ok", dns_protocol::kTypeA, MockDnsClientRule::OK, true); 1308 AddDnsRule("4slow_ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK, 1309 false); 1310 AddDnsRule("6slow_ok", dns_protocol::kTypeA, MockDnsClientRule::OK, false); 1311 AddDnsRule("6slow_ok", dns_protocol::kTypeAAAA, MockDnsClientRule::OK, 1312 true); 1313 AddDnsRule("4slow_4ok", dns_protocol::kTypeA, MockDnsClientRule::OK, true); 1314 AddDnsRule("4slow_4ok", dns_protocol::kTypeAAAA, MockDnsClientRule::EMPTY, 1315 false); 1316 AddDnsRule("4slow_4timeout", dns_protocol::kTypeA, 1317 MockDnsClientRule::TIMEOUT, true); 1318 AddDnsRule("4slow_4timeout", dns_protocol::kTypeAAAA, MockDnsClientRule::OK, 1319 false); 1320 AddDnsRule("4slow_6timeout", dns_protocol::kTypeA, 1321 MockDnsClientRule::OK, true); 1322 AddDnsRule("4slow_6timeout", dns_protocol::kTypeAAAA, 1323 MockDnsClientRule::TIMEOUT, false); 1324 CreateResolver(); 1325 } 1326 1327 // HostResolverImplTest implementation: 1328 virtual void CreateResolverWithLimitsAndParams( 1329 const PrioritizedDispatcher::Limits& limits, 1330 const HostResolverImpl::ProcTaskParams& params) OVERRIDE { 1331 resolver_.reset(new HostResolverImpl(HostCache::CreateDefaultCache(), 1332 limits, 1333 params, 1334 NULL)); 1335 // Disable IPv6 support probing. 1336 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 1337 dns_client_ = new MockDnsClient(DnsConfig(), dns_rules_); 1338 resolver_->SetDnsClient(scoped_ptr<DnsClient>(dns_client_)); 1339 } 1340 1341 // Adds a rule to |dns_rules_|. Must be followed by |CreateResolver| to apply. 1342 void AddDnsRule(const std::string& prefix, 1343 uint16 qtype, 1344 MockDnsClientRule::Result result, 1345 bool delay) { 1346 dns_rules_.push_back(MockDnsClientRule(prefix, qtype, result, delay)); 1347 } 1348 1349 void ChangeDnsConfig(const DnsConfig& config) { 1350 NetworkChangeNotifier::SetDnsConfig(config); 1351 // Notification is delivered asynchronously. 1352 base::MessageLoop::current()->RunUntilIdle(); 1353 } 1354 1355 MockDnsClientRuleList dns_rules_; 1356 // Owned by |resolver_|. 1357 MockDnsClient* dns_client_; 1358 }; 1359 1360 // TODO(szym): Test AbortAllInProgressJobs due to DnsConfig change. 1361 1362 // TODO(cbentzel): Test a mix of requests with different HostResolverFlags. 1363 1364 // Test successful and fallback resolutions in HostResolverImpl::DnsTask. 1365 TEST_F(HostResolverImplDnsTest, DnsTask) { 1366 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4); 1367 1368 proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102"); 1369 // All other hostnames will fail in proc_. 1370 1371 // Initially there is no config, so client should not be invoked. 1372 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve()); 1373 proc_->SignalMultiple(requests_.size()); 1374 1375 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult()); 1376 1377 ChangeDnsConfig(CreateValidDnsConfig()); 1378 1379 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve()); 1380 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_fail", 80)->Resolve()); 1381 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_succeed", 80)->Resolve()); 1382 1383 proc_->SignalMultiple(requests_.size()); 1384 1385 for (size_t i = 1; i < requests_.size(); ++i) 1386 EXPECT_NE(ERR_UNEXPECTED, requests_[i]->WaitForResult()) << i; 1387 1388 EXPECT_EQ(OK, requests_[1]->result()); 1389 // Resolved by MockDnsClient. 1390 EXPECT_TRUE(requests_[1]->HasOneAddress("127.0.0.1", 80)); 1391 // Fallback to ProcTask. 1392 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[2]->result()); 1393 EXPECT_EQ(OK, requests_[3]->result()); 1394 EXPECT_TRUE(requests_[3]->HasOneAddress("192.168.1.102", 80)); 1395 } 1396 1397 // Test successful and failing resolutions in HostResolverImpl::DnsTask when 1398 // fallback to ProcTask is disabled. 1399 TEST_F(HostResolverImplDnsTest, NoFallbackToProcTask) { 1400 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4); 1401 set_fallback_to_proctask(false); 1402 1403 proc_->AddRuleForAllFamilies("nx_succeed", "192.168.1.102"); 1404 // All other hostnames will fail in proc_. 1405 1406 // Set empty DnsConfig. 1407 ChangeDnsConfig(DnsConfig()); 1408 // Initially there is no config, so client should not be invoked. 1409 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve()); 1410 // There is no config, so fallback to ProcTask must work. 1411 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_succeed", 80)->Resolve()); 1412 proc_->SignalMultiple(requests_.size()); 1413 1414 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult()); 1415 EXPECT_EQ(OK, requests_[1]->WaitForResult()); 1416 EXPECT_TRUE(requests_[1]->HasOneAddress("192.168.1.102", 80)); 1417 1418 ChangeDnsConfig(CreateValidDnsConfig()); 1419 1420 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_abort", 80)->Resolve()); 1421 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80)->Resolve()); 1422 1423 // Simulate the case when the preference or policy has disabled the DNS client 1424 // causing AbortDnsTasks. 1425 resolver_->SetDnsClient( 1426 scoped_ptr<DnsClient>(new MockDnsClient(DnsConfig(), dns_rules_))); 1427 ChangeDnsConfig(CreateValidDnsConfig()); 1428 1429 // First request is resolved by MockDnsClient, others should fail due to 1430 // disabled fallback to ProcTask. 1431 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok_fail", 80)->Resolve()); 1432 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_fail", 80)->Resolve()); 1433 proc_->SignalMultiple(requests_.size()); 1434 1435 // Aborted due to Network Change. 1436 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[2]->WaitForResult()); 1437 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[3]->WaitForResult()); 1438 // Resolved by MockDnsClient. 1439 EXPECT_EQ(OK, requests_[4]->WaitForResult()); 1440 EXPECT_TRUE(requests_[4]->HasOneAddress("127.0.0.1", 80)); 1441 // Fallback to ProcTask is disabled. 1442 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[5]->WaitForResult()); 1443 } 1444 1445 // Test behavior of OnDnsTaskFailure when Job is aborted. 1446 TEST_F(HostResolverImplDnsTest, OnDnsTaskFailureAbortedJob) { 1447 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4); 1448 ChangeDnsConfig(CreateValidDnsConfig()); 1449 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80)->Resolve()); 1450 // Abort all jobs here. 1451 CreateResolver(); 1452 proc_->SignalMultiple(requests_.size()); 1453 // Run to completion. 1454 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async. 1455 // It shouldn't crash during OnDnsTaskFailure callbacks. 1456 EXPECT_EQ(ERR_IO_PENDING, requests_[0]->result()); 1457 1458 // Repeat test with Fallback to ProcTask disabled 1459 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4); 1460 set_fallback_to_proctask(false); 1461 ChangeDnsConfig(CreateValidDnsConfig()); 1462 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("nx_abort", 80)->Resolve()); 1463 // Abort all jobs here. 1464 CreateResolver(); 1465 // Run to completion. 1466 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async. 1467 // It shouldn't crash during OnDnsTaskFailure callbacks. 1468 EXPECT_EQ(ERR_IO_PENDING, requests_[1]->result()); 1469 } 1470 1471 TEST_F(HostResolverImplDnsTest, DnsTaskUnspec) { 1472 ChangeDnsConfig(CreateValidDnsConfig()); 1473 1474 proc_->AddRuleForAllFamilies("4nx", "192.168.1.101"); 1475 // All other hostnames will fail in proc_. 1476 1477 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve()); 1478 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4ok", 80)->Resolve()); 1479 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("6ok", 80)->Resolve()); 1480 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4nx", 80)->Resolve()); 1481 1482 proc_->SignalMultiple(requests_.size()); 1483 1484 for (size_t i = 0; i < requests_.size(); ++i) 1485 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; 1486 1487 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses()); 1488 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80)); 1489 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80)); 1490 EXPECT_EQ(1u, requests_[1]->NumberOfAddresses()); 1491 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80)); 1492 EXPECT_EQ(1u, requests_[2]->NumberOfAddresses()); 1493 EXPECT_TRUE(requests_[2]->HasAddress("::1", 80)); 1494 EXPECT_EQ(1u, requests_[3]->NumberOfAddresses()); 1495 EXPECT_TRUE(requests_[3]->HasAddress("192.168.1.101", 80)); 1496 } 1497 1498 TEST_F(HostResolverImplDnsTest, ServeFromHosts) { 1499 // Initially, use empty HOSTS file. 1500 DnsConfig config = CreateValidDnsConfig(); 1501 ChangeDnsConfig(config); 1502 1503 proc_->AddRuleForAllFamilies(std::string(), 1504 std::string()); // Default to failures. 1505 proc_->SignalMultiple(1u); // For the first request which misses. 1506 1507 Request* req0 = CreateRequest("nx_ipv4", 80); 1508 EXPECT_EQ(ERR_IO_PENDING, req0->Resolve()); 1509 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req0->WaitForResult()); 1510 1511 IPAddressNumber local_ipv4, local_ipv6; 1512 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4)); 1513 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6)); 1514 1515 DnsHosts hosts; 1516 hosts[DnsHostsKey("nx_ipv4", ADDRESS_FAMILY_IPV4)] = local_ipv4; 1517 hosts[DnsHostsKey("nx_ipv6", ADDRESS_FAMILY_IPV6)] = local_ipv6; 1518 hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV4)] = local_ipv4; 1519 hosts[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV6)] = local_ipv6; 1520 1521 // Update HOSTS file. 1522 config.hosts = hosts; 1523 ChangeDnsConfig(config); 1524 1525 Request* req1 = CreateRequest("nx_ipv4", 80); 1526 EXPECT_EQ(OK, req1->Resolve()); 1527 EXPECT_TRUE(req1->HasOneAddress("127.0.0.1", 80)); 1528 1529 Request* req2 = CreateRequest("nx_ipv6", 80); 1530 EXPECT_EQ(OK, req2->Resolve()); 1531 EXPECT_TRUE(req2->HasOneAddress("::1", 80)); 1532 1533 Request* req3 = CreateRequest("nx_both", 80); 1534 EXPECT_EQ(OK, req3->Resolve()); 1535 EXPECT_TRUE(req3->HasAddress("127.0.0.1", 80) && 1536 req3->HasAddress("::1", 80)); 1537 1538 // Requests with specified AddressFamily. 1539 Request* req4 = CreateRequest("nx_ipv4", 80, MEDIUM, ADDRESS_FAMILY_IPV4); 1540 EXPECT_EQ(OK, req4->Resolve()); 1541 EXPECT_TRUE(req4->HasOneAddress("127.0.0.1", 80)); 1542 1543 Request* req5 = CreateRequest("nx_ipv6", 80, MEDIUM, ADDRESS_FAMILY_IPV6); 1544 EXPECT_EQ(OK, req5->Resolve()); 1545 EXPECT_TRUE(req5->HasOneAddress("::1", 80)); 1546 1547 // Request with upper case. 1548 Request* req6 = CreateRequest("nx_IPV4", 80); 1549 EXPECT_EQ(OK, req6->Resolve()); 1550 EXPECT_TRUE(req6->HasOneAddress("127.0.0.1", 80)); 1551 } 1552 1553 TEST_F(HostResolverImplDnsTest, BypassDnsTask) { 1554 ChangeDnsConfig(CreateValidDnsConfig()); 1555 1556 proc_->AddRuleForAllFamilies(std::string(), 1557 std::string()); // Default to failures. 1558 1559 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok.local", 80)->Resolve()); 1560 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok.local.", 80)->Resolve()); 1561 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("oklocal", 80)->Resolve()); 1562 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("oklocal.", 80)->Resolve()); 1563 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve()); 1564 1565 proc_->SignalMultiple(requests_.size()); 1566 1567 for (size_t i = 0; i < 2; ++i) 1568 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[i]->WaitForResult()) << i; 1569 1570 for (size_t i = 2; i < requests_.size(); ++i) 1571 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; 1572 } 1573 1574 TEST_F(HostResolverImplDnsTest, SystemOnlyBypassesDnsTask) { 1575 ChangeDnsConfig(CreateValidDnsConfig()); 1576 1577 proc_->AddRuleForAllFamilies(std::string(), std::string()); 1578 1579 HostResolver::RequestInfo info_bypass(HostPortPair("ok", 80)); 1580 info_bypass.set_host_resolver_flags(HOST_RESOLVER_SYSTEM_ONLY); 1581 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info_bypass, MEDIUM)->Resolve()); 1582 1583 HostResolver::RequestInfo info(HostPortPair("ok", 80)); 1584 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(info, MEDIUM)->Resolve()); 1585 1586 proc_->SignalMultiple(requests_.size()); 1587 1588 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, requests_[0]->WaitForResult()); 1589 EXPECT_EQ(OK, requests_[1]->WaitForResult()); 1590 } 1591 1592 TEST_F(HostResolverImplDnsTest, DisableDnsClientOnPersistentFailure) { 1593 ChangeDnsConfig(CreateValidDnsConfig()); 1594 1595 proc_->AddRuleForAllFamilies(std::string(), 1596 std::string()); // Default to failures. 1597 1598 // Check that DnsTask works. 1599 Request* req = CreateRequest("ok_1", 80); 1600 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 1601 EXPECT_EQ(OK, req->WaitForResult()); 1602 1603 for (unsigned i = 0; i < maximum_dns_failures(); ++i) { 1604 // Use custom names to require separate Jobs. 1605 std::string hostname = base::StringPrintf("nx_%u", i); 1606 // Ensure fallback to ProcTask succeeds. 1607 proc_->AddRuleForAllFamilies(hostname, "192.168.1.101"); 1608 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve()) << i; 1609 } 1610 1611 proc_->SignalMultiple(requests_.size()); 1612 1613 for (size_t i = 0; i < requests_.size(); ++i) 1614 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; 1615 1616 ASSERT_FALSE(proc_->HasBlockedRequests()); 1617 1618 // DnsTask should be disabled by now. 1619 req = CreateRequest("ok_2", 80); 1620 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 1621 proc_->SignalMultiple(1u); 1622 EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req->WaitForResult()); 1623 1624 // Check that it is re-enabled after DNS change. 1625 ChangeDnsConfig(CreateValidDnsConfig()); 1626 req = CreateRequest("ok_3", 80); 1627 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 1628 EXPECT_EQ(OK, req->WaitForResult()); 1629 } 1630 1631 TEST_F(HostResolverImplDnsTest, DontDisableDnsClientOnSporadicFailure) { 1632 ChangeDnsConfig(CreateValidDnsConfig()); 1633 1634 // |proc_| defaults to successes. 1635 1636 // 20 failures interleaved with 20 successes. 1637 for (unsigned i = 0; i < 40; ++i) { 1638 // Use custom names to require separate Jobs. 1639 std::string hostname = (i % 2) == 0 ? base::StringPrintf("nx_%u", i) 1640 : base::StringPrintf("ok_%u", i); 1641 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(hostname, 80)->Resolve()) << i; 1642 } 1643 1644 proc_->SignalMultiple(requests_.size()); 1645 1646 for (size_t i = 0; i < requests_.size(); ++i) 1647 EXPECT_EQ(OK, requests_[i]->WaitForResult()) << i; 1648 1649 // Make |proc_| default to failures. 1650 proc_->AddRuleForAllFamilies(std::string(), std::string()); 1651 1652 // DnsTask should still be enabled. 1653 Request* req = CreateRequest("ok_last", 80); 1654 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 1655 EXPECT_EQ(OK, req->WaitForResult()); 1656 } 1657 1658 // Confirm that resolving "localhost" is unrestricted even if there are no 1659 // global IPv6 address. See SystemHostResolverCall for rationale. 1660 // Test both the DnsClient and system host resolver paths. 1661 TEST_F(HostResolverImplDnsTest, DualFamilyLocalhost) { 1662 // Use regular SystemHostResolverCall! 1663 scoped_refptr<HostResolverProc> proc(new SystemHostResolverProc()); 1664 resolver_.reset(new HostResolverImpl(HostCache::CreateDefaultCache(), 1665 DefaultLimits(), 1666 DefaultParams(proc.get()), 1667 NULL)); 1668 resolver_->SetDnsClient( 1669 scoped_ptr<DnsClient>(new MockDnsClient(DnsConfig(), dns_rules_))); 1670 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4); 1671 1672 // Get the expected output. 1673 AddressList addrlist; 1674 int rv = proc->Resolve("localhost", ADDRESS_FAMILY_UNSPECIFIED, 0, &addrlist, 1675 NULL); 1676 if (rv != OK) 1677 return; 1678 1679 for (unsigned i = 0; i < addrlist.size(); ++i) 1680 LOG(WARNING) << addrlist[i].ToString(); 1681 1682 bool saw_ipv4 = AddressListContains(addrlist, "127.0.0.1", 0); 1683 bool saw_ipv6 = AddressListContains(addrlist, "::1", 0); 1684 if (!saw_ipv4 && !saw_ipv6) 1685 return; 1686 1687 HostResolver::RequestInfo info(HostPortPair("localhost", 80)); 1688 info.set_address_family(ADDRESS_FAMILY_UNSPECIFIED); 1689 info.set_host_resolver_flags(HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6); 1690 1691 // Try without DnsClient. 1692 ChangeDnsConfig(DnsConfig()); 1693 Request* req = CreateRequest(info, DEFAULT_PRIORITY); 1694 // It is resolved via getaddrinfo, so expect asynchronous result. 1695 EXPECT_EQ(ERR_IO_PENDING, req->Resolve()); 1696 EXPECT_EQ(OK, req->WaitForResult()); 1697 1698 EXPECT_EQ(saw_ipv4, req->HasAddress("127.0.0.1", 80)); 1699 EXPECT_EQ(saw_ipv6, req->HasAddress("::1", 80)); 1700 1701 // Configure DnsClient with dual-host HOSTS file. 1702 DnsConfig config = CreateValidDnsConfig(); 1703 DnsHosts hosts; 1704 IPAddressNumber local_ipv4, local_ipv6; 1705 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4)); 1706 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6)); 1707 if (saw_ipv4) 1708 hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4)] = local_ipv4; 1709 if (saw_ipv6) 1710 hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV6)] = local_ipv6; 1711 config.hosts = hosts; 1712 1713 ChangeDnsConfig(config); 1714 req = CreateRequest(info, DEFAULT_PRIORITY); 1715 // Expect synchronous resolution from DnsHosts. 1716 EXPECT_EQ(OK, req->Resolve()); 1717 1718 EXPECT_EQ(saw_ipv4, req->HasAddress("127.0.0.1", 80)); 1719 EXPECT_EQ(saw_ipv6, req->HasAddress("::1", 80)); 1720 } 1721 1722 // Cancel a request with a single DNS transaction active. 1723 TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActive) { 1724 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4); 1725 ChangeDnsConfig(CreateValidDnsConfig()); 1726 1727 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve()); 1728 EXPECT_EQ(1u, num_running_dispatcher_jobs()); 1729 requests_[0]->Cancel(); 1730 1731 // Dispatcher state checked in TearDown. 1732 } 1733 1734 // Cancel a request with a single DNS transaction active and another pending. 1735 TEST_F(HostResolverImplDnsTest, CancelWithOneTransactionActiveOnePending) { 1736 CreateSerialResolver(); 1737 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 1738 ChangeDnsConfig(CreateValidDnsConfig()); 1739 1740 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve()); 1741 EXPECT_EQ(1u, num_running_dispatcher_jobs()); 1742 requests_[0]->Cancel(); 1743 1744 // Dispatcher state checked in TearDown. 1745 } 1746 1747 // Cancel a request with two DNS transactions active. 1748 TEST_F(HostResolverImplDnsTest, CancelWithTwoTransactionsActive) { 1749 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 1750 ChangeDnsConfig(CreateValidDnsConfig()); 1751 1752 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve()); 1753 EXPECT_EQ(2u, num_running_dispatcher_jobs()); 1754 requests_[0]->Cancel(); 1755 1756 // Dispatcher state checked in TearDown. 1757 } 1758 1759 // Delete a resolver with some active requests and some queued requests. 1760 TEST_F(HostResolverImplDnsTest, DeleteWithActiveTransactions) { 1761 // At most 10 Jobs active at once. 1762 CreateResolverWithLimitsAndParams( 1763 PrioritizedDispatcher::Limits(NUM_PRIORITIES, 10u), 1764 DefaultParams(proc_.get())); 1765 1766 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 1767 ChangeDnsConfig(CreateValidDnsConfig()); 1768 1769 // First active job is an IPv4 request. 1770 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM, 1771 ADDRESS_FAMILY_IPV4)->Resolve()); 1772 1773 // Add 10 more DNS lookups for different hostnames. First 4 should have two 1774 // active jobs, next one has a single active job, and one pending. Others 1775 // should all be queued. 1776 for (int i = 0; i < 10; ++i) { 1777 EXPECT_EQ(ERR_IO_PENDING, CreateRequest( 1778 base::StringPrintf("ok%i", i))->Resolve()); 1779 } 1780 EXPECT_EQ(10u, num_running_dispatcher_jobs()); 1781 1782 resolver_.reset(); 1783 } 1784 1785 // Cancel a request with only the IPv6 transaction active. 1786 TEST_F(HostResolverImplDnsTest, CancelWithIPv6TransactionActive) { 1787 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 1788 ChangeDnsConfig(CreateValidDnsConfig()); 1789 1790 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("6slow_ok", 80)->Resolve()); 1791 EXPECT_EQ(2u, num_running_dispatcher_jobs()); 1792 1793 // The IPv4 request should complete, the IPv6 request is still pending. 1794 base::RunLoop().RunUntilIdle(); 1795 EXPECT_EQ(1u, num_running_dispatcher_jobs()); 1796 requests_[0]->Cancel(); 1797 1798 // Dispatcher state checked in TearDown. 1799 } 1800 1801 // Cancel a request with only the IPv4 transaction pending. 1802 TEST_F(HostResolverImplDnsTest, CancelWithIPv4TransactionPending) { 1803 set_fallback_to_proctask(false); 1804 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 1805 ChangeDnsConfig(CreateValidDnsConfig()); 1806 1807 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_ok", 80)->Resolve()); 1808 EXPECT_EQ(2u, num_running_dispatcher_jobs()); 1809 1810 // The IPv6 request should complete, the IPv4 request is still pending. 1811 base::RunLoop().RunUntilIdle(); 1812 EXPECT_EQ(1u, num_running_dispatcher_jobs()); 1813 1814 requests_[0]->Cancel(); 1815 } 1816 1817 // Test cases where AAAA completes first. 1818 TEST_F(HostResolverImplDnsTest, AAAACompletesFirst) { 1819 set_fallback_to_proctask(false); 1820 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 1821 ChangeDnsConfig(CreateValidDnsConfig()); 1822 1823 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_ok", 80)->Resolve()); 1824 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_4ok", 80)->Resolve()); 1825 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_4timeout", 80)->Resolve()); 1826 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("4slow_6timeout", 80)->Resolve()); 1827 1828 base::RunLoop().RunUntilIdle(); 1829 EXPECT_FALSE(requests_[0]->completed()); 1830 EXPECT_FALSE(requests_[1]->completed()); 1831 EXPECT_FALSE(requests_[2]->completed()); 1832 // The IPv6 of the third request should have failed and resulted in cancelling 1833 // the IPv4 request. 1834 EXPECT_TRUE(requests_[3]->completed()); 1835 EXPECT_EQ(ERR_DNS_TIMED_OUT, requests_[3]->result()); 1836 EXPECT_EQ(3u, num_running_dispatcher_jobs()); 1837 1838 dns_client_->CompleteDelayedTransactions(); 1839 EXPECT_TRUE(requests_[0]->completed()); 1840 EXPECT_EQ(OK, requests_[0]->result()); 1841 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses()); 1842 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80)); 1843 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80)); 1844 1845 EXPECT_TRUE(requests_[1]->completed()); 1846 EXPECT_EQ(OK, requests_[1]->result()); 1847 EXPECT_EQ(1u, requests_[1]->NumberOfAddresses()); 1848 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80)); 1849 1850 EXPECT_TRUE(requests_[2]->completed()); 1851 EXPECT_EQ(ERR_DNS_TIMED_OUT, requests_[2]->result()); 1852 } 1853 1854 // Test the case where only a single transaction slot is available. 1855 TEST_F(HostResolverImplDnsTest, SerialResolver) { 1856 CreateSerialResolver(); 1857 set_fallback_to_proctask(false); 1858 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 1859 ChangeDnsConfig(CreateValidDnsConfig()); 1860 1861 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80)->Resolve()); 1862 EXPECT_EQ(1u, num_running_dispatcher_jobs()); 1863 1864 base::RunLoop().RunUntilIdle(); 1865 EXPECT_TRUE(requests_[0]->completed()); 1866 EXPECT_EQ(OK, requests_[0]->result()); 1867 EXPECT_EQ(2u, requests_[0]->NumberOfAddresses()); 1868 EXPECT_TRUE(requests_[0]->HasAddress("127.0.0.1", 80)); 1869 EXPECT_TRUE(requests_[0]->HasAddress("::1", 80)); 1870 } 1871 1872 // Test the case where the AAAA query is started when another transaction 1873 // completes. 1874 TEST_F(HostResolverImplDnsTest, AAAAStartsAfterOtherJobFinishes) { 1875 CreateResolverWithLimitsAndParams( 1876 PrioritizedDispatcher::Limits(NUM_PRIORITIES, 2), 1877 DefaultParams(proc_.get())); 1878 set_fallback_to_proctask(false); 1879 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 1880 ChangeDnsConfig(CreateValidDnsConfig()); 1881 1882 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok", 80, MEDIUM, 1883 ADDRESS_FAMILY_IPV4)->Resolve()); 1884 EXPECT_EQ(ERR_IO_PENDING, 1885 CreateRequest("4slow_ok", 80, MEDIUM)->Resolve()); 1886 // An IPv4 request should have been started pending for each job. 1887 EXPECT_EQ(2u, num_running_dispatcher_jobs()); 1888 1889 // Request 0's IPv4 request should complete, starting Request 1's IPv6 1890 // request, which should also complete. 1891 base::RunLoop().RunUntilIdle(); 1892 EXPECT_EQ(1u, num_running_dispatcher_jobs()); 1893 EXPECT_TRUE(requests_[0]->completed()); 1894 EXPECT_FALSE(requests_[1]->completed()); 1895 1896 dns_client_->CompleteDelayedTransactions(); 1897 EXPECT_TRUE(requests_[1]->completed()); 1898 EXPECT_EQ(OK, requests_[1]->result()); 1899 EXPECT_EQ(2u, requests_[1]->NumberOfAddresses()); 1900 EXPECT_TRUE(requests_[1]->HasAddress("127.0.0.1", 80)); 1901 EXPECT_TRUE(requests_[1]->HasAddress("::1", 80)); 1902 } 1903 1904 // Tests the case that a Job with a single transaction receives an empty address 1905 // list, triggering fallback to ProcTask. 1906 TEST_F(HostResolverImplDnsTest, IPv4EmptyFallback) { 1907 ChangeDnsConfig(CreateValidDnsConfig()); 1908 proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1"); 1909 proc_->SignalMultiple(1u); 1910 EXPECT_EQ(ERR_IO_PENDING, 1911 CreateRequest("empty_fallback", 80, MEDIUM, 1912 ADDRESS_FAMILY_IPV4)->Resolve()); 1913 EXPECT_EQ(OK, requests_[0]->WaitForResult()); 1914 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80)); 1915 } 1916 1917 // Tests the case that a Job with two transactions receives two empty address 1918 // lists, triggering fallback to ProcTask. 1919 TEST_F(HostResolverImplDnsTest, UnspecEmptyFallback) { 1920 ChangeDnsConfig(CreateValidDnsConfig()); 1921 proc_->AddRuleForAllFamilies("empty_fallback", "192.168.0.1"); 1922 proc_->SignalMultiple(1u); 1923 EXPECT_EQ(ERR_IO_PENDING, 1924 CreateRequest("empty_fallback", 80, MEDIUM, 1925 ADDRESS_FAMILY_UNSPECIFIED)->Resolve()); 1926 EXPECT_EQ(OK, requests_[0]->WaitForResult()); 1927 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80)); 1928 } 1929 1930 // Tests getting a new invalid DnsConfig while there are active DnsTasks. 1931 TEST_F(HostResolverImplDnsTest, InvalidDnsConfigWithPendingRequests) { 1932 // At most 3 jobs active at once. This number is important, since we want to 1933 // make sure that aborting the first HostResolverImpl::Job does not trigger 1934 // another DnsTransaction on the second Job when it releases its second 1935 // prioritized dispatcher slot. 1936 CreateResolverWithLimitsAndParams( 1937 PrioritizedDispatcher::Limits(NUM_PRIORITIES, 3u), 1938 DefaultParams(proc_.get())); 1939 1940 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 1941 ChangeDnsConfig(CreateValidDnsConfig()); 1942 1943 proc_->AddRuleForAllFamilies("slow_nx1", "192.168.0.1"); 1944 proc_->AddRuleForAllFamilies("slow_nx2", "192.168.0.2"); 1945 proc_->AddRuleForAllFamilies("ok", "192.168.0.3"); 1946 1947 // First active job gets two slots. 1948 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_nx1")->Resolve()); 1949 // Next job gets one slot, and waits on another. 1950 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_nx2")->Resolve()); 1951 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok")->Resolve()); 1952 1953 EXPECT_EQ(3u, num_running_dispatcher_jobs()); 1954 1955 // Clear DNS config. Two in-progress jobs should be aborted, and the next one 1956 // should use a ProcTask. 1957 ChangeDnsConfig(DnsConfig()); 1958 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[0]->WaitForResult()); 1959 EXPECT_EQ(ERR_NETWORK_CHANGED, requests_[1]->WaitForResult()); 1960 1961 // Finish up the third job. Should bypass the DnsClient, and get its results 1962 // from MockHostResolverProc. 1963 EXPECT_FALSE(requests_[2]->completed()); 1964 proc_->SignalMultiple(1u); 1965 EXPECT_EQ(OK, requests_[2]->WaitForResult()); 1966 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80)); 1967 } 1968 1969 // Tests the case that DnsClient is automatically disabled due to failures 1970 // while there are active DnsTasks. 1971 TEST_F(HostResolverImplDnsTest, 1972 AutomaticallyDisableDnsClientWithPendingRequests) { 1973 // Trying different limits is important for this test: Different limits 1974 // result in different behavior when aborting in-progress DnsTasks. Having 1975 // a DnsTask that has one job active and one in the queue when another job 1976 // occupying two slots has its DnsTask aborted is the case most likely to run 1977 // into problems. 1978 for (size_t limit = 1u; limit < 6u; ++limit) { 1979 CreateResolverWithLimitsAndParams( 1980 PrioritizedDispatcher::Limits(NUM_PRIORITIES, limit), 1981 DefaultParams(proc_.get())); 1982 1983 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 1984 ChangeDnsConfig(CreateValidDnsConfig()); 1985 1986 // Queue up enough failures to disable DnsTasks. These will all fall back 1987 // to ProcTasks, and succeed there. 1988 for (unsigned i = 0u; i < maximum_dns_failures(); ++i) { 1989 std::string host = base::StringPrintf("nx%u", i); 1990 proc_->AddRuleForAllFamilies(host, "192.168.0.1"); 1991 EXPECT_EQ(ERR_IO_PENDING, CreateRequest(host)->Resolve()); 1992 } 1993 1994 // These requests should all bypass DnsTasks, due to the above failures, 1995 // so should end up using ProcTasks. 1996 proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.2"); 1997 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok1")->Resolve()); 1998 proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.3"); 1999 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok2")->Resolve()); 2000 proc_->AddRuleForAllFamilies("slow_ok3", "192.168.0.4"); 2001 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok3")->Resolve()); 2002 proc_->SignalMultiple(maximum_dns_failures() + 3); 2003 2004 for (size_t i = 0u; i < maximum_dns_failures(); ++i) { 2005 EXPECT_EQ(OK, requests_[i]->WaitForResult()); 2006 EXPECT_TRUE(requests_[i]->HasOneAddress("192.168.0.1", 80)); 2007 } 2008 2009 EXPECT_EQ(OK, requests_[maximum_dns_failures()]->WaitForResult()); 2010 EXPECT_TRUE(requests_[maximum_dns_failures()]->HasOneAddress( 2011 "192.168.0.2", 80)); 2012 EXPECT_EQ(OK, requests_[maximum_dns_failures() + 1]->WaitForResult()); 2013 EXPECT_TRUE(requests_[maximum_dns_failures() + 1]->HasOneAddress( 2014 "192.168.0.3", 80)); 2015 EXPECT_EQ(OK, requests_[maximum_dns_failures() + 2]->WaitForResult()); 2016 EXPECT_TRUE(requests_[maximum_dns_failures() + 2]->HasOneAddress( 2017 "192.168.0.4", 80)); 2018 requests_.clear(); 2019 } 2020 } 2021 2022 // Tests a call to SetDnsClient while there are active DnsTasks. 2023 TEST_F(HostResolverImplDnsTest, ManuallyDisableDnsClientWithPendingRequests) { 2024 // At most 3 jobs active at once. This number is important, since we want to 2025 // make sure that aborting the first HostResolverImpl::Job does not trigger 2026 // another DnsTransaction on the second Job when it releases its second 2027 // prioritized dispatcher slot. 2028 CreateResolverWithLimitsAndParams( 2029 PrioritizedDispatcher::Limits(NUM_PRIORITIES, 3u), 2030 DefaultParams(proc_.get())); 2031 2032 resolver_->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED); 2033 ChangeDnsConfig(CreateValidDnsConfig()); 2034 2035 proc_->AddRuleForAllFamilies("slow_ok1", "192.168.0.1"); 2036 proc_->AddRuleForAllFamilies("slow_ok2", "192.168.0.2"); 2037 proc_->AddRuleForAllFamilies("ok", "192.168.0.3"); 2038 2039 // First active job gets two slots. 2040 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok1")->Resolve()); 2041 // Next job gets one slot, and waits on another. 2042 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("slow_ok2")->Resolve()); 2043 // Next one is queued. 2044 EXPECT_EQ(ERR_IO_PENDING, CreateRequest("ok")->Resolve()); 2045 2046 EXPECT_EQ(3u, num_running_dispatcher_jobs()); 2047 2048 // Clear DnsClient. The two in-progress jobs should fall back to a ProcTask, 2049 // and the next one should be started with a ProcTask. 2050 resolver_->SetDnsClient(scoped_ptr<DnsClient>()); 2051 2052 // All three in-progress requests should now be running a ProcTask. 2053 EXPECT_EQ(3u, num_running_dispatcher_jobs()); 2054 proc_->SignalMultiple(3u); 2055 2056 EXPECT_EQ(OK, requests_[0]->WaitForResult()); 2057 EXPECT_TRUE(requests_[0]->HasOneAddress("192.168.0.1", 80)); 2058 EXPECT_EQ(OK, requests_[1]->WaitForResult()); 2059 EXPECT_TRUE(requests_[1]->HasOneAddress("192.168.0.2", 80)); 2060 EXPECT_EQ(OK, requests_[2]->WaitForResult()); 2061 EXPECT_TRUE(requests_[2]->HasOneAddress("192.168.0.3", 80)); 2062 } 2063 2064 } // namespace net 2065