• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #ifndef NET_PROXY_PROXY_SERVICE_H_
6 #define NET_PROXY_PROXY_SERVICE_H_
7 
8 #include <string>
9 #include <vector>
10 
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/net_log.h"
20 #include "net/base/network_change_notifier.h"
21 #include "net/proxy/proxy_config_service.h"
22 #include "net/proxy/proxy_info.h"
23 #include "net/proxy/proxy_server.h"
24 
25 class GURL;
26 
27 namespace base {
28 class MessageLoop;
29 class SingleThreadTaskRunner;
30 class TimeDelta;
31 }  // namespace base
32 
33 namespace net {
34 
35 class DhcpProxyScriptFetcher;
36 class HostResolver;
37 class NetworkDelegate;
38 class ProxyResolver;
39 class ProxyResolverScriptData;
40 class ProxyScriptDecider;
41 class ProxyScriptFetcher;
42 
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;
52 
53   // This interface defines the set of policies for when to poll the PAC
54   // script for changes.
55   //
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).
61   //
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.
66   //
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,
79     };
80 
~PacPollPolicy()81     virtual ~PacPollPolicy() {}
82 
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;
92   };
93 
94   // The instance takes ownership of |config_service| and |resolver|.
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                ProxyResolver* resolver,
99                NetLog* net_log);
100 
101   virtual ~ProxyService();
102 
103   // Used internally to handle PAC queries.
104   // TODO(eroman): consider naming this simply "Request".
105   class PacRequest;
106 
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.
111   //
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.
117   //
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
124   //
125   // Profiling information for the request is saved to |net_log| if non-NULL.
126   int ResolveProxy(const GURL& url,
127                    ProxyInfo* results,
128                    const net::CompletionCallback& callback,
129                    PacRequest** pac_request,
130                    const BoundNetLog& net_log);
131 
132   // This method is called after a failure to connect or resolve a host name.
133   // It gives the proxy service an opportunity to reconsider the proxy to use.
134   // The |results| parameter contains the results returned by an earlier call
135   // to ResolveProxy.  The semantics of this call are otherwise similar to
136   // ResolveProxy.
137   //
138   // NULL can be passed for |pac_request| if the caller will not need to
139   // cancel the request.
140   //
141   // Returns ERR_FAILED if there is not another proxy config to try.
142   //
143   // Profiling information for the request is saved to |net_log| if non-NULL.
144   int ReconsiderProxyAfterError(const GURL& url,
145                                 ProxyInfo* results,
146                                 const CompletionCallback& callback,
147                                 PacRequest** pac_request,
148                                 const BoundNetLog& net_log);
149 
150   // Explicitly trigger proxy fallback for the given |results| by updating our
151   // list of bad proxies to include the first entry of |results|, and,
152   // optionally, another bad proxy. Will retry after |retry_delay| if positive,
153   // and will use the default proxy retry duration otherwise. Returns true if
154   // there will be at least one proxy remaining in the list after fallback and
155   // false otherwise.
156   bool MarkProxiesAsBad(const ProxyInfo& results,
157                         base::TimeDelta retry_delay,
158                         const ProxyServer& another_bad_proxy,
159                         const BoundNetLog& net_log);
160 
161   // Called to report that the last proxy connection succeeded.  If |proxy_info|
162   // has a non empty proxy_retry_info map, the proxies that have been tried (and
163   // failed) for this request will be marked as bad.
164   void ReportSuccess(const ProxyInfo& proxy_info);
165 
166   // Call this method with a non-null |pac_request| to cancel the PAC request.
167   void CancelPacRequest(PacRequest* pac_request);
168 
169   // Returns the LoadState for this |pac_request| which must be non-NULL.
170   LoadState GetLoadState(const PacRequest* pac_request) const;
171 
172   // Sets the ProxyScriptFetcher and DhcpProxyScriptFetcher dependencies. This
173   // is needed if the ProxyResolver is of type ProxyResolverWithoutFetch.
174   // ProxyService takes ownership of both objects.
175   void SetProxyScriptFetchers(
176       ProxyScriptFetcher* proxy_script_fetcher,
177       DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher);
178   ProxyScriptFetcher* GetProxyScriptFetcher() const;
179 
180   // Tells this ProxyService to start using a new ProxyConfigService to
181   // retrieve its ProxyConfig from. The new ProxyConfigService will immediately
182   // be queried for new config info which will be used for all subsequent
183   // ResolveProxy calls. ProxyService takes ownership of
184   // |new_proxy_config_service|.
185   void ResetConfigService(ProxyConfigService* new_proxy_config_service);
186 
187   // Tells the resolver to purge any memory it does not need.
188   void PurgeMemory();
189 
190 
191   // Returns the last configuration fetched from ProxyConfigService.
fetched_config()192   const ProxyConfig& fetched_config() {
193     return fetched_config_;
194   }
195 
196   // Returns the current configuration being used by ProxyConfigService.
config()197   const ProxyConfig& config() {
198     return config_;
199   }
200 
201   // Returns the map of proxies which have been marked as "bad".
proxy_retry_info()202   const ProxyRetryInfoMap& proxy_retry_info() const {
203     return proxy_retry_info_;
204   }
205 
206   // Clears the list of bad proxy servers that has been cached.
ClearBadProxiesCache()207   void ClearBadProxiesCache() {
208     proxy_retry_info_.clear();
209   }
210 
211   // Forces refetching the proxy configuration, and applying it.
212   // This re-does everything from fetching the system configuration,
213   // to downloading and testing the PAC files.
214   void ForceReloadProxyConfig();
215 
216   // Same as CreateProxyServiceUsingV8ProxyResolver, except it uses system
217   // libraries for evaluating the PAC script if available, otherwise skips
218   // proxy autoconfig.
219   static ProxyService* CreateUsingSystemProxyResolver(
220       ProxyConfigService* proxy_config_service,
221       size_t num_pac_threads,
222       NetLog* net_log);
223 
224   // Creates a ProxyService without support for proxy autoconfig.
225   static ProxyService* CreateWithoutProxyResolver(
226       ProxyConfigService* proxy_config_service,
227       NetLog* net_log);
228 
229   // Convenience methods that creates a proxy service using the
230   // specified fixed settings.
231   static ProxyService* CreateFixed(const ProxyConfig& pc);
232   static ProxyService* CreateFixed(const std::string& proxy);
233 
234   // Creates a proxy service that uses a DIRECT connection for all requests.
235   static ProxyService* CreateDirect();
236   // |net_log|'s lifetime must exceed ProxyService.
237   static ProxyService* CreateDirectWithNetLog(NetLog* net_log);
238 
239   // This method is used by tests to create a ProxyService that returns a
240   // hardcoded proxy fallback list (|pac_string|) for every URL.
241   //
242   // |pac_string| is a list of proxy servers, in the format that a PAC script
243   // would return it. For example, "PROXY foobar:99; SOCKS fml:2; DIRECT"
244   static ProxyService* CreateFixedFromPacResult(const std::string& pac_string);
245 
246   // Creates a config service appropriate for this platform that fetches the
247   // system proxy settings.
248   static ProxyConfigService* CreateSystemProxyConfigService(
249       base::SingleThreadTaskRunner* io_thread_task_runner,
250       base::MessageLoop* file_loop);
251 
252   // This method should only be used by unit tests.
set_stall_proxy_auto_config_delay(base::TimeDelta delay)253   void set_stall_proxy_auto_config_delay(base::TimeDelta delay) {
254     stall_proxy_auto_config_delay_ = delay;
255   }
256 
257   // This method should only be used by unit tests. Returns the previously
258   // active policy.
259   static const PacPollPolicy* set_pac_script_poll_policy(
260       const PacPollPolicy* policy);
261 
262   // This method should only be used by unit tests. Creates an instance
263   // of the default internal PacPollPolicy used by ProxyService.
264   static scoped_ptr<PacPollPolicy> CreateDefaultPacPollPolicy();
265 
266 #if defined(SPDY_PROXY_AUTH_ORIGIN)
267   // Values of the UMA DataReductionProxy.BypassInfo{Primary|Fallback}
268   // histograms. This enum must remain synchronized with the enum of the same
269   // name in metrics/histograms/histograms.xml.
270   enum DataReductionProxyBypassEventType {
271     // Bypass the proxy for less than 30 minutes.
272     SHORT_BYPASS = 0,
273 
274     // Bypass the proxy for 30 minutes or more.
275     LONG_BYPASS,
276 
277     // Bypass the proxy because of an internal server error.
278     INTERNAL_SERVER_ERROR_BYPASS,
279 
280     // Bypass the proxy because of any other error.
281     ERROR_BYPASS,
282 
283     // Bypass the proxy because responses appear not to be coming via it.
284     MISSING_VIA_HEADER,
285 
286     // This must always be last.
287     BYPASS_EVENT_TYPE_MAX
288   };
289 
290   // Records a |DataReductionProxyBypassEventType| for either the data reduction
291   // proxy (|is_primary| is true) or the data reduction proxy fallback.
292   void RecordDataReductionProxyBypassInfo(
293       bool is_primary,
294       const ProxyServer& proxy_server,
295       DataReductionProxyBypassEventType bypass_type) const;
296 #endif
297 
298  private:
299   FRIEND_TEST_ALL_PREFIXES(ProxyServiceTest, UpdateConfigAfterFailedAutodetect);
300   FRIEND_TEST_ALL_PREFIXES(ProxyServiceTest, UpdateConfigFromPACToDirect);
301   friend class PacRequest;
302   class InitProxyResolver;
303   class ProxyScriptDeciderPoller;
304 
305   // TODO(eroman): change this to a std::set. Note that this requires updating
306   // some tests in proxy_service_unittest.cc such as:
307   //   ProxyServiceTest.InitialPACScriptDownload
308   // which expects requests to finish in the order they were added.
309   typedef std::vector<scoped_refptr<PacRequest> > PendingRequests;
310 
311   enum State {
312     STATE_NONE,
313     STATE_WAITING_FOR_PROXY_CONFIG,
314     STATE_WAITING_FOR_INIT_PROXY_RESOLVER,
315     STATE_READY,
316   };
317 
318   // Resets all the variables associated with the current proxy configuration,
319   // and rewinds the current state to |STATE_NONE|. Returns the previous value
320   // of |current_state_|.  If |reset_fetched_config| is true then
321   // |fetched_config_| will also be reset, otherwise it will be left as-is.
322   // Resetting it means that we will have to re-fetch the configuration from
323   // the ProxyConfigService later.
324   State ResetProxyConfig(bool reset_fetched_config);
325 
326   // Retrieves the current proxy configuration from the ProxyConfigService, and
327   // starts initializing for it.
328   void ApplyProxyConfigIfAvailable();
329 
330   // Callback for when the proxy resolver has been initialized with a
331   // PAC script.
332   void OnInitProxyResolverComplete(int result);
333 
334   // Returns ERR_IO_PENDING if the request cannot be completed synchronously.
335   // Otherwise it fills |result| with the proxy information for |url|.
336   // Completing synchronously means we don't need to query ProxyResolver.
337   int TryToCompleteSynchronously(const GURL& url, ProxyInfo* result);
338 
339   // Cancels all of the requests sent to the ProxyResolver. These will be
340   // restarted when calling SetReady().
341   void SuspendAllPendingRequests();
342 
343   // Advances the current state to |STATE_READY|, and resumes any pending
344   // requests which had been stalled waiting for initialization to complete.
345   void SetReady();
346 
347   // Returns true if |pending_requests_| contains |req|.
348   bool ContainsPendingRequest(PacRequest* req);
349 
350   // Removes |req| from the list of pending requests.
351   void RemovePendingRequest(PacRequest* req);
352 
353   // Called when proxy resolution has completed (either synchronously or
354   // asynchronously). Handles logging the result, and cleaning out
355   // bad entries from the results list.
356   int DidFinishResolvingProxy(ProxyInfo* result,
357                               int result_code,
358                               const BoundNetLog& net_log);
359 
360   // Start initialization using |fetched_config_|.
361   void InitializeUsingLastFetchedConfig();
362 
363   // Start the initialization skipping past the "decision" phase.
364   void InitializeUsingDecidedConfig(
365       int decider_result,
366       ProxyResolverScriptData* script_data,
367       const ProxyConfig& effective_config);
368 
369   // NetworkChangeNotifier::IPAddressObserver
370   // When this is called, we re-fetch PAC scripts and re-run WPAD.
371   virtual void OnIPAddressChanged() OVERRIDE;
372 
373   // NetworkChangeNotifier::DNSObserver
374   // We respond as above.
375   virtual void OnDNSChanged() OVERRIDE;
376 
377   // ProxyConfigService::Observer
378   virtual void OnProxyConfigChanged(
379       const ProxyConfig& config,
380       ProxyConfigService::ConfigAvailability availability) OVERRIDE;
381 
382   scoped_ptr<ProxyConfigService> config_service_;
383   scoped_ptr<ProxyResolver> resolver_;
384 
385   // We store the proxy configuration that was last fetched from the
386   // ProxyConfigService, as well as the resulting "effective" configuration.
387   // The effective configuration is what we condense the original fetched
388   // settings to after testing the various automatic settings (auto-detect
389   // and custom PAC url).
390   ProxyConfig fetched_config_;
391   ProxyConfig config_;
392 
393   // Increasing ID to give to the next ProxyConfig that we set.
394   int next_config_id_;
395 
396   // The time when the proxy configuration was last read from the system.
397   base::TimeTicks config_last_update_time_;
398 
399   // Map of the known bad proxies and the information about the retry time.
400   ProxyRetryInfoMap proxy_retry_info_;
401 
402   // Set of pending/inprogress requests.
403   PendingRequests pending_requests_;
404 
405   // The fetcher to use when downloading PAC scripts for the ProxyResolver.
406   // This dependency can be NULL if our ProxyResolver has no need for
407   // external PAC script fetching.
408   scoped_ptr<ProxyScriptFetcher> proxy_script_fetcher_;
409 
410   // The fetcher to use when attempting to download the most appropriate PAC
411   // script configured in DHCP, if any. Can be NULL if the ProxyResolver has
412   // no need for DHCP PAC script fetching.
413   scoped_ptr<DhcpProxyScriptFetcher> dhcp_proxy_script_fetcher_;
414 
415   // Helper to download the PAC script (wpad + custom) and apply fallback rules.
416   //
417   // Note that the declaration is important here: |proxy_script_fetcher_| and
418   // |proxy_resolver_| must outlive |init_proxy_resolver_|.
419   scoped_ptr<InitProxyResolver> init_proxy_resolver_;
420 
421   // Helper to poll the PAC script for changes.
422   scoped_ptr<ProxyScriptDeciderPoller> script_poller_;
423 
424   State current_state_;
425 
426   // Either OK or an ERR_* value indicating that a permanent error (e.g.
427   // failed to fetch the PAC script) prevents proxy resolution.
428   int permanent_error_;
429 
430   // This is the log where any events generated by |init_proxy_resolver_| are
431   // sent to.
432   NetLog* net_log_;
433 
434   // The earliest time at which we should run any proxy auto-config. (Used to
435   // stall re-configuration following an IP address change).
436   base::TimeTicks stall_proxy_autoconfig_until_;
437 
438   // The amount of time to stall requests following IP address changes.
439   base::TimeDelta stall_proxy_auto_config_delay_;
440 
441   DISALLOW_COPY_AND_ASSIGN(ProxyService);
442 };
443 
444 // Wrapper for invoking methods on a ProxyService synchronously.
445 class NET_EXPORT SyncProxyServiceHelper
446     : public base::RefCountedThreadSafe<SyncProxyServiceHelper> {
447  public:
448   SyncProxyServiceHelper(base::MessageLoop* io_message_loop,
449                          ProxyService* proxy_service);
450 
451   int ResolveProxy(const GURL& url,
452                    ProxyInfo* proxy_info,
453                    const BoundNetLog& net_log);
454   int ReconsiderProxyAfterError(const GURL& url,
455                                 ProxyInfo* proxy_info,
456                                 const BoundNetLog& net_log);
457 
458  private:
459   friend class base::RefCountedThreadSafe<SyncProxyServiceHelper>;
460 
461   virtual ~SyncProxyServiceHelper();
462 
463   void StartAsyncResolve(const GURL& url, const BoundNetLog& net_log);
464   void StartAsyncReconsider(const GURL& url, const BoundNetLog& net_log);
465 
466   void OnCompletion(int result);
467 
468   base::MessageLoop* io_message_loop_;
469   ProxyService* proxy_service_;
470 
471   base::WaitableEvent event_;
472   CompletionCallback callback_;
473   ProxyInfo proxy_info_;
474   int result_;
475 };
476 
477 }  // namespace net
478 
479 #endif  // NET_PROXY_PROXY_SERVICE_H_
480