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_
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/capturing_net_log.h"
18 #include "net/base/net_export.h"
19 #include "net/base/network_change_notifier.h"
20 #include "net/base/prioritized_dispatcher.h"
21 #include "net/dns/host_cache.h"
22 #include "net/dns/host_resolver.h"
23 #include "net/dns/host_resolver_proc.h"
31 // For each hostname that is requested, HostResolver creates a
32 // HostResolverImpl::Job. When this job gets dispatched it creates a ProcTask
33 // which runs the given HostResolverProc on a WorkerPool thread. If requests for
34 // that same host are made during the job's lifetime, they are attached to the
35 // existing job rather than creating a new one. This avoids doing parallel
36 // resolves for the same host.
38 // The way these classes fit together is illustrated by:
41 // +----------- HostResolverImpl -------------+
44 // (for host1, fam1) (for host2, fam2) (for hostx, famx)
46 // Request ... Request Request ... Request Request ... Request
47 // (port1) (port2) (port3) (port4) (port5) (portX)
49 // When a HostResolverImpl::Job finishes, the callbacks of each waiting request
50 // are run on the origin thread.
52 // Thread safety: This class is not threadsafe, and must only be called
55 // The HostResolverImpl enforces limits on the maximum number of concurrent
56 // threads using PrioritizedDispatcher::Limits.
58 // Jobs are ordered in the queue based on their priority and order of arrival.
59 class NET_EXPORT HostResolverImpl
60 : public HostResolver
,
61 NON_EXPORTED_BASE(public base::NonThreadSafe
),
62 public NetworkChangeNotifier::IPAddressObserver
,
63 public NetworkChangeNotifier::DNSObserver
{
65 // Parameters for ProcTask which resolves hostnames using HostResolveProc.
67 // |resolver_proc| is used to perform the actual resolves; it must be
68 // thread-safe since it is run from multiple worker threads. If
69 // |resolver_proc| is NULL then the default host resolver procedure is
70 // used (which is SystemHostResolverProc except if overridden).
72 // For each attempt, we could start another attempt if host is not resolved
73 // within |unresponsive_delay| time. We keep attempting to resolve the host
74 // for |max_retry_attempts|. For every retry attempt, we grow the
75 // |unresponsive_delay| by the |retry_factor| amount (that is retry interval
76 // is multiplied by the retry factor each time). Once we have retried
77 // |max_retry_attempts|, we give up on additional attempts.
79 struct NET_EXPORT_PRIVATE ProcTaskParams
{
81 ProcTaskParams(HostResolverProc
* resolver_proc
, size_t max_retry_attempts
);
85 // The procedure to use for resolving host names. This will be NULL, except
86 // in the case of unit-tests which inject custom host resolving behaviors.
87 scoped_refptr
<HostResolverProc
> resolver_proc
;
89 // Maximum number retry attempts to resolve the hostname.
90 // Pass HostResolver::kDefaultRetryAttempts to choose a default value.
91 size_t max_retry_attempts
;
93 // This is the limit after which we make another attempt to resolve the host
94 // if the worker thread has not responded yet.
95 base::TimeDelta unresponsive_delay
;
97 // Factor to grow |unresponsive_delay| when we re-re-try.
101 // Creates a HostResolver that first uses the local cache |cache|, and then
102 // falls back to |proc_params.resolver_proc|.
104 // If |cache| is NULL, then no caching is used. Otherwise we take
105 // ownership of the |cache| pointer, and will free it during destruction.
107 // |job_limits| specifies the maximum number of jobs that the resolver will
108 // run at once. This upper-bounds the total number of outstanding
109 // DNS transactions (not counting retransmissions and retries).
111 // |net_log| must remain valid for the life of the HostResolverImpl.
112 HostResolverImpl(scoped_ptr
<HostCache
> cache
,
113 const PrioritizedDispatcher::Limits
& job_limits
,
114 const ProcTaskParams
& proc_params
,
117 // If any completion callbacks are pending when the resolver is destroyed,
118 // the host resolutions are cancelled, and the completion callbacks will not
120 virtual ~HostResolverImpl();
122 // Configures maximum number of Jobs in the queue. Exposed for testing.
123 // Only allowed when the queue is empty.
124 void SetMaxQueuedJobs(size_t value
);
126 // Set the DnsClient to be used for resolution. In case of failure, the
127 // HostResolverProc from ProcTaskParams will be queried. If the DnsClient is
128 // not pre-configured with a valid DnsConfig, a new config is fetched from
129 // NetworkChangeNotifier.
130 void SetDnsClient(scoped_ptr
<DnsClient
> dns_client
);
132 // HostResolver methods:
133 virtual int Resolve(const RequestInfo
& info
,
134 RequestPriority priority
,
135 AddressList
* addresses
,
136 const CompletionCallback
& callback
,
137 RequestHandle
* out_req
,
138 const BoundNetLog
& source_net_log
) OVERRIDE
;
139 virtual int ResolveFromCache(const RequestInfo
& info
,
140 AddressList
* addresses
,
141 const BoundNetLog
& source_net_log
) OVERRIDE
;
142 virtual void CancelRequest(RequestHandle req
) OVERRIDE
;
143 virtual void SetDefaultAddressFamily(AddressFamily address_family
) OVERRIDE
;
144 virtual AddressFamily
GetDefaultAddressFamily() const OVERRIDE
;
145 virtual void SetDnsClientEnabled(bool enabled
) OVERRIDE
;
146 virtual HostCache
* GetHostCache() OVERRIDE
;
147 virtual base::Value
* GetDnsConfigAsValue() const OVERRIDE
;
150 friend class HostResolverImplTest
;
153 class LoopbackProbeJob
;
156 typedef HostCache::Key Key
;
157 typedef std::map
<Key
, Job
*> JobMap
;
158 typedef ScopedVector
<Request
> RequestsList
;
160 // Number of consecutive failures of DnsTask (with successful fallback to
161 // ProcTask) before the DnsClient is disabled until the next DNS change.
162 static const unsigned kMaximumDnsFailures
;
164 // Helper used by |Resolve()| and |ResolveFromCache()|. Performs IP
165 // literal, cache and HOSTS lookup (if enabled), returns OK if successful,
166 // ERR_NAME_NOT_RESOLVED if either hostname is invalid or IP literal is
167 // incompatible, ERR_DNS_CACHE_MISS if entry was not found in cache and HOSTS.
168 int ResolveHelper(const Key
& key
,
169 const RequestInfo
& info
,
170 AddressList
* addresses
,
171 const BoundNetLog
& request_net_log
);
173 // Tries to resolve |key| as an IP, returns true and sets |net_error| if
174 // succeeds, returns false otherwise.
175 bool ResolveAsIP(const Key
& key
,
176 const RequestInfo
& info
,
178 AddressList
* addresses
);
180 // If |key| is not found in cache returns false, otherwise returns
181 // true, sets |net_error| to the cached error code and fills |addresses|
182 // if it is a positive entry.
183 bool ServeFromCache(const Key
& key
,
184 const RequestInfo
& info
,
186 AddressList
* addresses
);
188 // If we have a DnsClient with a valid DnsConfig, and |key| is found in the
189 // HOSTS file, returns true and fills |addresses|. Otherwise returns false.
190 bool ServeFromHosts(const Key
& key
,
191 const RequestInfo
& info
,
192 AddressList
* addresses
);
194 // Callback from HaveOnlyLoopbackAddresses probe.
195 void SetHaveOnlyLoopbackAddresses(bool result
);
197 // Returns the (hostname, address_family) key to use for |info|, choosing an
198 // "effective" address family by inheriting the resolver's default address
199 // family when the request leaves it unspecified.
200 Key
GetEffectiveKeyForRequest(const RequestInfo
& info
,
201 const BoundNetLog
& net_log
) const;
203 // Records the result in cache if cache is present.
204 void CacheResult(const Key
& key
,
205 const HostCache::Entry
& entry
,
206 base::TimeDelta ttl
);
208 // Removes |job| from |jobs_|, only if it exists.
209 void RemoveJob(Job
* job
);
211 // Aborts all in progress jobs with ERR_NETWORK_CHANGED and notifies their
212 // requests. Might start new jobs.
213 void AbortAllInProgressJobs();
215 // Aborts all in progress DnsTasks. In-progress jobs will fall back to
216 // ProcTasks. Might start new jobs, if any jobs were taking up two dispatcher
218 void AbortDnsTasks();
220 // Attempts to serve each Job in |jobs_| from the HOSTS file if we have
221 // a DnsClient with a valid DnsConfig.
222 void TryServingAllJobsFromHosts();
224 // NetworkChangeNotifier::IPAddressObserver:
225 virtual void OnIPAddressChanged() OVERRIDE
;
227 // NetworkChangeNotifier::DNSObserver:
228 virtual void OnDNSChanged() OVERRIDE
;
230 // True if have a DnsClient with a valid DnsConfig.
231 bool HaveDnsConfig() const;
233 // Called when a host name is successfully resolved and DnsTask was run on it
234 // and resulted in |net_error|.
235 void OnDnsTaskResolve(int net_error
);
237 // Allows the tests to catch slots leaking out of the dispatcher. One
238 // HostResolverImpl::Job could occupy multiple PrioritizedDispatcher job
240 size_t num_running_dispatcher_jobs_for_tests() const {
241 return dispatcher_
.num_running_jobs();
244 // Cache of host resolution results.
245 scoped_ptr
<HostCache
> cache_
;
247 // Map from HostCache::Key to a Job.
250 // Starts Jobs according to their priority and the configured limits.
251 PrioritizedDispatcher dispatcher_
;
253 // Limit on the maximum number of jobs queued in |dispatcher_|.
254 size_t max_queued_jobs_
;
256 // Parameters for ProcTask.
257 ProcTaskParams proc_params_
;
261 // Address family to use when the request doesn't specify one.
262 AddressFamily default_address_family_
;
264 base::WeakPtrFactory
<HostResolverImpl
> weak_ptr_factory_
;
266 base::WeakPtrFactory
<HostResolverImpl
> probe_weak_ptr_factory_
;
268 // If present, used by DnsTask and ServeFromHosts to resolve requests.
269 scoped_ptr
<DnsClient
> dns_client_
;
271 // True if received valid config from |dns_config_service_|. Temporary, used
272 // to measure performance of DnsConfigService: http://crbug.com/125599
273 bool received_dns_config_
;
275 // Number of consecutive failures of DnsTask, counted when fallback succeeds.
276 unsigned num_dns_failures_
;
278 // True if probing is done for each Request to set address family. When false,
279 // explicit setting in |default_address_family_| is used.
280 bool probe_ipv6_support_
;
282 // True if DnsConfigService detected that system configuration depends on
283 // local IPv6 connectivity. Disables probing.
284 bool use_local_ipv6_
;
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 DISALLOW_COPY_AND_ASSIGN(HostResolverImpl
);
301 #endif // NET_DNS_HOST_RESOLVER_IMPL_H_