Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / net / proxy / proxy_service.h
blobe0f807777d3fdb81a61d2d37282b8fafa51306b0
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_PROXY_PROXY_SERVICE_H_
6 #define NET_PROXY_PROXY_SERVICE_H_
8 #include <string>
9 #include <vector>
11 #include "base/gtest_prod_util.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/synchronization/waitable_event.h"
15 #include "base/threading/non_thread_safe.h"
16 #include "net/base/completion_callback.h"
17 #include "net/base/load_states.h"
18 #include "net/base/net_export.h"
19 #include "net/base/network_change_notifier.h"
20 #include "net/log/net_log.h"
21 #include "net/proxy/proxy_config_service.h"
22 #include "net/proxy/proxy_info.h"
23 #include "net/proxy/proxy_server.h"
25 class GURL;
27 namespace base {
28 class SingleThreadTaskRunner;
29 class TimeDelta;
30 } // namespace base
32 namespace net {
34 class DhcpProxyScriptFetcher;
35 class HostResolver;
36 class NetworkDelegate;
37 class ProxyResolver;
38 class ProxyResolverFactory;
39 class ProxyResolverScriptData;
40 class ProxyScriptDecider;
41 class ProxyScriptFetcher;
43 // This class can be used to resolve the proxy server to use when loading a
44 // HTTP(S) URL. It uses the given ProxyResolver to handle the actual proxy
45 // resolution. See ProxyResolverV8 for example.
46 class NET_EXPORT ProxyService : public NetworkChangeNotifier::IPAddressObserver,
47 public NetworkChangeNotifier::DNSObserver,
48 public ProxyConfigService::Observer,
49 NON_EXPORTED_BASE(public base::NonThreadSafe) {
50 public:
51 static const size_t kDefaultNumPacThreads = 4;
53 // This interface defines the set of policies for when to poll the PAC
54 // script for changes.
56 // The polling policy decides what the next poll delay should be in
57 // milliseconds. It also decides how to wait for this delay -- either
58 // by starting a timer to do the poll at exactly |next_delay_ms|
59 // (MODE_USE_TIMER) or by waiting for the first network request issued after
60 // |next_delay_ms| (MODE_START_AFTER_ACTIVITY).
62 // The timer method is more precise and guarantees that polling happens when
63 // it was requested. However it has the disadvantage of causing spurious CPU
64 // and network activity. It is a reasonable choice to use for short poll
65 // intervals which only happen a couple times.
67 // However for repeated timers this will prevent the browser from going
68 // idle. MODE_START_AFTER_ACTIVITY solves this problem by only polling in
69 // direct response to network activity. The drawback to
70 // MODE_START_AFTER_ACTIVITY is since the poll is initiated only after the
71 // request is received, the first couple requests initiated after a long
72 // period of inactivity will likely see a stale version of the PAC script
73 // until the background polling gets a chance to update things.
74 class NET_EXPORT_PRIVATE PacPollPolicy {
75 public:
76 enum Mode {
77 MODE_USE_TIMER,
78 MODE_START_AFTER_ACTIVITY,
81 virtual ~PacPollPolicy() {}
83 // Decides the next poll delay. |current_delay| is the delay used
84 // by the preceding poll, or a negative TimeDelta value if determining
85 // the delay for the initial poll. |initial_error| is the network error
86 // code that the last PAC fetch (or WPAD initialization) failed with,
87 // or OK if it completed successfully. Implementations must set
88 // |next_delay| to a non-negative value.
89 virtual Mode GetNextDelay(int initial_error,
90 base::TimeDelta current_delay,
91 base::TimeDelta* next_delay) const = 0;
94 // The instance takes ownership of |config_service| and |resolver_factory|.
95 // |net_log| is a possibly NULL destination to send log events to. It must
96 // remain alive for the lifetime of this ProxyService.
97 ProxyService(ProxyConfigService* config_service,
98 scoped_ptr<ProxyResolverFactory> resolver_factory,
99 NetLog* net_log);
101 ~ProxyService() override;
103 // Used internally to handle PAC queries.
104 // TODO(eroman): consider naming this simply "Request".
105 class PacRequest;
107 // Returns ERR_IO_PENDING if the proxy information could not be provided
108 // synchronously, to indicate that the result will be available when the
109 // callback is run. The callback is run on the thread that calls
110 // ResolveProxy.
112 // The caller is responsible for ensuring that |results| and |callback|
113 // remain valid until the callback is run or until |pac_request| is cancelled
114 // via CancelPacRequest. |pac_request| is only valid while the completion
115 // callback is still pending. NULL can be passed for |pac_request| if
116 // the caller will not need to cancel the request.
118 // We use the three possible proxy access types in the following order,
119 // doing fallback if one doesn't work. See "pac_script_decider.h"
120 // for the specifics.
121 // 1. WPAD auto-detection
122 // 2. PAC URL
123 // 3. named proxy
125 // Profiling information for the request is saved to |net_log| if non-NULL.
126 int ResolveProxy(const GURL& url,
127 int load_flags,
128 ProxyInfo* results,
129 const CompletionCallback& callback,
130 PacRequest** pac_request,
131 NetworkDelegate* network_delegate,
132 const BoundNetLog& net_log);
134 // Returns true if the proxy information could be determined without spawning
135 // an asynchronous task. Otherwise, |result| is unmodified.
136 bool TryResolveProxySynchronously(const GURL& raw_url,
137 int load_flags,
138 ProxyInfo* result,
139 NetworkDelegate* network_delegate,
140 const BoundNetLog& net_log);
142 // This method is called after a failure to connect or resolve a host name.
143 // It gives the proxy service an opportunity to reconsider the proxy to use.
144 // The |results| parameter contains the results returned by an earlier call
145 // to ResolveProxy. The |net_error| parameter contains the network error
146 // code associated with the failure. See "net/base/net_error_list.h" for a
147 // list of possible values. The semantics of this call are otherwise
148 // similar to ResolveProxy.
150 // NULL can be passed for |pac_request| if the caller will not need to
151 // cancel the request.
153 // Returns ERR_FAILED if there is not another proxy config to try.
155 // Profiling information for the request is saved to |net_log| if non-NULL.
156 int ReconsiderProxyAfterError(const GURL& url,
157 int load_flags,
158 int net_error,
159 ProxyInfo* results,
160 const CompletionCallback& callback,
161 PacRequest** pac_request,
162 NetworkDelegate* network_delegate,
163 const BoundNetLog& net_log);
165 // Explicitly trigger proxy fallback for the given |results| by updating our
166 // list of bad proxies to include the first entry of |results|, and,
167 // additional bad proxies (can be none). Will retry after |retry_delay| if
168 // positive, and will use the default proxy retry duration otherwise. Proxies
169 // marked as bad will not be retried until |retry_delay| has passed. Returns
170 // true if there will be at least one proxy remaining in the list after
171 // fallback and false otherwise. This method should be used to add proxies to
172 // the bad proxy list only for reasons other than a network error. If a proxy
173 // needs to be added to the bad proxy list because a network error was
174 // encountered when trying to connect to it, use |ReconsiderProxyAfterError|.
175 bool MarkProxiesAsBadUntil(
176 const ProxyInfo& results,
177 base::TimeDelta retry_delay,
178 const std::vector<ProxyServer>& additional_bad_proxies,
179 const BoundNetLog& net_log);
181 // Called to report that the last proxy connection succeeded. If |proxy_info|
182 // has a non empty proxy_retry_info map, the proxies that have been tried (and
183 // failed) for this request will be marked as bad. |network_delegate| will
184 // be notified of any proxy fallbacks.
185 void ReportSuccess(const ProxyInfo& proxy_info,
186 NetworkDelegate* network_delegate);
188 // Call this method with a non-null |pac_request| to cancel the PAC request.
189 void CancelPacRequest(PacRequest* pac_request);
191 // Returns the LoadState for this |pac_request| which must be non-NULL.
192 LoadState GetLoadState(const PacRequest* pac_request) const;
194 // Sets the ProxyScriptFetcher and DhcpProxyScriptFetcher dependencies. This
195 // is needed if the ProxyResolver is of type ProxyResolverWithoutFetch.
196 // ProxyService takes ownership of both objects.
197 void SetProxyScriptFetchers(
198 ProxyScriptFetcher* proxy_script_fetcher,
199 DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher);
200 ProxyScriptFetcher* GetProxyScriptFetcher() const;
202 // Tells this ProxyService to start using a new ProxyConfigService to
203 // retrieve its ProxyConfig from. The new ProxyConfigService will immediately
204 // be queried for new config info which will be used for all subsequent
205 // ResolveProxy calls. ProxyService takes ownership of
206 // |new_proxy_config_service|.
207 void ResetConfigService(ProxyConfigService* new_proxy_config_service);
209 // Returns the last configuration fetched from ProxyConfigService.
210 const ProxyConfig& fetched_config() {
211 return fetched_config_;
214 // Returns the current configuration being used by ProxyConfigService.
215 const ProxyConfig& config() const {
216 return config_;
219 // Returns the map of proxies which have been marked as "bad".
220 const ProxyRetryInfoMap& proxy_retry_info() const {
221 return proxy_retry_info_;
224 // Clears the list of bad proxy servers that has been cached.
225 void ClearBadProxiesCache() {
226 proxy_retry_info_.clear();
229 // Forces refetching the proxy configuration, and applying it.
230 // This re-does everything from fetching the system configuration,
231 // to downloading and testing the PAC files.
232 void ForceReloadProxyConfig();
234 // Same as CreateProxyServiceUsingV8ProxyResolver, except it uses system
235 // libraries for evaluating the PAC script if available, otherwise skips
236 // proxy autoconfig.
237 static ProxyService* CreateUsingSystemProxyResolver(
238 ProxyConfigService* proxy_config_service,
239 size_t num_pac_threads,
240 NetLog* net_log);
242 // Creates a ProxyService without support for proxy autoconfig.
243 static ProxyService* CreateWithoutProxyResolver(
244 ProxyConfigService* proxy_config_service,
245 NetLog* net_log);
247 // Convenience methods that creates a proxy service using the
248 // specified fixed settings.
249 static ProxyService* CreateFixed(const ProxyConfig& pc);
250 static ProxyService* CreateFixed(const std::string& proxy);
252 // Creates a proxy service that uses a DIRECT connection for all requests.
253 static ProxyService* CreateDirect();
254 // |net_log|'s lifetime must exceed ProxyService.
255 static ProxyService* CreateDirectWithNetLog(NetLog* net_log);
257 // This method is used by tests to create a ProxyService that returns a
258 // hardcoded proxy fallback list (|pac_string|) for every URL.
260 // |pac_string| is a list of proxy servers, in the format that a PAC script
261 // would return it. For example, "PROXY foobar:99; SOCKS fml:2; DIRECT"
262 static ProxyService* CreateFixedFromPacResult(const std::string& pac_string);
264 // Creates a config service appropriate for this platform that fetches the
265 // system proxy settings.
266 static ProxyConfigService* CreateSystemProxyConfigService(
267 const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,
268 const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner);
270 // This method should only be used by unit tests.
271 void set_stall_proxy_auto_config_delay(base::TimeDelta delay) {
272 stall_proxy_auto_config_delay_ = delay;
275 // This method should only be used by unit tests. Returns the previously
276 // active policy.
277 static const PacPollPolicy* set_pac_script_poll_policy(
278 const PacPollPolicy* policy);
280 // This method should only be used by unit tests. Creates an instance
281 // of the default internal PacPollPolicy used by ProxyService.
282 static scoped_ptr<PacPollPolicy> CreateDefaultPacPollPolicy();
284 void set_quick_check_enabled(bool value) {
285 quick_check_enabled_ = value;
288 bool quick_check_enabled() const { return quick_check_enabled_; }
290 private:
291 FRIEND_TEST_ALL_PREFIXES(ProxyServiceTest, UpdateConfigAfterFailedAutodetect);
292 FRIEND_TEST_ALL_PREFIXES(ProxyServiceTest, UpdateConfigFromPACToDirect);
293 friend class PacRequest;
294 class InitProxyResolver;
295 class ProxyScriptDeciderPoller;
297 // TODO(eroman): change this to a std::set. Note that this requires updating
298 // some tests in proxy_service_unittest.cc such as:
299 // ProxyServiceTest.InitialPACScriptDownload
300 // which expects requests to finish in the order they were added.
301 typedef std::vector<scoped_refptr<PacRequest> > PendingRequests;
303 enum State {
304 STATE_NONE,
305 STATE_WAITING_FOR_PROXY_CONFIG,
306 STATE_WAITING_FOR_INIT_PROXY_RESOLVER,
307 STATE_READY,
310 // Resets all the variables associated with the current proxy configuration,
311 // and rewinds the current state to |STATE_NONE|. Returns the previous value
312 // of |current_state_|. If |reset_fetched_config| is true then
313 // |fetched_config_| will also be reset, otherwise it will be left as-is.
314 // Resetting it means that we will have to re-fetch the configuration from
315 // the ProxyConfigService later.
316 State ResetProxyConfig(bool reset_fetched_config);
318 // Retrieves the current proxy configuration from the ProxyConfigService, and
319 // starts initializing for it.
320 void ApplyProxyConfigIfAvailable();
322 // Callback for when the proxy resolver has been initialized with a
323 // PAC script.
324 void OnInitProxyResolverComplete(int result);
326 // Returns ERR_IO_PENDING if the request cannot be completed synchronously.
327 // Otherwise it fills |result| with the proxy information for |url|.
328 // Completing synchronously means we don't need to query ProxyResolver.
329 int TryToCompleteSynchronously(const GURL& url,
330 int load_flags,
331 NetworkDelegate* network_delegate,
332 ProxyInfo* result);
334 // Identical to ResolveProxy, except that |callback| is permitted to be null.
335 // if |callback.is_null()|, this function becomes a thin wrapper around
336 // |TryToCompleteSynchronously|.
337 int ResolveProxyHelper(const GURL& url,
338 int load_flags,
339 ProxyInfo* results,
340 const CompletionCallback& callback,
341 PacRequest** pac_request,
342 NetworkDelegate* network_delegate,
343 const BoundNetLog& net_log);
345 // Cancels all of the requests sent to the ProxyResolver. These will be
346 // restarted when calling SetReady().
347 void SuspendAllPendingRequests();
349 // Advances the current state to |STATE_READY|, and resumes any pending
350 // requests which had been stalled waiting for initialization to complete.
351 void SetReady();
353 // Returns true if |pending_requests_| contains |req|.
354 bool ContainsPendingRequest(PacRequest* req);
356 // Removes |req| from the list of pending requests.
357 void RemovePendingRequest(PacRequest* req);
359 // Called when proxy resolution has completed (either synchronously or
360 // asynchronously). Handles logging the result, and cleaning out
361 // bad entries from the results list.
362 int DidFinishResolvingProxy(const GURL& url,
363 int load_flags,
364 NetworkDelegate* network_delegate,
365 ProxyInfo* result,
366 int result_code,
367 const BoundNetLog& net_log,
368 base::TimeTicks start_time,
369 bool script_executed);
371 // Start initialization using |fetched_config_|.
372 void InitializeUsingLastFetchedConfig();
374 // Start the initialization skipping past the "decision" phase.
375 void InitializeUsingDecidedConfig(
376 int decider_result,
377 ProxyResolverScriptData* script_data,
378 const ProxyConfig& effective_config);
380 // NetworkChangeNotifier::IPAddressObserver
381 // When this is called, we re-fetch PAC scripts and re-run WPAD.
382 void OnIPAddressChanged() override;
384 // NetworkChangeNotifier::DNSObserver
385 // We respond as above.
386 void OnDNSChanged() override;
388 // ProxyConfigService::Observer
389 void OnProxyConfigChanged(
390 const ProxyConfig& config,
391 ProxyConfigService::ConfigAvailability availability) override;
393 scoped_ptr<ProxyConfigService> config_service_;
394 scoped_ptr<ProxyResolverFactory> resolver_factory_;
395 scoped_ptr<ProxyResolver> resolver_;
397 // We store the proxy configuration that was last fetched from the
398 // ProxyConfigService, as well as the resulting "effective" configuration.
399 // The effective configuration is what we condense the original fetched
400 // settings to after testing the various automatic settings (auto-detect
401 // and custom PAC url).
402 ProxyConfig fetched_config_;
403 ProxyConfig config_;
405 // Increasing ID to give to the next ProxyConfig that we set.
406 int next_config_id_;
408 // The time when the proxy configuration was last read from the system.
409 base::TimeTicks config_last_update_time_;
411 // Map of the known bad proxies and the information about the retry time.
412 ProxyRetryInfoMap proxy_retry_info_;
414 // Set of pending/inprogress requests.
415 PendingRequests pending_requests_;
417 // The fetcher to use when downloading PAC scripts for the ProxyResolver.
418 // This dependency can be NULL if our ProxyResolver has no need for
419 // external PAC script fetching.
420 scoped_ptr<ProxyScriptFetcher> proxy_script_fetcher_;
422 // The fetcher to use when attempting to download the most appropriate PAC
423 // script configured in DHCP, if any. Can be NULL if the ProxyResolver has
424 // no need for DHCP PAC script fetching.
425 scoped_ptr<DhcpProxyScriptFetcher> dhcp_proxy_script_fetcher_;
427 // Helper to download the PAC script (wpad + custom) and apply fallback rules.
429 // Note that the declaration is important here: |proxy_script_fetcher_| and
430 // |proxy_resolver_| must outlive |init_proxy_resolver_|.
431 scoped_ptr<InitProxyResolver> init_proxy_resolver_;
433 // Helper to poll the PAC script for changes.
434 scoped_ptr<ProxyScriptDeciderPoller> script_poller_;
436 State current_state_;
438 // Either OK or an ERR_* value indicating that a permanent error (e.g.
439 // failed to fetch the PAC script) prevents proxy resolution.
440 int permanent_error_;
442 // This is the log where any events generated by |init_proxy_resolver_| are
443 // sent to.
444 NetLog* net_log_;
446 // The earliest time at which we should run any proxy auto-config. (Used to
447 // stall re-configuration following an IP address change).
448 base::TimeTicks stall_proxy_autoconfig_until_;
450 // The amount of time to stall requests following IP address changes.
451 base::TimeDelta stall_proxy_auto_config_delay_;
453 // Whether child ProxyScriptDeciders should use QuickCheck
454 bool quick_check_enabled_;
456 DISALLOW_COPY_AND_ASSIGN(ProxyService);
459 } // namespace net
461 #endif // NET_PROXY_PROXY_SERVICE_H_