move SK_DISABLE_DITHER_32BIT_GRADIENT from SkUserConfig.h to skia.gyp, so we can...
[chromium-blink-merge.git] / net / base / host_resolver_impl.h
blob8d28ab37939e021fa277818a9b558fa3fffb1e59
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_BASE_HOST_RESOLVER_IMPL_H_
6 #define NET_BASE_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.h"
17 #include "net/base/capturing_net_log.h"
18 #include "net/base/host_cache.h"
19 #include "net/base/host_resolver.h"
20 #include "net/base/host_resolver_proc.h"
21 #include "net/base/net_export.h"
22 #include "net/base/network_change_notifier.h"
23 #include "net/base/prioritized_dispatcher.h"
25 namespace net {
27 class BoundNetLog;
28 class DnsClient;
29 class NetLog;
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 -------------+
42 // | | |
43 // Job Job Job
44 // (for host1, fam1) (for host2, fam2) (for hostx, famx)
45 // / | | / | | / | |
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
53 // from one thread!
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 {
64 public:
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 {
80 // Sets up defaults.
81 ProcTaskParams(HostResolverProc* resolver_proc, size_t max_retry_attempts);
83 ~ProcTaskParams();
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.
98 uint32 retry_factor;
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,
115 NetLog* net_log);
117 // If any completion callbacks are pending when the resolver is destroyed,
118 // the host resolutions are cancelled, and the completion callbacks will not
119 // be called.
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 AddressList* addresses,
135 const CompletionCallback& callback,
136 RequestHandle* out_req,
137 const BoundNetLog& source_net_log) OVERRIDE;
138 virtual int ResolveFromCache(const RequestInfo& info,
139 AddressList* addresses,
140 const BoundNetLog& source_net_log) OVERRIDE;
141 virtual void CancelRequest(RequestHandle req) OVERRIDE;
142 virtual void SetDefaultAddressFamily(AddressFamily address_family) OVERRIDE;
143 virtual AddressFamily GetDefaultAddressFamily() const OVERRIDE;
144 virtual void ProbeIPv6Support() OVERRIDE;
145 virtual void SetDnsClientEnabled(bool enabled) OVERRIDE;
146 virtual HostCache* GetHostCache() OVERRIDE;
147 virtual base::Value* GetDnsConfigAsValue() const OVERRIDE;
149 private:
150 friend class HostResolverImplTest;
151 class Job;
152 class ProcTask;
153 class IPv6ProbeJob;
154 class LoopbackProbeJob;
155 class DnsTask;
156 class Request;
157 typedef HostCache::Key Key;
158 typedef std::map<Key, Job*> JobMap;
159 typedef ScopedVector<Request> RequestsList;
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 AddressList* addresses,
168 const BoundNetLog& request_net_log);
170 // Tries to resolve |key| as an IP, returns true and sets |net_error| if
171 // succeeds, returns false otherwise.
172 bool ResolveAsIP(const Key& key,
173 const RequestInfo& info,
174 int* net_error,
175 AddressList* addresses);
177 // If |key| is not found in cache returns false, otherwise returns
178 // true, sets |net_error| to the cached error code and fills |addresses|
179 // if it is a positive entry.
180 bool ServeFromCache(const Key& key,
181 const RequestInfo& info,
182 int* net_error,
183 AddressList* addresses);
185 // If we have a DnsClient with a valid DnsConfig, and |key| is found in the
186 // HOSTS file, returns true and fills |addresses|. Otherwise returns false.
187 bool ServeFromHosts(const Key& key,
188 const RequestInfo& info,
189 AddressList* addresses);
191 // Callback from IPv6 probe activity.
192 void IPv6ProbeSetDefaultAddressFamily(AddressFamily address_family);
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) const;
202 // Records the result in cache if cache is present.
203 void CacheResult(const Key& key,
204 const HostCache::Entry& entry,
205 base::TimeDelta ttl);
207 // Removes |job| from |jobs_|, only if it exists.
208 void RemoveJob(Job* job);
210 // Aborts all in progress jobs and notifies their requests.
211 // Might start new jobs.
212 void AbortAllInProgressJobs();
214 // Attempts to serve each Job in |jobs_| from the HOSTS file if we have
215 // a DnsClient with a valid DnsConfig.
216 void TryServingAllJobsFromHosts();
218 // NetworkChangeNotifier::IPAddressObserver:
219 virtual void OnIPAddressChanged() OVERRIDE;
221 // NetworkChangeNotifier::DNSObserver:
222 virtual void OnDNSChanged() OVERRIDE;
224 // True if have a DnsClient with a valid DnsConfig.
225 bool HaveDnsConfig() const;
227 // Called when a host name is successfully resolved and DnsTask was run on it.
228 // |success| is false iff the DnsTask failed to resolve it, but getaddrinfo
229 // succeeded.
230 void OnDnsTaskResolve(bool success);
232 // Allows the tests to catch slots leaking out of the dispatcher.
233 size_t num_running_jobs_for_tests() const {
234 return dispatcher_.num_running_jobs();
237 // Cache of host resolution results.
238 scoped_ptr<HostCache> cache_;
240 // Map from HostCache::Key to a Job.
241 JobMap jobs_;
243 // Starts Jobs according to their priority and the configured limits.
244 PrioritizedDispatcher dispatcher_;
246 // Limit on the maximum number of jobs queued in |dispatcher_|.
247 size_t max_queued_jobs_;
249 // Parameters for ProcTask.
250 ProcTaskParams proc_params_;
252 // Address family to use when the request doesn't specify one.
253 AddressFamily default_address_family_;
255 base::WeakPtrFactory<HostResolverImpl> weak_ptr_factory_;
257 base::WeakPtrFactory<HostResolverImpl> probe_weak_ptr_factory_;
259 // If present, used by DnsTask and ServeFromHosts to resolve requests.
260 scoped_ptr<DnsClient> dns_client_;
262 // True if received valid config from |dns_config_service_|. Temporary, used
263 // to measure performance of DnsConfigService: http://crbug.com/125599
264 bool received_dns_config_;
266 // Number of consecutive failures of DnsTask, counted when fallback succeeds.
267 unsigned num_dns_failures_;
269 // Indicate if probing is done after each network change event to set address
270 // family. When false, explicit setting of address family is used and results
271 // of the IPv6 probe job are ignored.
272 bool ipv6_probe_monitoring_;
274 // Any resolver flags that should be added to a request by default.
275 HostResolverFlags additional_resolver_flags_;
277 NetLog* net_log_;
279 DISALLOW_COPY_AND_ASSIGN(HostResolverImpl);
282 } // namespace net
284 #endif // NET_BASE_HOST_RESOLVER_IMPL_H_