Cleanup setting of 'sysroot' in common.gypi
[chromium-blink-merge.git] / net / dns / host_resolver_impl.h
blobe360dd57333a891506a8c24b656e3ed0e367a379
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/ip_address_number.h"
18 #include "net/base/net_export.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
165 // HOSTS and is not localhost.
166 int ResolveHelper(const Key& key,
167 const RequestInfo& info,
168 const IPAddressNumber* ip_address,
169 AddressList* addresses,
170 const BoundNetLog& request_net_log);
172 // Tries to resolve |key| as an IP, returns true and sets |net_error| if
173 // succeeds, returns false otherwise.
174 bool ResolveAsIP(const Key& key,
175 const RequestInfo& info,
176 const IPAddressNumber* ip_address,
177 int* net_error,
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,
185 int* net_error,
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 // If |key| is for a localhost name (RFC 6761), returns true and fills
195 // |addresses| with the loopback IP. Otherwise returns false.
196 bool ServeLocalhost(const Key& key,
197 const RequestInfo& info,
198 AddressList* addresses);
200 // Callback from HaveOnlyLoopbackAddresses probe.
201 void SetHaveOnlyLoopbackAddresses(bool result);
203 // Returns the (hostname, address_family) key to use for |info|, choosing an
204 // "effective" address family by inheriting the resolver's default address
205 // family when the request leaves it unspecified.
206 Key GetEffectiveKeyForRequest(const RequestInfo& info,
207 const IPAddressNumber* ip_number,
208 const BoundNetLog& net_log);
210 // Probes IPv6 support and returns true if IPv6 support is enabled.
211 // Results are cached, i.e. when called repeatedly this method returns result
212 // from the first probe for some time before probing again.
213 virtual bool IsIPv6Reachable(const BoundNetLog& net_log);
215 // Records the result in cache if cache is present.
216 void CacheResult(const Key& key,
217 const HostCache::Entry& entry,
218 base::TimeDelta ttl);
220 // Removes |job| from |jobs_|, only if it exists.
221 void RemoveJob(Job* job);
223 // Aborts all in progress jobs with ERR_NETWORK_CHANGED and notifies their
224 // requests. Might start new jobs.
225 void AbortAllInProgressJobs();
227 // Aborts all in progress DnsTasks. In-progress jobs will fall back to
228 // ProcTasks. Might start new jobs, if any jobs were taking up two dispatcher
229 // slots.
230 void AbortDnsTasks();
232 // Attempts to serve each Job in |jobs_| from the HOSTS file if we have
233 // a DnsClient with a valid DnsConfig.
234 void TryServingAllJobsFromHosts();
236 // NetworkChangeNotifier::IPAddressObserver:
237 void OnIPAddressChanged() override;
239 // NetworkChangeNotifier::DNSObserver:
240 void OnDNSChanged() override;
241 void OnInitialDNSConfigRead() override;
243 void UpdateDNSConfig(bool config_changed);
245 // True if have a DnsClient with a valid DnsConfig.
246 bool HaveDnsConfig() const;
248 // Called when a host name is successfully resolved and DnsTask was run on it
249 // and resulted in |net_error|.
250 void OnDnsTaskResolve(int net_error);
252 // Allows the tests to catch slots leaking out of the dispatcher. One
253 // HostResolverImpl::Job could occupy multiple PrioritizedDispatcher job
254 // slots.
255 size_t num_running_dispatcher_jobs_for_tests() const {
256 return dispatcher_->num_running_jobs();
259 // Cache of host resolution results.
260 scoped_ptr<HostCache> cache_;
262 // Map from HostCache::Key to a Job.
263 JobMap jobs_;
265 // Starts Jobs according to their priority and the configured limits.
266 scoped_ptr<PrioritizedDispatcher> dispatcher_;
268 // Limit on the maximum number of jobs queued in |dispatcher_|.
269 size_t max_queued_jobs_;
271 // Parameters for ProcTask.
272 ProcTaskParams proc_params_;
274 NetLog* net_log_;
276 // If present, used by DnsTask and ServeFromHosts to resolve requests.
277 scoped_ptr<DnsClient> dns_client_;
279 // True if received valid config from |dns_config_service_|. Temporary, used
280 // to measure performance of DnsConfigService: http://crbug.com/125599
281 bool received_dns_config_;
283 // Number of consecutive failures of DnsTask, counted when fallback succeeds.
284 unsigned num_dns_failures_;
286 // True if DnsConfigService detected that system configuration depends on
287 // local IPv6 connectivity. Disables probing.
288 bool use_local_ipv6_;
290 base::TimeTicks last_ipv6_probe_time_;
291 bool last_ipv6_probe_result_;
293 // True iff ProcTask has successfully resolved a hostname known to have IPv6
294 // addresses using ADDRESS_FAMILY_UNSPECIFIED. Reset on IP address change.
295 bool resolved_known_ipv6_hostname_;
297 // Any resolver flags that should be added to a request by default.
298 HostResolverFlags additional_resolver_flags_;
300 // Allow fallback to ProcTask if DnsTask fails.
301 bool fallback_to_proctask_;
303 base::WeakPtrFactory<HostResolverImpl> weak_ptr_factory_;
305 base::WeakPtrFactory<HostResolverImpl> probe_weak_ptr_factory_;
307 DISALLOW_COPY_AND_ASSIGN(HostResolverImpl);
310 } // namespace net
312 #endif // NET_DNS_HOST_RESOLVER_IMPL_H_