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