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
17namespace net {
18
19class HostCache;
20class 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.
26int 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.
54class 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                      RequestPriority priority,
79                      AddressList* addresses,
80                      const CompletionCallback& callback,
81                      RequestHandle* out_req,
82                      const BoundNetLog& net_log) OVERRIDE;
83  virtual int ResolveFromCache(const RequestInfo& info,
84                               AddressList* addresses,
85                               const BoundNetLog& net_log) OVERRIDE;
86  virtual void CancelRequest(RequestHandle req) OVERRIDE;
87  virtual HostCache* GetHostCache() OVERRIDE;
88
89  // Resolves all pending requests. It is only valid to invoke this if
90  // set_ondemand_mode was set before. The requests are resolved asynchronously,
91  // after this call returns.
92  void ResolveAllPending();
93
94  // Returns true if there are pending requests that can be resolved by invoking
95  // ResolveAllPending().
96  bool has_pending_requests() const { return !requests_.empty(); }
97
98  // The number of times that Resolve() has been called.
99  size_t num_resolve() const {
100    return num_resolve_;
101  }
102
103  // The number of times that ResolveFromCache() has been called.
104  size_t num_resolve_from_cache() const {
105    return num_resolve_from_cache_;
106  }
107
108  // Returns the RequestPriority of the last call to Resolve() (or
109  // DEFAULT_PRIORITY if Resolve() hasn't been called yet).
110  RequestPriority last_request_priority() const {
111    return last_request_priority_;
112  }
113
114 protected:
115  explicit MockHostResolverBase(bool use_caching);
116
117 private:
118  struct Request;
119  typedef std::map<size_t, Request*> RequestMap;
120
121  // Resolve as IP or from |cache_| return cached error or
122  // DNS_CACHE_MISS if failed.
123  int ResolveFromIPLiteralOrCache(const RequestInfo& info,
124                                  AddressList* addresses);
125  // Resolve via |proc_|.
126  int ResolveProc(size_t id, const RequestInfo& info, AddressList* addresses);
127  // Resolve request stored in |requests_|. Pass rv to callback.
128  void ResolveNow(size_t id);
129
130  RequestPriority last_request_priority_;
131  bool synchronous_mode_;
132  bool ondemand_mode_;
133  scoped_refptr<RuleBasedHostResolverProc> rules_;
134  scoped_ptr<HostCache> cache_;
135  RequestMap requests_;
136  size_t next_request_id_;
137
138  size_t num_resolve_;
139  size_t num_resolve_from_cache_;
140
141  DISALLOW_COPY_AND_ASSIGN(MockHostResolverBase);
142};
143
144class MockHostResolver : public MockHostResolverBase {
145 public:
146  MockHostResolver() : MockHostResolverBase(false /*use_caching*/) {}
147  virtual ~MockHostResolver() {}
148};
149
150// Same as MockHostResolver, except internally it uses a host-cache.
151//
152// Note that tests are advised to use MockHostResolver instead, since it is
153// more predictable. (MockHostResolver also can be put into synchronous
154// operation mode in case that is what you needed from the caching version).
155class MockCachingHostResolver : public MockHostResolverBase {
156 public:
157  MockCachingHostResolver() : MockHostResolverBase(true /*use_caching*/) {}
158  virtual ~MockCachingHostResolver() {}
159};
160
161// RuleBasedHostResolverProc applies a set of rules to map a host string to
162// a replacement host string. It then uses the system host resolver to return
163// a socket address. Generally the replacement should be an IPv4 literal so
164// there is no network dependency.
165class RuleBasedHostResolverProc : public HostResolverProc {
166 public:
167  explicit RuleBasedHostResolverProc(HostResolverProc* previous);
168
169  // Any hostname matching the given pattern will be replaced with the given
170  // replacement value.  Usually, replacement should be an IP address literal.
171  void AddRule(const std::string& host_pattern,
172               const std::string& replacement);
173
174  // Same as AddRule(), but further restricts to |address_family|.
175  void AddRuleForAddressFamily(const std::string& host_pattern,
176                               AddressFamily address_family,
177                               const std::string& replacement);
178
179  // Same as AddRule(), but the replacement is expected to be an IPv4 or IPv6
180  // literal. This can be used in place of AddRule() to bypass the system's
181  // host resolver (the address list will be constructed manually).
182  // If |canonical_name| is non-empty, it is copied to the resulting AddressList
183  // but does not impact DNS resolution.
184  // |ip_literal| can be a single IP address like "192.168.1.1" or a comma
185  // separated list of IP addresses, like "::1,192:168.1.2".
186  void AddIPLiteralRule(const std::string& host_pattern,
187                        const std::string& ip_literal,
188                        const std::string& canonical_name);
189
190  void AddRuleWithLatency(const std::string& host_pattern,
191                          const std::string& replacement,
192                          int latency_ms);
193
194  // Make sure that |host| will not be re-mapped or even processed by underlying
195  // host resolver procedures. It can also be a pattern.
196  void AllowDirectLookup(const std::string& host);
197
198  // Simulate a lookup failure for |host| (it also can be a pattern).
199  void AddSimulatedFailure(const std::string& host);
200
201  // Deletes all the rules that have been added.
202  void ClearRules();
203
204  // HostResolverProc methods:
205  virtual int Resolve(const std::string& host,
206                      AddressFamily address_family,
207                      HostResolverFlags host_resolver_flags,
208                      AddressList* addrlist,
209                      int* os_error) OVERRIDE;
210
211 private:
212  struct Rule;
213  typedef std::list<Rule> RuleList;
214
215  virtual ~RuleBasedHostResolverProc();
216
217  RuleList rules_;
218};
219
220// Create rules that map all requests to localhost.
221RuleBasedHostResolverProc* CreateCatchAllHostResolverProc();
222
223// HangingHostResolver never completes its |Resolve| request.
224class HangingHostResolver : public HostResolver {
225 public:
226  virtual int Resolve(const RequestInfo& info,
227                      RequestPriority priority,
228                      AddressList* addresses,
229                      const CompletionCallback& callback,
230                      RequestHandle* out_req,
231                      const BoundNetLog& net_log) OVERRIDE;
232  virtual int ResolveFromCache(const RequestInfo& info,
233                               AddressList* addresses,
234                               const BoundNetLog& net_log) OVERRIDE;
235  virtual void CancelRequest(RequestHandle req) OVERRIDE {}
236};
237
238// This class sets the default HostResolverProc for a particular scope.  The
239// chain of resolver procs starting at |proc| is placed in front of any existing
240// default resolver proc(s).  This means that if multiple
241// ScopedDefaultHostResolverProcs are declared, then resolving will start with
242// the procs given to the last-allocated one, then fall back to the procs given
243// to the previously-allocated one, and so forth.
244//
245// NOTE: Only use this as a catch-all safety net. Individual tests should use
246// MockHostResolver.
247class ScopedDefaultHostResolverProc {
248 public:
249  ScopedDefaultHostResolverProc();
250  explicit ScopedDefaultHostResolverProc(HostResolverProc* proc);
251
252  ~ScopedDefaultHostResolverProc();
253
254  void Init(HostResolverProc* proc);
255
256 private:
257  scoped_refptr<HostResolverProc> current_proc_;
258  scoped_refptr<HostResolverProc> previous_proc_;
259};
260
261}  // namespace net
262
263#endif  // NET_DNS_MOCK_HOST_RESOLVER_H_
264