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