host_resolver.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. #ifndef NET_DNS_HOST_RESOLVER_H_
  5. #define NET_DNS_HOST_RESOLVER_H_
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <memory>
  9. #include <set>
  10. #include <string>
  11. #include <vector>
  12. #include "base/strings/string_piece.h"
  13. #include "net/base/address_family.h"
  14. #include "net/base/completion_once_callback.h"
  15. #include "net/base/host_port_pair.h"
  16. #include "net/base/network_handle.h"
  17. #include "net/base/network_isolation_key.h"
  18. #include "net/base/request_priority.h"
  19. #include "net/dns/host_cache.h"
  20. #include "net/dns/host_resolver_results.h"
  21. #include "net/dns/public/dns_config_overrides.h"
  22. #include "net/dns/public/dns_query_type.h"
  23. #include "net/dns/public/host_resolver_source.h"
  24. #include "net/dns/public/mdns_listener_update_type.h"
  25. #include "net/dns/public/resolve_error_info.h"
  26. #include "net/dns/public/secure_dns_policy.h"
  27. #include "net/log/net_log_with_source.h"
  28. #include "third_party/abseil-cpp/absl/types/optional.h"
  29. #include "url/scheme_host_port.h"
  30. namespace base {
  31. class Value;
  32. }
  33. namespace net {
  34. class AddressList;
  35. class ContextHostResolver;
  36. class DnsClient;
  37. struct DnsConfigOverrides;
  38. class HostResolverManager;
  39. class NetLog;
  40. class URLRequestContext;
  41. // This class represents the task of resolving hostnames (or IP address
  42. // literal) to an AddressList object (or other DNS-style results).
  43. //
  44. // Typically implemented by ContextHostResolver or wrappers thereof. See
  45. // HostResolver::Create[...]() methods for construction or URLRequestContext for
  46. // retrieval.
  47. //
  48. // See mock_host_resolver.h for test implementations.
  49. class NET_EXPORT HostResolver {
  50. public:
  51. using Host = absl::variant<url::SchemeHostPort, HostPortPair>;
  52. // Handler for an individual host resolution request. Created by
  53. // HostResolver::CreateRequest().
  54. class ResolveHostRequest {
  55. public:
  56. // Destruction cancels the request if running asynchronously, causing the
  57. // callback to never be invoked.
  58. virtual ~ResolveHostRequest() = default;
  59. // Starts the request and returns a network error code.
  60. //
  61. // If the request could not be handled synchronously, returns
  62. // |ERR_IO_PENDING|, and completion will be signaled later via |callback|.
  63. // On any other returned value, the request was handled synchronously and
  64. // |callback| will not be invoked.
  65. //
  66. // Results in ERR_NAME_NOT_RESOLVED if the hostname is not resolved. More
  67. // detail about the underlying error can be retrieved using
  68. // GetResolveErrorInfo().
  69. //
  70. // The parent HostResolver must still be alive when Start() is called, but
  71. // if it is destroyed before an asynchronous result completes, the request
  72. // will be automatically cancelled.
  73. //
  74. // If cancelled before |callback| is invoked, it will never be invoked.
  75. virtual int Start(CompletionOnceCallback callback) = 0;
  76. // Address record (A or AAAA) results of the request. Should only be called
  77. // after Start() signals completion, either by invoking the callback or by
  78. // returning a result other than |ERR_IO_PENDING|.
  79. //
  80. // TODO(crbug.com/1264933): Remove and replace all usage with
  81. // GetEndpointResults().
  82. virtual const AddressList* GetAddressResults() const = 0;
  83. // Endpoint results for `A`, `AAAA`, `UNSPECIFIED`, or `HTTPS` requests.
  84. // Should only be called after Start() signals completion, either by
  85. // invoking the callback or by returning a result other than
  86. // `ERR_IO_PENDING`.
  87. virtual const std::vector<HostResolverEndpointResult>* GetEndpointResults()
  88. const = 0;
  89. // Text record (TXT) results of the request. Should only be called after
  90. // Start() signals completion, either by invoking the callback or by
  91. // returning a result other than |ERR_IO_PENDING|.
  92. virtual const absl::optional<std::vector<std::string>>& GetTextResults()
  93. const = 0;
  94. // Hostname record (SRV or PTR) results of the request. For SRV results,
  95. // hostnames are ordered acording to their priorities and weights. See RFC
  96. // 2782.
  97. //
  98. // Should only be called after Start() signals completion, either by
  99. // invoking the callback or by returning a result other than
  100. // |ERR_IO_PENDING|.
  101. virtual const absl::optional<std::vector<HostPortPair>>&
  102. GetHostnameResults() const = 0;
  103. // Any DNS record aliases, such as CNAME aliases, found as a result of an
  104. // address query. Includes all known aliases, e.g. from A, AAAA, or HTTPS,
  105. // not just from the address used for the connection, in no particular
  106. // order. Should only be called after Start() signals completion, either by
  107. // invoking the callback or by returning a result other than
  108. // `ERR_IO_PENDING`. Returns a list of aliases that has been fixed up and
  109. // canonicalized (as URL hostnames), and thus may differ from the results
  110. // stored directly in the AddressList.
  111. //
  112. // If `ResolveHostParameters::include_canonical_name` was true, alias
  113. // results will always be the single "canonical name" received from the
  114. // system resolver without URL hostname canonicalization (or an empty set or
  115. // `nullptr` in the unusual case that the system resolver did not give a
  116. // canonical name).
  117. virtual const std::set<std::string>* GetDnsAliasResults() const = 0;
  118. // Result of an experimental query. Meaning depends on the specific query
  119. // type, but each boolean value generally refers to a valid or invalid
  120. // record of the experimental type.
  121. NET_EXPORT virtual const std::vector<bool>*
  122. GetExperimentalResultsForTesting() const;
  123. // Error info for the request.
  124. //
  125. // Should only be called after Start() signals completion, either by
  126. // invoking the callback or by returning a result other than
  127. // |ERR_IO_PENDING|.
  128. virtual ResolveErrorInfo GetResolveErrorInfo() const = 0;
  129. // Information about the result's staleness in the host cache. Only
  130. // available if results were received from the host cache.
  131. //
  132. // Should only be called after Start() signals completion, either by
  133. // invoking the callback or by returning a result other than
  134. // |ERR_IO_PENDING|.
  135. virtual const absl::optional<HostCache::EntryStaleness>& GetStaleInfo()
  136. const = 0;
  137. // Changes the priority of the specified request. Can only be called while
  138. // the request is running (after Start() returns |ERR_IO_PENDING| and before
  139. // the callback is invoked).
  140. virtual void ChangeRequestPriority(RequestPriority priority) {}
  141. };
  142. // Handler for an activation of probes controlled by a HostResolver. Created
  143. // by HostResolver::CreateDohProbeRequest().
  144. class ProbeRequest {
  145. public:
  146. // Destruction cancels the request and all probes.
  147. virtual ~ProbeRequest() = default;
  148. // Activates async running of probes. Always returns ERR_IO_PENDING or an
  149. // error from activating probes. No callback as probes will never "complete"
  150. // until cancellation.
  151. virtual int Start() = 0;
  152. };
  153. // The options for features::kUseDnsHttpsSvcb experiment. See the comments
  154. // in net/base/features.h for more details.
  155. struct NET_EXPORT HttpsSvcbOptions {
  156. HttpsSvcbOptions();
  157. HttpsSvcbOptions(const HttpsSvcbOptions&);
  158. HttpsSvcbOptions(HttpsSvcbOptions&&);
  159. HttpsSvcbOptions& operator=(const HttpsSvcbOptions&) = default;
  160. HttpsSvcbOptions& operator=(HttpsSvcbOptions&&) = default;
  161. ~HttpsSvcbOptions();
  162. static HttpsSvcbOptions FromDict(const base::Value::Dict& dict);
  163. static HttpsSvcbOptions FromFeatures();
  164. bool enable = false;
  165. bool enable_insecure = false;
  166. base::TimeDelta insecure_extra_time_max;
  167. int insecure_extra_time_percent = 0;
  168. base::TimeDelta insecure_extra_time_min;
  169. base::TimeDelta secure_extra_time_max;
  170. int secure_extra_time_percent = 0;
  171. base::TimeDelta secure_extra_time_min;
  172. base::TimeDelta extra_time_absolute;
  173. int extra_time_percent = 0;
  174. };
  175. // Parameter-grouping struct for additional optional parameters for creation
  176. // of HostResolverManagers and stand-alone HostResolvers.
  177. struct NET_EXPORT ManagerOptions {
  178. ManagerOptions();
  179. ManagerOptions(const ManagerOptions&);
  180. ManagerOptions(ManagerOptions&&);
  181. ManagerOptions& operator=(const ManagerOptions&) = default;
  182. ManagerOptions& operator=(ManagerOptions&&) = default;
  183. ~ManagerOptions();
  184. // Set |max_concurrent_resolves| to this to select a default level
  185. // of concurrency.
  186. static const size_t kDefaultParallelism = 0;
  187. // Set |max_system_retry_attempts| to this to select a default retry value.
  188. static const size_t kDefaultRetryAttempts;
  189. // How many resolve requests will be allowed to run in parallel.
  190. // |kDefaultParallelism| for the resolver to choose a default value.
  191. size_t max_concurrent_resolves = kDefaultParallelism;
  192. // The maximum number of times to retry for host resolution if using the
  193. // system resolver. No effect when the system resolver is not used.
  194. // |kDefaultRetryAttempts| for the resolver to choose a default value.
  195. size_t max_system_retry_attempts = kDefaultRetryAttempts;
  196. // Initial setting for whether the insecure portion of the built-in
  197. // asynchronous DnsClient is enabled or disabled. See HostResolverManager::
  198. // SetInsecureDnsClientEnabled() for details.
  199. bool insecure_dns_client_enabled = false;
  200. // Initial setting for whether additional DNS types (e.g. HTTPS) may be
  201. // queried when using the built-in resolver for insecure DNS.
  202. bool additional_types_via_insecure_dns_enabled = true;
  203. // Initial configuration overrides for the built-in asynchronous DnsClient.
  204. // See HostResolverManager::SetDnsConfigOverrides() for details.
  205. DnsConfigOverrides dns_config_overrides;
  206. // If set to |false|, when on a WiFi connection, IPv6 will be assumed to be
  207. // unreachable without actually checking. See https://crbug.com/696569 for
  208. // further context.
  209. bool check_ipv6_on_wifi = true;
  210. // An experimental options for features::kUseDnsHttpsSvcb
  211. // and features::kUseDnsHttpsSvcbAlpn.
  212. absl::optional<HostResolver::HttpsSvcbOptions> https_svcb_options;
  213. };
  214. // Factory class. Useful for classes that need to inject and override resolver
  215. // creation for tests.
  216. class NET_EXPORT Factory {
  217. public:
  218. virtual ~Factory() = default;
  219. // See HostResolver::CreateResolver.
  220. virtual std::unique_ptr<HostResolver> CreateResolver(
  221. HostResolverManager* manager,
  222. base::StringPiece host_mapping_rules,
  223. bool enable_caching);
  224. // See HostResolver::CreateStandaloneResolver.
  225. virtual std::unique_ptr<HostResolver> CreateStandaloneResolver(
  226. NetLog* net_log,
  227. const ManagerOptions& options,
  228. base::StringPiece host_mapping_rules,
  229. bool enable_caching);
  230. };
  231. // Parameter-grouping struct for additional optional parameters for
  232. // CreateRequest() calls. All fields are optional and have a reasonable
  233. // default.
  234. struct NET_EXPORT ResolveHostParameters {
  235. ResolveHostParameters();
  236. ResolveHostParameters(const ResolveHostParameters& other);
  237. // Requested DNS query type. If UNSPECIFIED, the resolver will select a set
  238. // of queries automatically. It will select A, AAAA, or both as the address
  239. // queries, depending on IPv4/IPv6 settings and reachability. It may also
  240. // replace UNSPECIFIED with additional queries, such as HTTPS.
  241. DnsQueryType dns_query_type = DnsQueryType::UNSPECIFIED;
  242. // The initial net priority for the host resolution request.
  243. RequestPriority initial_priority = RequestPriority::DEFAULT_PRIORITY;
  244. // The source to use for resolved addresses. Default allows the resolver to
  245. // pick an appropriate source. Only affects use of big external sources (eg
  246. // calling the system for resolution or using DNS). Even if a source is
  247. // specified, results can still come from cache, resolving "localhost" or
  248. // IP literals, etc.
  249. HostResolverSource source = HostResolverSource::ANY;
  250. enum class CacheUsage {
  251. // Results may come from the host cache if non-stale.
  252. ALLOWED,
  253. // Results may come from the host cache even if stale (by expiration or
  254. // network changes). In secure dns AUTOMATIC mode, the cache is checked
  255. // for both secure and insecure results prior to any secure DNS lookups to
  256. // minimize response time.
  257. STALE_ALLOWED,
  258. // Results will not come from the host cache.
  259. DISALLOWED,
  260. };
  261. CacheUsage cache_usage = CacheUsage::ALLOWED;
  262. // If |true|, requests special behavior that the "canonical name" be
  263. // requested from the system and be returned as the only entry in
  264. // `ResolveHostRequest::GetDnsAliasResults()` results. Setting this
  265. // parameter is disallowed for any requests that cannot be resolved using
  266. // the system resolver, e.g. non-address requests or requests specifying a
  267. // non-`SYSTEM` `source`.
  268. //
  269. // TODO(crbug.com/1282281): Consider allowing the built-in resolver to still
  270. // be used with this parameter. Would then function as a request to just
  271. // keep the single final name from the alias chain instead of all aliases,
  272. // and also skip the canonicalization unless that canonicalization is found
  273. // to be fine for usage.
  274. bool include_canonical_name = false;
  275. // Hint to the resolver that resolution is only being requested for loopback
  276. // hosts.
  277. bool loopback_only = false;
  278. // Set |true| iff the host resolve request is only being made speculatively
  279. // to fill the cache and the result addresses will not be used. The request
  280. // will receive special logging/observer treatment, and the result addresses
  281. // will always be |absl::nullopt|.
  282. bool is_speculative = false;
  283. // If `true`, resolver may (but is not guaranteed to) take steps to avoid
  284. // the name being resolved via LLMNR or mDNS. Useful for requests where it
  285. // is not desired to wait for longer timeouts on potential negative results,
  286. // as is typically the case for LLMNR or mDNS queries without any results.
  287. bool avoid_multicast_resolution = false;
  288. // Controls the resolver's Secure DNS behavior for this request.
  289. SecureDnsPolicy secure_dns_policy = SecureDnsPolicy::kAllow;
  290. };
  291. // Handler for an ongoing MDNS listening operation. Created by
  292. // HostResolver::CreateMdnsListener().
  293. class MdnsListener {
  294. public:
  295. // Delegate type for result update notifications from MdnsListener. All
  296. // methods have a |result_type| field to allow a single delegate to be
  297. // passed to multiple MdnsListeners and be used to listen for updates for
  298. // multiple types for the same host.
  299. class Delegate {
  300. public:
  301. virtual ~Delegate() = default;
  302. virtual void OnAddressResult(MdnsListenerUpdateType update_type,
  303. DnsQueryType result_type,
  304. IPEndPoint address) = 0;
  305. virtual void OnTextResult(MdnsListenerUpdateType update_type,
  306. DnsQueryType result_type,
  307. std::vector<std::string> text_records) = 0;
  308. virtual void OnHostnameResult(MdnsListenerUpdateType update_type,
  309. DnsQueryType result_type,
  310. HostPortPair host) = 0;
  311. // For results which may be valid MDNS but are not handled/parsed by
  312. // HostResolver, e.g. pointers to the root domain.
  313. virtual void OnUnhandledResult(MdnsListenerUpdateType update_type,
  314. DnsQueryType result_type) = 0;
  315. };
  316. // Destruction cancels the listening operation.
  317. virtual ~MdnsListener() = default;
  318. // Begins the listening operation, invoking |delegate| whenever results are
  319. // updated. |delegate| will no longer be called once the listening operation
  320. // is cancelled (via destruction of |this|).
  321. virtual int Start(Delegate* delegate) = 0;
  322. };
  323. HostResolver(const HostResolver&) = delete;
  324. HostResolver& operator=(const HostResolver&) = delete;
  325. // If any completion callbacks are pending when the resolver is destroyed,
  326. // the host resolutions are cancelled, and the completion callbacks will not
  327. // be called.
  328. virtual ~HostResolver();
  329. // Cancels any pending requests without calling callbacks, same as
  330. // destruction, except also leaves the resolver in a mostly-noop state. Any
  331. // future request Start() calls (for requests created before or after
  332. // OnShutdown()) will immediately fail with ERR_CONTEXT_SHUT_DOWN.
  333. virtual void OnShutdown() = 0;
  334. // Creates a request to resolve the given hostname (or IP address literal).
  335. // Profiling information for the request is saved to |net_log| if non-NULL.
  336. //
  337. // Additional parameters may be set using |optional_parameters|. Reasonable
  338. // defaults will be used if passed |nullptr|.
  339. virtual std::unique_ptr<ResolveHostRequest> CreateRequest(
  340. url::SchemeHostPort host,
  341. NetworkIsolationKey network_isolation_key,
  342. NetLogWithSource net_log,
  343. absl::optional<ResolveHostParameters> optional_parameters) = 0;
  344. // Create requests when scheme is unknown or non-standard.
  345. // TODO(crbug.com/1206799): Rename to discourage use when scheme is known.
  346. virtual std::unique_ptr<ResolveHostRequest> CreateRequest(
  347. const HostPortPair& host,
  348. const NetworkIsolationKey& network_isolation_key,
  349. const NetLogWithSource& net_log,
  350. const absl::optional<ResolveHostParameters>& optional_parameters) = 0;
  351. // Creates a request to probe configured DoH servers to find which can be used
  352. // successfully.
  353. virtual std::unique_ptr<ProbeRequest> CreateDohProbeRequest();
  354. // Create a listener to watch for updates to an MDNS result.
  355. virtual std::unique_ptr<MdnsListener> CreateMdnsListener(
  356. const HostPortPair& host,
  357. DnsQueryType query_type);
  358. // Returns the HostResolverCache |this| uses, or NULL if there isn't one.
  359. // Used primarily to clear the cache and for getting debug information.
  360. virtual HostCache* GetHostCache();
  361. // Returns the current DNS configuration |this| is using, as a Value.
  362. virtual base::Value GetDnsConfigAsValue() const;
  363. // Set the associated URLRequestContext, generally expected to be called by
  364. // URLRequestContextBuilder on passing ownership of |this| to a context. May
  365. // only be called once.
  366. virtual void SetRequestContext(URLRequestContext* request_context);
  367. virtual HostResolverManager* GetManagerForTesting();
  368. virtual const URLRequestContext* GetContextForTesting() const;
  369. virtual handles::NetworkHandle GetTargetNetworkForTesting() const;
  370. // Creates a new HostResolver. |manager| must outlive the returned resolver.
  371. //
  372. // If |mapping_rules| is non-empty, the mapping rules will be applied to
  373. // requests. See MappedHostResolver for details.
  374. static std::unique_ptr<HostResolver> CreateResolver(
  375. HostResolverManager* manager,
  376. base::StringPiece host_mapping_rules = "",
  377. bool enable_caching = true);
  378. // Creates a HostResolver independent of any global HostResolverManager. Only
  379. // for tests and standalone tools not part of the browser.
  380. //
  381. // If |mapping_rules| is non-empty, the mapping rules will be applied to
  382. // requests. See MappedHostResolver for details.
  383. static std::unique_ptr<HostResolver> CreateStandaloneResolver(
  384. NetLog* net_log,
  385. absl::optional<ManagerOptions> options = absl::nullopt,
  386. base::StringPiece host_mapping_rules = "",
  387. bool enable_caching = true);
  388. // Same, but explicitly returns the implementing ContextHostResolver. Only
  389. // used by tests and by StaleHostResolver in Cronet. No mapping rules can be
  390. // applied because doing so requires wrapping the ContextHostResolver.
  391. static std::unique_ptr<ContextHostResolver> CreateStandaloneContextResolver(
  392. NetLog* net_log,
  393. absl::optional<ManagerOptions> options = absl::nullopt,
  394. bool enable_caching = true);
  395. // Same, but bind the resolver to `target_network`: all lookups will be
  396. // performed exclusively for `target_network`, lookups will fail if
  397. // `target_network` disconnects. This can only be used by network-bound
  398. // URLRequestContexts.
  399. // Due to the current implementation, if `options` is specified, its
  400. // DnsConfigOverrides parameter must be empty.
  401. // Only implemented for Android starting from Marshmallow.
  402. static std::unique_ptr<HostResolver> CreateStandaloneNetworkBoundResolver(
  403. NetLog* net_log,
  404. handles::NetworkHandle network,
  405. absl::optional<ManagerOptions> options = absl::nullopt,
  406. base::StringPiece host_mapping_rules = "",
  407. bool enable_caching = true);
  408. // Helpers for interacting with HostCache and ProcResolver.
  409. static AddressFamily DnsQueryTypeSetToAddressFamily(
  410. DnsQueryTypeSet query_types);
  411. static HostResolverFlags ParametersToHostResolverFlags(
  412. const ResolveHostParameters& parameters);
  413. // Helper for squashing error code to a small set of DNS error codes.
  414. static int SquashErrorCode(int error);
  415. // Utility to convert an AddressList to an equivalent list of
  416. // `HostResolverEndpointResults`. Assumes all addresses in the input list
  417. // represent the default non-protocol endpoint.
  418. //
  419. // TODO(crbug.com/1264933): Delete once `AddressList` usage is fully replaced
  420. // in `HostResolver` and results.
  421. static std::vector<HostResolverEndpointResult> AddressListToEndpointResults(
  422. const AddressList& address_list);
  423. // Opposite conversion of `AddressListToEndpointResults()`. Builds an
  424. // AddressList from the first non-protocol endpoint found in `endpoints`.
  425. //
  426. // TODO(crbug.com/1264933): Delete once `AddressList` usage is fully replaced
  427. // in `HostResolver` and results.
  428. static AddressList EndpointResultToAddressList(
  429. const std::vector<HostResolverEndpointResult>& endpoints,
  430. const std::set<std::string>& aliases);
  431. protected:
  432. HostResolver();
  433. // Utility to create a request implementation that always fails with |error|
  434. // immediately on start.
  435. static std::unique_ptr<ResolveHostRequest> CreateFailingRequest(int error);
  436. static std::unique_ptr<ProbeRequest> CreateFailingProbeRequest(int error);
  437. };
  438. } // namespace net
  439. #endif // NET_DNS_HOST_RESOLVER_H_