xref: /aosp_15_r20/external/cronet/net/dns/host_resolver_manager.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
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_HOST_RESOLVER_MANAGER_H_
6 #define NET_DNS_HOST_RESOLVER_MANAGER_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <deque>
12 #include <map>
13 #include <memory>
14 #include <optional>
15 #include <set>
16 #include <string>
17 #include <string_view>
18 #include <vector>
19 
20 #include "base/functional/callback.h"
21 #include "base/functional/callback_helpers.h"
22 #include "base/memory/raw_ptr.h"
23 #include "base/memory/scoped_refptr.h"
24 #include "base/memory/weak_ptr.h"
25 #include "base/observer_list.h"
26 #include "base/time/time.h"
27 #include "base/timer/timer.h"
28 #include "base/values.h"
29 #include "net/base/completion_once_callback.h"
30 #include "net/base/host_port_pair.h"
31 #include "net/base/network_anonymization_key.h"
32 #include "net/base/network_change_notifier.h"
33 #include "net/base/network_handle.h"
34 #include "net/base/prioritized_dispatcher.h"
35 #include "net/dns/dns_config.h"
36 #include "net/dns/host_cache.h"
37 #include "net/dns/host_resolver.h"
38 #include "net/dns/httpssvc_metrics.h"
39 #include "net/dns/public/dns_config_overrides.h"
40 #include "net/dns/public/dns_query_type.h"
41 #include "net/dns/public/secure_dns_mode.h"
42 #include "net/dns/public/secure_dns_policy.h"
43 #include "net/dns/resolve_context.h"
44 #include "net/dns/system_dns_config_change_notifier.h"
45 #include "net/log/net_log_with_source.h"
46 #include "net/socket/datagram_client_socket.h"
47 #include "third_party/abseil-cpp/absl/types/variant.h"
48 #include "url/gurl.h"
49 #include "url/scheme_host_port.h"
50 
51 namespace base {
52 class TickClock;
53 }  // namespace base
54 
55 namespace net {
56 
57 class DnsClient;
58 class DnsProbeRunner;
59 class IPAddress;
60 class MDnsClient;
61 class ClientSocketFactory;
62 class MDnsSocketFactory;
63 class NetLog;
64 
65 // Scheduler and controller of host resolution requests. Because of the global
66 // nature of host resolutions, this class is generally expected to be singleton
67 // within the browser and only be interacted with through per-context
68 // ContextHostResolver objects (which are themselves generally interacted with
69 // though the HostResolver interface).
70 //
71 // For each hostname that is requested, HostResolver creates a
72 // HostResolverManager::Job. When this job gets dispatched it creates a task
73 // (HostResolverSystemTask for the system resolver or DnsTask for the async
74 // resolver) which resolves the hostname. If requests for that same host are
75 // made during the job's lifetime, they are attached to the existing job rather
76 // than creating a new one. This avoids doing parallel resolves for the same
77 // host.
78 //
79 // The way these classes fit together is illustrated by:
80 //
81 //
82 //            +----------- HostResolverManager ----------+
83 //            |                    |                     |
84 //           Job                  Job                   Job
85 //    (for host1, fam1)    (for host2, fam2)     (for hostx, famx)
86 //       /    |   |            /   |   |             /   |   |
87 //   Request ... Request  Request ... Request   Request ... Request
88 //  (port1)     (port2)  (port3)      (port4)  (port5)      (portX)
89 //
90 // When a HostResolverManager::Job finishes, the callbacks of each waiting
91 // request are run on the origin thread.
92 //
93 // Thread safety: This class is not threadsafe, and must only be called
94 // from one thread!
95 //
96 // The HostResolverManager enforces limits on the maximum number of concurrent
97 // threads using PrioritizedDispatcher::Limits.
98 //
99 // Jobs are ordered in the queue based on their priority and order of arrival.
100 class NET_EXPORT HostResolverManager
101     : public NetworkChangeNotifier::IPAddressObserver,
102       public NetworkChangeNotifier::ConnectionTypeObserver,
103       public SystemDnsConfigChangeNotifier::Observer {
104  public:
105   using MdnsListener = HostResolver::MdnsListener;
106   using ResolveHostParameters = HostResolver::ResolveHostParameters;
107   using PassKey = base::PassKey<HostResolverManager>;
108 
109   struct NET_EXPORT_PRIVATE JobKey;
110   class NET_EXPORT_PRIVATE Job;
111   class NET_EXPORT_PRIVATE RequestImpl;
112   class NET_EXPORT_PRIVATE ServiceEndpointRequestImpl;
113 
114   // Creates a HostResolver as specified by |options|. Blocking tasks are run in
115   // ThreadPool.
116   //
117   // If Options.enable_caching is true, a cache is created using
118   // HostCache::CreateDefaultCache(). Otherwise no cache is used.
119   //
120   // Options.GetDispatcherLimits() determines the maximum number of jobs that
121   // the resolver will run at once. This upper-bounds the total number of
122   // outstanding DNS transactions (not counting retransmissions and retries).
123   //
124   // |net_log| and |system_dns_config_notifier|, if non-null, must remain valid
125   // for the life of the HostResolverManager.
126   HostResolverManager(const HostResolver::ManagerOptions& options,
127                       SystemDnsConfigChangeNotifier* system_dns_config_notifier,
128                       NetLog* net_log);
129 
130   HostResolverManager(const HostResolverManager&) = delete;
131   HostResolverManager& operator=(const HostResolverManager&) = delete;
132 
133   // If any completion callbacks are pending when the resolver is destroyed,
134   // the host resolutions are cancelled, and the completion callbacks will not
135   // be called.
136   ~HostResolverManager() override;
137 
138   // Same as constructor above, but binds the HostResolverManager to
139   // `target_network`: all DNS requests will be performed for `target_network`
140   // only, requests will fail if `target_network` disconnects. Only
141   // HostResolvers bound to the same network will be able to use this.
142   // Only implemented for Android.
143   static std::unique_ptr<HostResolverManager>
144   CreateNetworkBoundHostResolverManager(
145       const HostResolver::ManagerOptions& options,
146       handles::NetworkHandle target_network,
147       NetLog* net_log);
148 
149   // Creates a host resolution request. `resolve_context` must have already been
150   // added via RegisterResolveContext(). If `optional_parameters` specifies any
151   // cache usage other than LOCAL_ONLY, `resolve_context` should have a valid
152   // `host_cache()` coming from a ContextHostResolver that owns
153   // `resolve_context`.
154   std::unique_ptr<HostResolver::ResolveHostRequest> CreateRequest(
155       absl::variant<url::SchemeHostPort, HostPortPair> host,
156       NetworkAnonymizationKey network_anonymization_key,
157       NetLogWithSource net_log,
158       std::optional<ResolveHostParameters> optional_parameters,
159       ResolveContext* resolve_context);
160   std::unique_ptr<HostResolver::ResolveHostRequest> CreateRequest(
161       HostResolver::Host host,
162       NetworkAnonymizationKey network_anonymization_key,
163       NetLogWithSource net_log,
164       std::optional<ResolveHostParameters> optional_parameters,
165       ResolveContext* resolve_context);
166   // |resolve_context| is the context to use for the probes, and it is expected
167   // to be the context of the calling ContextHostResolver.
168   std::unique_ptr<HostResolver::ProbeRequest> CreateDohProbeRequest(
169       ResolveContext* resolve_context);
170   std::unique_ptr<MdnsListener> CreateMdnsListener(const HostPortPair& host,
171                                                    DnsQueryType query_type);
172 
173   // Creates a service endpoint resolution request.
174   std::unique_ptr<HostResolver::ServiceEndpointRequest>
175   CreateServiceEndpointRequest(
176       url::SchemeHostPort scheme_host_port,
177       NetworkAnonymizationKey network_anonymization_key,
178       NetLogWithSource net_log,
179       ResolveHostParameters parameters,
180       ResolveContext* resolve_context);
181 
182   // Enables or disables the built-in asynchronous DnsClient. If enabled, by
183   // default (when no |ResolveHostParameters::source| is specified), the
184   // DnsClient will be used for resolves and, in case of failure, resolution
185   // will fallback to the system resolver (in tests, HostResolverProc from
186   // HostResolverSystemTask::Params). If the DnsClient is not pre-configured
187   // with a valid DnsConfig, a new config is fetched from NetworkChangeNotifier.
188   //
189   // Setting to |true| has no effect if |ENABLE_BUILT_IN_DNS| not defined.
190   virtual void SetInsecureDnsClientEnabled(bool enabled,
191                                            bool additional_dns_types_enabled);
192 
193   base::Value::Dict GetDnsConfigAsValue() const;
194 
195   // Sets overriding configuration that will replace or add to configuration
196   // read from the system for DnsClient resolution.
197   void SetDnsConfigOverrides(DnsConfigOverrides overrides);
198 
199   void SetIPv6ReachabilityOverride(bool reachability_override);
200 
201   // Support for invalidating cached per-context data on changes to network or
202   // DNS configuration. ContextHostResolvers should register/deregister
203   // themselves here rather than attempting to listen for relevant network
204   // change signals themselves because HostResolverManager needs to coordinate
205   // invalidations with in-progress resolves and because some invalidations are
206   // triggered by changes to manager properties/configuration rather than pure
207   // network changes.
208   //
209   // Note: Invalidation handling must not call back into HostResolverManager as
210   // the invalidation is expected to be handled atomically with other clearing
211   // and aborting actions.
212   void RegisterResolveContext(ResolveContext* context);
213   void DeregisterResolveContext(const ResolveContext* context);
214 
set_host_resolver_system_params_for_test(const HostResolverSystemTask::Params & host_resolver_system_params)215   void set_host_resolver_system_params_for_test(
216       const HostResolverSystemTask::Params& host_resolver_system_params) {
217     host_resolver_system_params_ = host_resolver_system_params;
218   }
219 
InvalidateCachesForTesting()220   void InvalidateCachesForTesting() { InvalidateCaches(); }
221 
222   void SetTickClockForTesting(const base::TickClock* tick_clock);
223 
224   // Configures maximum number of Jobs in the queue. Exposed for testing.
225   // Only allowed when the queue is empty.
226   void SetMaxQueuedJobsForTesting(size_t value);
227 
228   void SetMdnsSocketFactoryForTesting(
229       std::unique_ptr<MDnsSocketFactory> socket_factory);
230   void SetMdnsClientForTesting(std::unique_ptr<MDnsClient> client);
231 
232   // To simulate modifications it would have received if |dns_client| had been
233   // in place before calling this, DnsConfig will be set with the configuration
234   // from the previous DnsClient being replaced (including system config if
235   // |dns_client| does not already contain a system config). This means tests do
236   // not normally need to worry about ordering between setting a test client and
237   // setting DnsConfig.
238   void SetDnsClientForTesting(std::unique_ptr<DnsClient> dns_client);
239 
240   // Explicitly disable the system resolver even if tests have set a catch-all
241   // DNS block. See `ForceSystemResolverDueToTestOverride`.
DisableSystemResolverForTesting()242   void DisableSystemResolverForTesting() {
243     system_resolver_disabled_for_testing_ = true;
244   }
245 
246   // Sets the last IPv6 probe result for testing. Uses the standard timeout
247   // duration, so it's up to the test fixture to ensure it doesn't expire by
248   // mocking time, if expiration would pose a problem.
249   void SetLastIPv6ProbeResultForTesting(bool last_ipv6_probe_result);
250 
ResetIPv6ProbeTimeForTesting()251   void ResetIPv6ProbeTimeForTesting() {
252     last_ipv6_probe_time_ = base::TimeTicks();
253   }
254 
255   // Allows the tests to catch slots leaking out of the dispatcher.  One
256   // HostResolverManager::Job could occupy multiple PrioritizedDispatcher job
257   // slots.
num_running_dispatcher_jobs_for_tests()258   size_t num_running_dispatcher_jobs_for_tests() const {
259     return dispatcher_->num_running_jobs();
260   }
261 
num_jobs_for_testing()262   size_t num_jobs_for_testing() const { return jobs_.size(); }
263 
check_ipv6_on_wifi_for_testing()264   bool check_ipv6_on_wifi_for_testing() const { return check_ipv6_on_wifi_; }
265 
target_network_for_testing()266   handles::NetworkHandle target_network_for_testing() const {
267     return target_network_;
268   }
269 
https_svcb_options_for_testing()270   const HostResolver::HttpsSvcbOptions& https_svcb_options_for_testing() const {
271     return https_svcb_options_;
272   }
273 
274   // Public to be called from std::make_unique. Not to be called directly.
275   HostResolverManager(base::PassKey<HostResolverManager>,
276                       const HostResolver::ManagerOptions& options,
277                       SystemDnsConfigChangeNotifier* system_dns_config_notifier,
278                       handles::NetworkHandle target_network,
279                       NetLog* net_log);
280 
281  protected:
282   // Callback from HaveOnlyLoopbackAddresses probe.
283   void SetHaveOnlyLoopbackAddresses(bool result);
284 
285  private:
286   friend class HostResolverManagerTest;
287   friend class HostResolverManagerDnsTest;
288   class LoopbackProbeJob;
289   class ProbeRequestImpl;
290   using JobMap = std::map<JobKey, std::unique_ptr<Job>>;
291 
292   // Task types that a Job might run.
293   // These values are persisted to logs. Entries should not be renumbered and
294   // numeric values should never be reused
295   enum class TaskType {
296     SYSTEM = 0,
297     DNS = 1,
298     SECURE_DNS = 2,
299     MDNS = 3,
300     CACHE_LOOKUP = 4,
301     INSECURE_CACHE_LOOKUP = 5,
302     SECURE_CACHE_LOOKUP = 6,
303     CONFIG_PRESET = 7,
304     NAT64 = 8,
305     HOSTS = 9,
306 
307     kMaxValue = HOSTS,
308   };
309 
310   // Returns true if the task is local, synchronous, and instantaneous.
311   static bool IsLocalTask(TaskType task);
312 
313   // Initializes a job key and an IP address using manager properties and IPv6
314   // reachability. These job key and IP address are used to call
315   // ResolveLocally() and CreateAndStartJob().
316   void InitializeJobKeyAndIPAddress(
317       const NetworkAnonymizationKey& network_anonymization_key,
318       const ResolveHostParameters& parameters,
319       const NetLogWithSource& source_net_log,
320       JobKey& out_job_key,
321       IPAddress& out_ip_address);
322 
323   // Attempts host resolution using fast local sources: IP literal resolution,
324   // cache lookup, HOSTS lookup (if enabled), and localhost. Returns results
325   // with error() OK if successful, ERR_NAME_NOT_RESOLVED if input is invalid,
326   // or ERR_DNS_CACHE_MISS if the host could not be resolved using local
327   // sources.
328   //
329   // On ERR_DNS_CACHE_MISS and OK, |out_tasks| contains the tentative
330   // sequence of tasks that a future job should run.
331   //
332   // If results are returned from the host cache, |out_stale_info| will be
333   // filled in with information on how stale or fresh the result is. Otherwise,
334   // |out_stale_info| will be set to |std::nullopt|.
335   //
336   // If |cache_usage == ResolveHostParameters::CacheUsage::STALE_ALLOWED|, then
337   // stale cache entries can be returned.
338   HostCache::Entry ResolveLocally(
339       bool only_ipv6_reachable,
340       const JobKey& job_key,
341       const IPAddress& ip_address,
342       ResolveHostParameters::CacheUsage cache_usage,
343       SecureDnsPolicy secure_dns_policy,
344       HostResolverSource source,
345       const NetLogWithSource& source_net_log,
346       HostCache* cache,
347       std::deque<TaskType>* out_tasks,
348       std::optional<HostCache::EntryStaleness>* out_stale_info);
349 
350   // Creates and starts a Job to asynchronously attempt to resolve
351   // |request|.
352   void CreateAndStartJob(JobKey key,
353                          std::deque<TaskType> tasks,
354                          RequestImpl* request);
355 
356   HostResolverManager::Job* AddJobWithoutRequest(
357       JobKey key,
358       ResolveHostParameters::CacheUsage cache_usage,
359       HostCache* host_cache,
360       std::deque<TaskType> tasks,
361       RequestPriority priority,
362       const NetLogWithSource& source_net_log);
363 
364   // Similar to CreateAndStartJob(), but for a ServiceEndpointRequest.
365   void CreateAndStartJobForServiceEndpointRequest(
366       JobKey key,
367       std::deque<TaskType> tasks,
368       ServiceEndpointRequestImpl* request);
369 
370   // Resolves the IP literal hostname represented by `ip_address`.
371   HostCache::Entry ResolveAsIP(DnsQueryTypeSet query_types,
372                                bool resolve_canonname,
373                                const IPAddress& ip_address);
374 
375   // Returns the result iff |cache_usage| permits cache lookups and a positive
376   // match is found for |key| in |cache|. |out_stale_info| must be non-null, and
377   // will be filled in with details of the entry's staleness if an entry is
378   // returned, otherwise it will be set to |std::nullopt|.
379   std::optional<HostCache::Entry> MaybeServeFromCache(
380       HostCache* cache,
381       const HostCache::Key& key,
382       ResolveHostParameters::CacheUsage cache_usage,
383       bool ignore_secure,
384       const NetLogWithSource& source_net_log,
385       std::optional<HostCache::EntryStaleness>* out_stale_info);
386 
387   // Returns any preset resolution result from the active DoH configuration that
388   // matches |key.host|.
389   std::optional<HostCache::Entry> MaybeReadFromConfig(const JobKey& key);
390 
391   // Populates the secure cache with an optimal entry that supersedes the
392   // bootstrap result.
393   void StartBootstrapFollowup(JobKey key,
394                               HostCache* host_cache,
395                               const NetLogWithSource& source_net_log);
396 
397   // Iff we have a DnsClient with a valid DnsConfig and we're not about to
398   // attempt a system lookup, then try to resolve the query using the HOSTS
399   // file.
400   std::optional<HostCache::Entry> ServeFromHosts(
401       std::string_view hostname,
402       DnsQueryTypeSet query_types,
403       bool default_family_due_to_no_ipv6,
404       const std::deque<TaskType>& tasks);
405 
406   // Iff |key| is for a localhost name (RFC 6761) and address DNS query type,
407   // returns a results entry with the loopback IP.
408   std::optional<HostCache::Entry> ServeLocalhost(
409       std::string_view hostname,
410       DnsQueryTypeSet query_types,
411       bool default_family_due_to_no_ipv6);
412 
413   // Returns the secure dns mode to use for a job, taking into account the
414   // global DnsConfig mode and any per-request policy.
415   SecureDnsMode GetEffectiveSecureDnsMode(SecureDnsPolicy secure_dns_policy);
416 
417   // Returns true when a catch-all DNS block has been set for tests, unless
418   // `SetDisableSystemResolverForTesting` has been called to explicitly disable
419   // that safety net. DnsTasks should never be issued when this returns true.
420   bool ShouldForceSystemResolverDueToTestOverride() const;
421 
422   // Helper method to add DnsTasks and related tasks based on the SecureDnsMode
423   // and fallback parameters. If |prioritize_local_lookups| is true, then we
424   // may push an insecure cache lookup ahead of a secure DnsTask.
425   void PushDnsTasks(bool system_task_allowed,
426                     SecureDnsMode secure_dns_mode,
427                     bool insecure_tasks_allowed,
428                     bool allow_cache,
429                     bool prioritize_local_lookups,
430                     ResolveContext* resolve_context,
431                     std::deque<TaskType>* out_tasks);
432 
433   // Initialized the sequence of tasks to run to resolve a request. The sequence
434   // may be adjusted later and not all tasks need to be run.
435   void CreateTaskSequence(const JobKey& job_key,
436                           ResolveHostParameters::CacheUsage cache_usage,
437                           SecureDnsPolicy secure_dns_policy,
438                           std::deque<TaskType>* out_tasks);
439 
440   // Schedules probes to check IPv6 support. Returns OK if probe results are
441   // already cached, and ERR_IO_PENDING when a probe is scheduled to be
442   // completed asynchronously. When called repeatedly this method returns OK to
443   // confirm that results have been cached.
444   int StartIPv6ReachabilityCheck(const NetLogWithSource& net_log,
445                                  ClientSocketFactory* client_socket_factory,
446                                  CompletionOnceCallback callback);
447 
448   void FinishIPv6ReachabilityCheck(CompletionOnceCallback callback, int rv);
449 
450   // Sets |last_ipv6_probe_result_| and updates |last_ipv6_probe_time_|.
451   void SetLastIPv6ProbeResult(bool last_ipv6_probe_result);
452 
453   // Attempts to connect a UDP socket to |dest|:53. Virtual for testing. Returns
454   // the value of the attempted socket connection and the reachability check. If
455   // the return value from the connection is not ERR_IO_PENDING, callers must
456   // handle the results of the reachability check themselves. Otherwise the
457   // result of the reachability check will be set when `callback` is run.
458   // Returns OK if the reachability check succeeded, ERR_FAILED if it failed,
459   // ERR_IO_PENDING if it will be asynchronous.
460   virtual int StartGloballyReachableCheck(
461       const IPAddress& dest,
462       const NetLogWithSource& net_log,
463       ClientSocketFactory* client_socket_factory,
464       CompletionOnceCallback callback);
465 
466   bool FinishGloballyReachableCheck(DatagramClientSocket* socket, int rv);
467 
468   void RunFinishGloballyReachableCheck(
469       scoped_refptr<base::RefCountedData<std::unique_ptr<DatagramClientSocket>>>
470           socket,
471       CompletionOnceCallback callback,
472       int rv);
473 
474   // Asynchronously checks if only loopback IPs are available.
475   virtual void RunLoopbackProbeJob();
476 
477   // Records the result in cache if cache is present.
478   void CacheResult(HostCache* cache,
479                    const HostCache::Key& key,
480                    const HostCache::Entry& entry,
481                    base::TimeDelta ttl);
482 
483   // Removes |job_it| from |jobs_| and return.
484   std::unique_ptr<Job> RemoveJob(JobMap::iterator job_it);
485 
486   // Removes Jobs for this context.
487   void RemoveAllJobs(const ResolveContext* context);
488 
489   // Aborts all jobs (both scheduled and running) which are not targeting a
490   // specific network with ERR_NETWORK_CHANGED and notifies their requests.
491   // Aborts only running jobs if `in_progress_only` is true. Might start new
492   // jobs.
493   void AbortJobsWithoutTargetNetwork(bool in_progress_only);
494 
495   // Aborts all in progress insecure DnsTasks. In-progress jobs will fall back
496   // to HostResolverSystemTasks if able and otherwise abort with |error|. Might
497   // start new jobs, if any jobs were taking up two dispatcher slots.
498   //
499   // If |fallback_only|, insecure DnsTasks will only abort if they can fallback
500   // to HostResolverSystemTasks.
501   void AbortInsecureDnsTasks(int error, bool fallback_only);
502 
503   // Attempts to serve each Job in |jobs_| from the HOSTS file if we have
504   // a DnsClient with a valid DnsConfig.
505   void TryServingAllJobsFromHosts();
506 
507   // NetworkChangeNotifier::IPAddressObserver:
508   void OnIPAddressChanged() override;
509 
510   // NetworkChangeNotifier::ConnectionTypeObserver:
511   void OnConnectionTypeChanged(
512       NetworkChangeNotifier::ConnectionType type) override;
513 
514   // SystemDnsConfigChangeNotifier::Observer:
515   void OnSystemDnsConfigChanged(std::optional<DnsConfig> config) override;
516 
517   void UpdateJobsForChangedConfig();
518 
519   // Called on successful resolve after falling back to HostResolverSystemTask
520   // after a failed DnsTask resolve.
521   void OnFallbackResolve(int dns_task_error);
522 
523   int GetOrCreateMdnsClient(MDnsClient** out_client);
524 
525   // |network_change| indicates whether or not the invalidation was triggered
526   // by a network connection change.
527   void InvalidateCaches(bool network_change = false);
528 
529   void UpdateConnectionType(NetworkChangeNotifier::ConnectionType type);
530 
IsBoundToNetwork()531   bool IsBoundToNetwork() const {
532     return target_network_ != handles::kInvalidNetworkHandle;
533   }
534 
535   // Returns |nullptr| if DoH probes are currently not allowed (due to
536   // configuration or current connection state).
537   std::unique_ptr<DnsProbeRunner> CreateDohProbeRunner(
538       ResolveContext* resolve_context);
539 
540   // Used for multicast DNS tasks. Created on first use using
541   // GetOrCreateMndsClient().
542   std::unique_ptr<MDnsSocketFactory> mdns_socket_factory_;
543   std::unique_ptr<MDnsClient> mdns_client_;
544 
545   // Map from HostCache::Key to a Job.
546   JobMap jobs_;
547 
548   // Starts Jobs according to their priority and the configured limits.
549   std::unique_ptr<PrioritizedDispatcher> dispatcher_;
550 
551   // Limit on the maximum number of jobs queued in |dispatcher_|.
552   size_t max_queued_jobs_ = 0;
553 
554   // Parameters for HostResolverSystemTask.
555   HostResolverSystemTask::Params host_resolver_system_params_;
556 
557   raw_ptr<NetLog> net_log_;
558 
559   // If present, used by DnsTask and ServeFromHosts to resolve requests.
560   std::unique_ptr<DnsClient> dns_client_;
561 
562   raw_ptr<SystemDnsConfigChangeNotifier> system_dns_config_notifier_;
563 
564   handles::NetworkHandle target_network_;
565 
566   // False if IPv6 should not be attempted and assumed unreachable when on a
567   // WiFi connection. See https://crbug.com/696569 for further context.
568   bool check_ipv6_on_wifi_;
569 
570   base::TimeTicks last_ipv6_probe_time_;
571   bool last_ipv6_probe_result_ = true;
572   bool probing_ipv6_ = false;
573 
574   // When true, query AAAA even when the globally reachable check failed.
575   bool ipv6_reachability_override_ = false;
576 
577   // Any resolver flags that should be added to a request by default.
578   HostResolverFlags additional_resolver_flags_ = 0;
579 
580   // Allow fallback to HostResolverSystemTask if DnsTask fails.
581   bool allow_fallback_to_systemtask_ = true;
582 
583   // Shared tick clock, overridden for testing.
584   raw_ptr<const base::TickClock> tick_clock_;
585 
586   // When true, ignore the catch-all DNS block if it exists.
587   bool system_resolver_disabled_for_testing_ = false;
588 
589   // For per-context cache invalidation notifications.
590   base::ObserverList<ResolveContext,
591                      true /* check_empty */,
592                      false /* allow_reentrancy */>
593       registered_contexts_;
594   bool invalidation_in_progress_ = false;
595 
596   // An experimental flag for features::kUseDnsHttpsSvcb.
597   HostResolver::HttpsSvcbOptions https_svcb_options_;
598 
599   std::vector<CompletionOnceCallback> ipv6_request_callbacks_;
600 
601   THREAD_CHECKER(thread_checker_);
602 
603   base::WeakPtrFactory<HostResolverManager> weak_ptr_factory_{this};
604 
605   base::WeakPtrFactory<HostResolverManager> probe_weak_ptr_factory_{this};
606 };
607 
608 // Resolves a local hostname (such as "localhost" or "vhost.localhost") into
609 // IP endpoints (with port 0). Returns true if |host| is a local
610 // hostname and false otherwise. Names will resolve to both IPv4 and IPv6.
611 // This function is only exposed so it can be unit-tested.
612 // TODO(tfarina): It would be better to change the tests so this function
613 // gets exercised indirectly through HostResolverManager.
614 NET_EXPORT_PRIVATE bool ResolveLocalHostname(
615     std::string_view host,
616     std::vector<IPEndPoint>* address_list);
617 
618 }  // namespace net
619 
620 #endif  // NET_DNS_HOST_RESOLVER_MANAGER_H_
621