PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/qtwebengine/src/3rdparty/chromium/net/dns/mock_host_resolver.h

https://bitbucket.org/lotiuss/qt-5.11.0
C Header | 332 lines | 180 code | 57 blank | 95 comment | 0 complexity | 0128bd6416fb9559f4400cb32ea561f2 MD5 | raw file
Possible License(s): GPL-3.0, MPL-2.0, CC-BY-SA-3.0, LGPL-2.0, Unlicense, BSD-3-Clause, Apache-2.0, LGPL-3.0, MIT, WTFPL, GPL-2.0, MPL-2.0-no-copyleft-exception, AGPL-3.0, LGPL-2.1, BSD-2-Clause, 0BSD, JSON, ISC
  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. #ifndef NET_DNS_MOCK_HOST_RESOLVER_H_
  5. #define NET_DNS_MOCK_HOST_RESOLVER_H_
  6. #include <stddef.h>
  7. #include <list>
  8. #include <map>
  9. #include <string>
  10. #include "base/macros.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/thread_checker.h"
  15. #include "net/dns/host_resolver.h"
  16. #include "net/dns/host_resolver_proc.h"
  17. namespace net {
  18. class HostCache;
  19. class RuleBasedHostResolverProc;
  20. // Fills |*addrlist| with a socket address for |host_list| which should be a
  21. // comma-separated list of IPv4 or IPv6 literal(s) without enclosing brackets.
  22. // If |canonical_name| is non-empty it is used as the DNS canonical name for
  23. // the host. Returns OK on success, ERR_UNEXPECTED otherwise.
  24. int ParseAddressList(const std::string& host_list,
  25. const std::string& canonical_name,
  26. AddressList* addrlist);
  27. // In most cases, it is important that unit tests avoid relying on making actual
  28. // DNS queries since the resulting tests can be flaky, especially if the network
  29. // is unreliable for some reason. To simplify writing tests that avoid making
  30. // actual DNS queries, pass a MockHostResolver as the HostResolver dependency.
  31. // The socket addresses returned can be configured using the
  32. // RuleBasedHostResolverProc:
  33. //
  34. // host_resolver->rules()->AddRule("foo.com", "1.2.3.4");
  35. // host_resolver->rules()->AddRule("bar.com", "2.3.4.5");
  36. //
  37. // The above rules define a static mapping from hostnames to IP address
  38. // literals. The first parameter to AddRule specifies a host pattern to match
  39. // against, and the second parameter indicates what value should be used to
  40. // replace the given hostname. So, the following is also supported:
  41. //
  42. // host_mapper->AddRule("*.com", "127.0.0.1");
  43. //
  44. // Replacement doesn't have to be string representing an IP address. It can
  45. // re-map one hostname to another as well.
  46. //
  47. // By default, MockHostResolvers include a single rule that maps all hosts to
  48. // 127.0.0.1.
  49. // Base class shared by MockHostResolver and MockCachingHostResolver.
  50. class MockHostResolverBase
  51. : public HostResolver,
  52. public base::SupportsWeakPtr<MockHostResolverBase> {
  53. private:
  54. class RequestImpl;
  55. public:
  56. ~MockHostResolverBase() override;
  57. RuleBasedHostResolverProc* rules() { return rules_.get(); }
  58. void set_rules(RuleBasedHostResolverProc* rules) { rules_ = rules; }
  59. // Controls whether resolutions complete synchronously or asynchronously.
  60. void set_synchronous_mode(bool is_synchronous) {
  61. synchronous_mode_ = is_synchronous;
  62. }
  63. // Asynchronous requests are automatically resolved by default.
  64. // If set_ondemand_mode() is set then Resolve() returns IO_PENDING and
  65. // ResolveAllPending() must be explicitly invoked to resolve all requests
  66. // that are pending.
  67. void set_ondemand_mode(bool is_ondemand) {
  68. ondemand_mode_ = is_ondemand;
  69. }
  70. // HostResolver methods:
  71. int Resolve(const RequestInfo& info,
  72. RequestPriority priority,
  73. AddressList* addresses,
  74. const CompletionCallback& callback,
  75. std::unique_ptr<Request>* request,
  76. const NetLogWithSource& net_log) override;
  77. int ResolveFromCache(const RequestInfo& info,
  78. AddressList* addresses,
  79. const NetLogWithSource& net_log) override;
  80. int ResolveStaleFromCache(const RequestInfo& info,
  81. AddressList* addresses,
  82. HostCache::EntryStaleness* stale_info,
  83. const NetLogWithSource& source_net_log) override;
  84. HostCache* GetHostCache() override;
  85. bool HasCached(base::StringPiece hostname,
  86. HostCache::Entry::Source* source_out,
  87. HostCache::EntryStaleness* stale_out) const override;
  88. // Detach cancelled request.
  89. void DetachRequest(size_t id);
  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();
  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. // The number of times that Resolve() has been called.
  98. size_t num_resolve() const {
  99. return num_resolve_;
  100. }
  101. // The number of times that ResolveFromCache() has been called.
  102. size_t num_resolve_from_cache() const {
  103. return num_resolve_from_cache_;
  104. }
  105. // Returns the RequestPriority of the last call to Resolve() (or
  106. // DEFAULT_PRIORITY if Resolve() hasn't been called yet).
  107. RequestPriority last_request_priority() const {
  108. return last_request_priority_;
  109. }
  110. protected:
  111. explicit MockHostResolverBase(bool use_caching);
  112. private:
  113. typedef std::map<size_t, RequestImpl*> RequestMap;
  114. // Resolve as IP or from |cache_| return cached error or
  115. // DNS_CACHE_MISS if failed.
  116. int ResolveFromIPLiteralOrCache(
  117. const RequestInfo& info,
  118. AddressList* addresses,
  119. HostCache::EntryStaleness* stale_info = nullptr);
  120. // Resolve via |proc_|.
  121. int ResolveProc(const RequestInfo& info, AddressList* addresses);
  122. // Resolve request stored in |requests_|. Pass rv to callback.
  123. void ResolveNow(size_t id);
  124. RequestPriority last_request_priority_;
  125. bool synchronous_mode_;
  126. bool ondemand_mode_;
  127. scoped_refptr<RuleBasedHostResolverProc> rules_;
  128. std::unique_ptr<HostCache> cache_;
  129. RequestMap requests_;
  130. size_t next_request_id_;
  131. size_t num_resolve_;
  132. size_t num_resolve_from_cache_;
  133. THREAD_CHECKER(thread_checker_);
  134. DISALLOW_COPY_AND_ASSIGN(MockHostResolverBase);
  135. };
  136. class MockHostResolver : public MockHostResolverBase {
  137. public:
  138. MockHostResolver() : MockHostResolverBase(false /*use_caching*/) {}
  139. ~MockHostResolver() override {}
  140. };
  141. // Same as MockHostResolver, except internally it uses a host-cache.
  142. //
  143. // Note that tests are advised to use MockHostResolver instead, since it is
  144. // more predictable. (MockHostResolver also can be put into synchronous
  145. // operation mode in case that is what you needed from the caching version).
  146. class MockCachingHostResolver : public MockHostResolverBase {
  147. public:
  148. MockCachingHostResolver() : MockHostResolverBase(true /*use_caching*/) {}
  149. ~MockCachingHostResolver() override {}
  150. };
  151. // RuleBasedHostResolverProc applies a set of rules to map a host string to
  152. // a replacement host string. It then uses the system host resolver to return
  153. // a socket address. Generally the replacement should be an IPv4 literal so
  154. // there is no network dependency.
  155. //
  156. // RuleBasedHostResolverProc is thread-safe, to a limited degree. Rules can be
  157. // added or removed on any thread.
  158. class RuleBasedHostResolverProc : public HostResolverProc {
  159. public:
  160. explicit RuleBasedHostResolverProc(HostResolverProc* previous);
  161. // Any hostname matching the given pattern will be replaced with the given
  162. // |ip_literal|.
  163. void AddRule(const std::string& host_pattern, const std::string& ip_literal);
  164. // Same as AddRule(), but further restricts to |address_family|.
  165. void AddRuleForAddressFamily(const std::string& host_pattern,
  166. AddressFamily address_family,
  167. const std::string& ip_literal);
  168. // Same as AddRule(), but the replacement is expected to be an IPv4 or IPv6
  169. // literal. This can be used in place of AddRule() to bypass the system's
  170. // host resolver (the address list will be constructed manually).
  171. // If |canonical_name| is non-empty, it is copied to the resulting AddressList
  172. // but does not impact DNS resolution.
  173. // |ip_literal| can be a single IP address like "192.168.1.1" or a comma
  174. // separated list of IP addresses, like "::1,192:168.1.2".
  175. void AddIPLiteralRule(const std::string& host_pattern,
  176. const std::string& ip_literal,
  177. const std::string& canonical_name);
  178. void AddRuleWithLatency(const std::string& host_pattern,
  179. const std::string& replacement,
  180. int latency_ms);
  181. // Make sure that |host| will not be re-mapped or even processed by underlying
  182. // host resolver procedures. It can also be a pattern.
  183. void AllowDirectLookup(const std::string& host);
  184. // Simulate a lookup failure for |host| (it also can be a pattern).
  185. void AddSimulatedFailure(const std::string& host);
  186. // Deletes all the rules that have been added.
  187. void ClearRules();
  188. // Causes method calls that add or delete rules to assert.
  189. // TODO(jam): once this class isn't used by tests that use an out of process
  190. // network service, remove this method and make Rule private.
  191. void DisableModifications();
  192. // HostResolverProc methods:
  193. int Resolve(const std::string& host,
  194. AddressFamily address_family,
  195. HostResolverFlags host_resolver_flags,
  196. AddressList* addrlist,
  197. int* os_error) override;
  198. struct Rule {
  199. enum ResolverType {
  200. kResolverTypeFail,
  201. // TODO(mmenke): Is it really reasonable for a "mock" host resolver to
  202. // fall back to the system resolver?
  203. kResolverTypeSystem,
  204. kResolverTypeIPLiteral,
  205. };
  206. Rule(ResolverType resolver_type,
  207. const std::string& host_pattern,
  208. AddressFamily address_family,
  209. HostResolverFlags host_resolver_flags,
  210. const std::string& replacement,
  211. const std::string& canonical_name,
  212. int latency_ms);
  213. Rule(const Rule& other);
  214. ResolverType resolver_type;
  215. std::string host_pattern;
  216. AddressFamily address_family;
  217. HostResolverFlags host_resolver_flags;
  218. std::string replacement;
  219. std::string canonical_name;
  220. int latency_ms; // In milliseconds.
  221. };
  222. typedef std::list<Rule> RuleList;
  223. RuleList GetRules();
  224. private:
  225. ~RuleBasedHostResolverProc() override;
  226. void AddRuleInternal(const Rule& rule);
  227. RuleList rules_;
  228. // Must be obtained before writing to or reading from |rules_|.
  229. base::Lock rule_lock_;
  230. // Whether changes are allowed.
  231. bool modifications_allowed_;
  232. };
  233. // Create rules that map all requests to localhost.
  234. RuleBasedHostResolverProc* CreateCatchAllHostResolverProc();
  235. // HangingHostResolver never completes its |Resolve| request.
  236. class HangingHostResolver : public HostResolver {
  237. public:
  238. int Resolve(const RequestInfo& info,
  239. RequestPriority priority,
  240. AddressList* addresses,
  241. const CompletionCallback& callback,
  242. std::unique_ptr<Request>* out_req,
  243. const NetLogWithSource& net_log) override;
  244. int ResolveFromCache(const RequestInfo& info,
  245. AddressList* addresses,
  246. const NetLogWithSource& net_log) override;
  247. int ResolveStaleFromCache(const RequestInfo& info,
  248. AddressList* addresses,
  249. HostCache::EntryStaleness* stale_info,
  250. const NetLogWithSource& source_net_log) override;
  251. bool HasCached(base::StringPiece hostname,
  252. HostCache::Entry::Source* source_out,
  253. HostCache::EntryStaleness* stale_out) const override;
  254. };
  255. // This class sets the default HostResolverProc for a particular scope. The
  256. // chain of resolver procs starting at |proc| is placed in front of any existing
  257. // default resolver proc(s). This means that if multiple
  258. // ScopedDefaultHostResolverProcs are declared, then resolving will start with
  259. // the procs given to the last-allocated one, then fall back to the procs given
  260. // to the previously-allocated one, and so forth.
  261. //
  262. // NOTE: Only use this as a catch-all safety net. Individual tests should use
  263. // MockHostResolver.
  264. class ScopedDefaultHostResolverProc {
  265. public:
  266. ScopedDefaultHostResolverProc();
  267. explicit ScopedDefaultHostResolverProc(HostResolverProc* proc);
  268. ~ScopedDefaultHostResolverProc();
  269. void Init(HostResolverProc* proc);
  270. private:
  271. scoped_refptr<HostResolverProc> current_proc_;
  272. scoped_refptr<HostResolverProc> previous_proc_;
  273. };
  274. } // namespace net
  275. #endif // NET_DNS_MOCK_HOST_RESOLVER_H_