Remove "Default Address Family" behavior from the HostResolver.
[chromium-blink-merge.git] / net / dns / host_resolver_impl.h
blobe3b8ed7685ea5b935287a4a405e9769b45938ddf
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.
5 #ifndef NET_DNS_HOST_RESOLVER_IMPL_H_
6 #define NET_DNS_HOST_RESOLVER_IMPL_H_
8 #include <map>
10 #include "base/basictypes.h"
11 #include "base/gtest_prod_util.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/scoped_vector.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/threading/non_thread_safe.h"
16 #include "base/time/time.h"
17 #include "net/base/net_export.h"
18 #include "net/base/net_util.h"
19 #include "net/base/network_change_notifier.h"
20 #include "net/dns/host_cache.h"
21 #include "net/dns/host_resolver.h"
22 #include "net/dns/host_resolver_proc.h"
24 namespace net {
26 class BoundNetLog;
27 class DnsClient;
28 class NetLog;
30 // For each hostname that is requested, HostResolver creates a
31 // HostResolverImpl::Job. When this job gets dispatched it creates a ProcTask
32 // which runs the given HostResolverProc on a WorkerPool thread. If requests for
33 // that same host are made during the job's lifetime, they are attached to the
34 // existing job rather than creating a new one. This avoids doing parallel
35 // resolves for the same host.
37 // The way these classes fit together is illustrated by:
40 // +----------- HostResolverImpl -------------+
41 // | | |
42 // Job Job Job
43 // (for host1, fam1) (for host2, fam2) (for hostx, famx)
44 // / | | / | | / | |
45 // Request ... Request Request ... Request Request ... Request
46 // (port1) (port2) (port3) (port4) (port5) (portX)
48 // When a HostResolverImpl::Job finishes, the callbacks of each waiting request
49 // are run on the origin thread.
51 // Thread safety: This class is not threadsafe, and must only be called
52 // from one thread!
54 // The HostResolverImpl enforces limits on the maximum number of concurrent
55 // threads using PrioritizedDispatcher::Limits.
57 // Jobs are ordered in the queue based on their priority and order of arrival.
58 class NET_EXPORT HostResolverImpl
59 : public HostResolver,
60 NON_EXPORTED_BASE(public base::NonThreadSafe),
61 public NetworkChangeNotifier::IPAddressObserver,
62 public NetworkChangeNotifier::DNSObserver {
63 public:
64 // Parameters for ProcTask which resolves hostnames using HostResolveProc.
66 // |resolver_proc| is used to perform the actual resolves; it must be
67 // thread-safe since it is run from multiple worker threads. If
68 // |resolver_proc| is NULL then the default host resolver procedure is
69 // used (which is SystemHostResolverProc except if overridden).
71 // For each attempt, we could start another attempt if host is not resolved
72 // within |unresponsive_delay| time. We keep attempting to resolve the host
73 // for |max_retry_attempts|. For every retry attempt, we grow the
74 // |unresponsive_delay| by the |retry_factor| amount (that is retry interval
75 // is multiplied by the retry factor each time). Once we have retried
76 // |max_retry_attempts|, we give up on additional attempts.
78 struct NET_EXPORT_PRIVATE ProcTaskParams {
79 // Sets up defaults.
80 ProcTaskParams(HostResolverProc* resolver_proc, size_t max_retry_attempts);
82 ~ProcTaskParams();
84 // The procedure to use for resolving host names. This will be NULL, except
85 // in the case of unit-tests which inject custom host resolving behaviors.
86 scoped_refptr<HostResolverProc> resolver_proc;
88 // Maximum number retry attempts to resolve the hostname.
89 // Pass HostResolver::kDefaultRetryAttempts to choose a default value.
90 size_t max_retry_attempts;
92 // This is the limit after which we make another attempt to resolve the host
93 // if the worker thread has not responded yet.
94 base::TimeDelta unresponsive_delay;
96 // Factor to grow |unresponsive_delay| when we re-re-try.
97 uint32 retry_factor;
100 // Creates a HostResolver as specified by |options|.
102 // If Options.enable_caching is true, a cache is created using
103 // HostCache::CreateDefaultCache(). Otherwise no cache is used.
105 // Options.GetDispatcherLimits() determines the maximum number of jobs that
106 // the resolver will run at once. This upper-bounds the total number of
107 // outstanding DNS transactions (not counting retransmissions and retries).
109 // |net_log| must remain valid for the life of the HostResolverImpl.
110 HostResolverImpl(const Options& options, NetLog* net_log);
112 // If any completion callbacks are pending when the resolver is destroyed,
113 // the host resolutions are cancelled, and the completion callbacks will not
114 // be called.
115 ~HostResolverImpl() override;
117 // Configures maximum number of Jobs in the queue. Exposed for testing.
118 // Only allowed when the queue is empty.
119 void SetMaxQueuedJobs(size_t value);
121 // Set the DnsClient to be used for resolution. In case of failure, the
122 // HostResolverProc from ProcTaskParams will be queried. If the DnsClient is
123 // not pre-configured with a valid DnsConfig, a new config is fetched from
124 // NetworkChangeNotifier.
125 void SetDnsClient(scoped_ptr<DnsClient> dns_client);
127 // HostResolver methods:
128 int Resolve(const RequestInfo& info,
129 RequestPriority priority,
130 AddressList* addresses,
131 const CompletionCallback& callback,
132 RequestHandle* out_req,
133 const BoundNetLog& source_net_log) override;
134 int ResolveFromCache(const RequestInfo& info,
135 AddressList* addresses,
136 const BoundNetLog& source_net_log) override;
137 void CancelRequest(RequestHandle req) override;
138 void SetDnsClientEnabled(bool enabled) override;
139 HostCache* GetHostCache() override;
140 base::Value* GetDnsConfigAsValue() const override;
142 void set_proc_params_for_test(const ProcTaskParams& proc_params) {
143 proc_params_ = proc_params;
146 private:
147 friend class HostResolverImplTest;
148 class Job;
149 class ProcTask;
150 class LoopbackProbeJob;
151 class DnsTask;
152 class Request;
153 typedef HostCache::Key Key;
154 typedef std::map<Key, Job*> JobMap;
155 typedef ScopedVector<Request> RequestsList;
157 // Number of consecutive failures of DnsTask (with successful fallback to
158 // ProcTask) before the DnsClient is disabled until the next DNS change.
159 static const unsigned kMaximumDnsFailures;
161 // Helper used by |Resolve()| and |ResolveFromCache()|. Performs IP
162 // literal, cache and HOSTS lookup (if enabled), returns OK if successful,
163 // ERR_NAME_NOT_RESOLVED if either hostname is invalid or IP literal is
164 // incompatible, ERR_DNS_CACHE_MISS if entry was not found in cache and HOSTS.
165 int ResolveHelper(const Key& key,
166 const RequestInfo& info,
167 const IPAddressNumber* ip_address,
168 AddressList* addresses,
169 const BoundNetLog& request_net_log);
171 // Tries to resolve |key| as an IP, returns true and sets |net_error| if
172 // succeeds, returns false otherwise.
173 bool ResolveAsIP(const Key& key,
174 const RequestInfo& info,
175 const IPAddressNumber* ip_address,
176 int* net_error,
177 AddressList* addresses);
179 // If |key| is not found in cache returns false, otherwise returns
180 // true, sets |net_error| to the cached error code and fills |addresses|
181 // if it is a positive entry.
182 bool ServeFromCache(const Key& key,
183 const RequestInfo& info,
184 int* net_error,
185 AddressList* addresses);
187 // If we have a DnsClient with a valid DnsConfig, and |key| is found in the
188 // HOSTS file, returns true and fills |addresses|. Otherwise returns false.
189 bool ServeFromHosts(const Key& key,
190 const RequestInfo& info,
191 AddressList* addresses);
193 // Callback from HaveOnlyLoopbackAddresses probe.
194 void SetHaveOnlyLoopbackAddresses(bool result);
196 // Returns the (hostname, address_family) key to use for |info|, choosing an
197 // "effective" address family by inheriting the resolver's default address
198 // family when the request leaves it unspecified.
199 Key GetEffectiveKeyForRequest(const RequestInfo& info,
200 const IPAddressNumber* ip_number,
201 const BoundNetLog& net_log);
203 // Probes IPv6 support and returns true if IPv6 support is enabled.
204 // Results are cached, i.e. when called repeatedly this method returns result
205 // from the first probe for some time before probing again.
206 virtual bool IsIPv6Reachable(const BoundNetLog& net_log);
208 // Records the result in cache if cache is present.
209 void CacheResult(const Key& key,
210 const HostCache::Entry& entry,
211 base::TimeDelta ttl);
213 // Removes |job| from |jobs_|, only if it exists.
214 void RemoveJob(Job* job);
216 // Aborts all in progress jobs with ERR_NETWORK_CHANGED and notifies their
217 // requests. Might start new jobs.
218 void AbortAllInProgressJobs();
220 // Aborts all in progress DnsTasks. In-progress jobs will fall back to
221 // ProcTasks. Might start new jobs, if any jobs were taking up two dispatcher
222 // slots.
223 void AbortDnsTasks();
225 // Attempts to serve each Job in |jobs_| from the HOSTS file if we have
226 // a DnsClient with a valid DnsConfig.
227 void TryServingAllJobsFromHosts();
229 // NetworkChangeNotifier::IPAddressObserver:
230 void OnIPAddressChanged() override;
232 // NetworkChangeNotifier::DNSObserver:
233 void OnDNSChanged() override;
234 void OnInitialDNSConfigRead() override;
236 void UpdateDNSConfig(bool config_changed);
238 // True if have a DnsClient with a valid DnsConfig.
239 bool HaveDnsConfig() const;
241 // Called when a host name is successfully resolved and DnsTask was run on it
242 // and resulted in |net_error|.
243 void OnDnsTaskResolve(int net_error);
245 // Allows the tests to catch slots leaking out of the dispatcher. One
246 // HostResolverImpl::Job could occupy multiple PrioritizedDispatcher job
247 // slots.
248 size_t num_running_dispatcher_jobs_for_tests() const {
249 return dispatcher_->num_running_jobs();
252 // Cache of host resolution results.
253 scoped_ptr<HostCache> cache_;
255 // Map from HostCache::Key to a Job.
256 JobMap jobs_;
258 // Starts Jobs according to their priority and the configured limits.
259 scoped_ptr<PrioritizedDispatcher> dispatcher_;
261 // Limit on the maximum number of jobs queued in |dispatcher_|.
262 size_t max_queued_jobs_;
264 // Parameters for ProcTask.
265 ProcTaskParams proc_params_;
267 NetLog* net_log_;
269 // If present, used by DnsTask and ServeFromHosts to resolve requests.
270 scoped_ptr<DnsClient> dns_client_;
272 // True if received valid config from |dns_config_service_|. Temporary, used
273 // to measure performance of DnsConfigService: http://crbug.com/125599
274 bool received_dns_config_;
276 // Number of consecutive failures of DnsTask, counted when fallback succeeds.
277 unsigned num_dns_failures_;
279 // True if DnsConfigService detected that system configuration depends on
280 // local IPv6 connectivity. Disables probing.
281 bool use_local_ipv6_;
283 base::TimeTicks last_ipv6_probe_time_;
284 bool last_ipv6_probe_result_;
286 // True iff ProcTask has successfully resolved a hostname known to have IPv6
287 // addresses using ADDRESS_FAMILY_UNSPECIFIED. Reset on IP address change.
288 bool resolved_known_ipv6_hostname_;
290 // Any resolver flags that should be added to a request by default.
291 HostResolverFlags additional_resolver_flags_;
293 // Allow fallback to ProcTask if DnsTask fails.
294 bool fallback_to_proctask_;
296 base::WeakPtrFactory<HostResolverImpl> weak_ptr_factory_;
298 base::WeakPtrFactory<HostResolverImpl> probe_weak_ptr_factory_;
300 DISALLOW_COPY_AND_ASSIGN(HostResolverImpl);
303 } // namespace net
305 #endif // NET_DNS_HOST_RESOLVER_IMPL_H_