Home | History | Annotate | Download | only in dns
      1 // Copyright (c) 2011 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 #ifndef NET_DNS_MOCK_HOST_RESOLVER_H_
      6 #define NET_DNS_MOCK_HOST_RESOLVER_H_
      7 
      8 #include <list>
      9 #include <map>
     10 
     11 #include "base/memory/weak_ptr.h"
     12 #include "base/synchronization/waitable_event.h"
     13 #include "base/threading/non_thread_safe.h"
     14 #include "net/dns/host_resolver.h"
     15 #include "net/dns/host_resolver_proc.h"
     16 
     17 namespace net {
     18 
     19 class HostCache;
     20 class RuleBasedHostResolverProc;
     21 
     22 // Fills |*addrlist| with a socket address for |host_list| which should be a
     23 // comma-separated list of IPv4 or IPv6 literal(s) without enclosing brackets.
     24 // If |canonical_name| is non-empty it is used as the DNS canonical name for
     25 // the host. Returns OK on success, ERR_UNEXPECTED otherwise.
     26 int ParseAddressList(const std::string& host_list,
     27                      const std::string& canonical_name,
     28                      AddressList* addrlist);
     29 
     30 // In most cases, it is important that unit tests avoid relying on making actual
     31 // DNS queries since the resulting tests can be flaky, especially if the network
     32 // is unreliable for some reason.  To simplify writing tests that avoid making
     33 // actual DNS queries, pass a MockHostResolver as the HostResolver dependency.
     34 // The socket addresses returned can be configured using the
     35 // RuleBasedHostResolverProc:
     36 //
     37 //   host_resolver->rules()->AddRule("foo.com", "1.2.3.4");
     38 //   host_resolver->rules()->AddRule("bar.com", "2.3.4.5");
     39 //
     40 // The above rules define a static mapping from hostnames to IP address
     41 // literals.  The first parameter to AddRule specifies a host pattern to match
     42 // against, and the second parameter indicates what value should be used to
     43 // replace the given hostname.  So, the following is also supported:
     44 //
     45 //   host_mapper->AddRule("*.com", "127.0.0.1");
     46 //
     47 // Replacement doesn't have to be string representing an IP address. It can
     48 // re-map one hostname to another as well.
     49 //
     50 // By default, MockHostResolvers include a single rule that maps all hosts to
     51 // 127.0.0.1.
     52 
     53 // Base class shared by MockHostResolver and MockCachingHostResolver.
     54 class MockHostResolverBase : public HostResolver,
     55                              public base::SupportsWeakPtr<MockHostResolverBase>,
     56                              public base::NonThreadSafe {
     57  public:
     58   virtual ~MockHostResolverBase();
     59 
     60   RuleBasedHostResolverProc* rules() { return rules_.get(); }
     61   void set_rules(RuleBasedHostResolverProc* rules) { rules_ = rules; }
     62 
     63   // Controls whether resolutions complete synchronously or asynchronously.
     64   void set_synchronous_mode(bool is_synchronous) {
     65     synchronous_mode_ = is_synchronous;
     66   }
     67 
     68   // Asynchronous requests are automatically resolved by default.
     69   // If set_ondemand_mode() is set then Resolve() returns IO_PENDING and
     70   // ResolveAllPending() must be explicitly invoked to resolve all requests
     71   // that are pending.
     72   void set_ondemand_mode(bool is_ondemand) {
     73     ondemand_mode_ = is_ondemand;
     74   }
     75 
     76   // HostResolver methods:
     77   virtual int Resolve(const RequestInfo& info,
     78                       AddressList* addresses,
     79                       const CompletionCallback& callback,
     80                       RequestHandle* out_req,
     81                       const BoundNetLog& net_log) OVERRIDE;
     82   virtual int ResolveFromCache(const RequestInfo& info,
     83                                AddressList* addresses,
     84                                const BoundNetLog& net_log) OVERRIDE;
     85   virtual void CancelRequest(RequestHandle req) OVERRIDE;
     86   virtual HostCache* GetHostCache() OVERRIDE;
     87 
     88   // Resolves all pending requests. It is only valid to invoke this if
     89   // set_ondemand_mode was set before. The requests are resolved asynchronously,
     90   // after this call returns.
     91   void ResolveAllPending();
     92 
     93   // Returns true if there are pending requests that can be resolved by invoking
     94   // ResolveAllPending().
     95   bool has_pending_requests() const { return !requests_.empty(); }
     96 
     97   // The number of times that Resolve() has been called.
     98   size_t num_resolve() const {
     99     return num_resolve_;
    100   }
    101 
    102   // The number of times that ResolveFromCache() has been called.
    103   size_t num_resolve_from_cache() const {
    104     return num_resolve_from_cache_;
    105   }
    106 
    107  protected:
    108   explicit MockHostResolverBase(bool use_caching);
    109 
    110  private:
    111   struct Request;
    112   typedef std::map<size_t, Request*> RequestMap;
    113 
    114   // Resolve as IP or from |cache_| return cached error or
    115   // DNS_CACHE_MISS if failed.
    116   int ResolveFromIPLiteralOrCache(const RequestInfo& info,
    117                                   AddressList* addresses);
    118   // Resolve via |proc_|.
    119   int ResolveProc(size_t id, const RequestInfo& info, AddressList* addresses);
    120   // Resolve request stored in |requests_|. Pass rv to callback.
    121   void ResolveNow(size_t id);
    122 
    123   bool synchronous_mode_;
    124   bool ondemand_mode_;
    125   scoped_refptr<RuleBasedHostResolverProc> rules_;
    126   scoped_ptr<HostCache> cache_;
    127   RequestMap requests_;
    128   size_t next_request_id_;
    129 
    130   size_t num_resolve_;
    131   size_t num_resolve_from_cache_;
    132 
    133   DISALLOW_COPY_AND_ASSIGN(MockHostResolverBase);
    134 };
    135 
    136 class MockHostResolver : public MockHostResolverBase {
    137  public:
    138   MockHostResolver() : MockHostResolverBase(false /*use_caching*/) {}
    139   virtual ~MockHostResolver() {}
    140 };
    141 
    142 // Same as MockHostResolver, except internally it uses a host-cache.
    143 //
    144 // Note that tests are advised to use MockHostResolver instead, since it is
    145 // more predictable. (MockHostResolver also can be put into synchronous
    146 // operation mode in case that is what you needed from the caching version).
    147 class MockCachingHostResolver : public MockHostResolverBase {
    148  public:
    149   MockCachingHostResolver() : MockHostResolverBase(true /*use_caching*/) {}
    150   virtual ~MockCachingHostResolver() {}
    151 };
    152 
    153 // RuleBasedHostResolverProc applies a set of rules to map a host string to
    154 // a replacement host string. It then uses the system host resolver to return
    155 // a socket address. Generally the replacement should be an IPv4 literal so
    156 // there is no network dependency.
    157 class RuleBasedHostResolverProc : public HostResolverProc {
    158  public:
    159   explicit RuleBasedHostResolverProc(HostResolverProc* previous);
    160 
    161   // Any hostname matching the given pattern will be replaced with the given
    162   // replacement value.  Usually, replacement should be an IP address literal.
    163   void AddRule(const std::string& host_pattern,
    164                const std::string& replacement);
    165 
    166   // Same as AddRule(), but further restricts to |address_family|.
    167   void AddRuleForAddressFamily(const std::string& host_pattern,
    168                                AddressFamily address_family,
    169                                const std::string& replacement);
    170 
    171   // Same as AddRule(), but the replacement is expected to be an IPv4 or IPv6
    172   // literal. This can be used in place of AddRule() to bypass the system's
    173   // host resolver (the address list will be constructed manually).
    174   // If |canonical_name| is non-empty, it is copied to the resulting AddressList
    175   // but does not impact DNS resolution.
    176   // |ip_literal| can be a single IP address like "192.168.1.1" or a comma
    177   // separated list of IP addresses, like "::1,192:168.1.2".
    178   void AddIPLiteralRule(const std::string& host_pattern,
    179                         const std::string& ip_literal,
    180                         const std::string& canonical_name);
    181 
    182   void AddRuleWithLatency(const std::string& host_pattern,
    183                           const std::string& replacement,
    184                           int latency_ms);
    185 
    186   // Make sure that |host| will not be re-mapped or even processed by underlying
    187   // host resolver procedures. It can also be a pattern.
    188   void AllowDirectLookup(const std::string& host);
    189 
    190   // Simulate a lookup failure for |host| (it also can be a pattern).
    191   void AddSimulatedFailure(const std::string& host);
    192 
    193   // Deletes all the rules that have been added.
    194   void ClearRules();
    195 
    196   // HostResolverProc methods:
    197   virtual int Resolve(const std::string& host,
    198                       AddressFamily address_family,
    199                       HostResolverFlags host_resolver_flags,
    200                       AddressList* addrlist,
    201                       int* os_error) OVERRIDE;
    202 
    203  private:
    204   struct Rule;
    205   typedef std::list<Rule> RuleList;
    206 
    207   virtual ~RuleBasedHostResolverProc();
    208 
    209   RuleList rules_;
    210 };
    211 
    212 // Create rules that map all requests to localhost.
    213 RuleBasedHostResolverProc* CreateCatchAllHostResolverProc();
    214 
    215 // HangingHostResolver never completes its |Resolve| request.
    216 class HangingHostResolver : public HostResolver {
    217  public:
    218   virtual int Resolve(const RequestInfo& info,
    219                       AddressList* addresses,
    220                       const CompletionCallback& callback,
    221                       RequestHandle* out_req,
    222                       const BoundNetLog& net_log) OVERRIDE;
    223   virtual int ResolveFromCache(const RequestInfo& info,
    224                                AddressList* addresses,
    225                                const BoundNetLog& net_log) OVERRIDE;
    226   virtual void CancelRequest(RequestHandle req) OVERRIDE {}
    227 };
    228 
    229 // This class sets the default HostResolverProc for a particular scope.  The
    230 // chain of resolver procs starting at |proc| is placed in front of any existing
    231 // default resolver proc(s).  This means that if multiple
    232 // ScopedDefaultHostResolverProcs are declared, then resolving will start with
    233 // the procs given to the last-allocated one, then fall back to the procs given
    234 // to the previously-allocated one, and so forth.
    235 //
    236 // NOTE: Only use this as a catch-all safety net. Individual tests should use
    237 // MockHostResolver.
    238 class ScopedDefaultHostResolverProc {
    239  public:
    240   ScopedDefaultHostResolverProc();
    241   explicit ScopedDefaultHostResolverProc(HostResolverProc* proc);
    242 
    243   ~ScopedDefaultHostResolverProc();
    244 
    245   void Init(HostResolverProc* proc);
    246 
    247  private:
    248   scoped_refptr<HostResolverProc> current_proc_;
    249   scoped_refptr<HostResolverProc> previous_proc_;
    250 };
    251 
    252 }  // namespace net
    253 
    254 #endif  // NET_DNS_MOCK_HOST_RESOLVER_H_
    255