Home | History | Annotate | Download | only in browser
      1 // Copyright 2014 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 COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_SETTINGS_H_
      6 #define COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_SETTINGS_H_
      7 
      8 #include <vector>
      9 
     10 #include "base/basictypes.h"
     11 #include "base/callback.h"
     12 #include "base/compiler_specific.h"
     13 #include "base/gtest_prod_util.h"
     14 #include "base/memory/scoped_ptr.h"
     15 #include "base/prefs/pref_member.h"
     16 #include "base/threading/thread_checker.h"
     17 #include "components/data_reduction_proxy/browser/data_reduction_proxy_configurator.h"
     18 #include "components/data_reduction_proxy/browser/data_reduction_proxy_params.h"
     19 #include "components/data_reduction_proxy/browser/data_reduction_proxy_statistics_prefs.h"
     20 #include "net/base/net_util.h"
     21 #include "net/base/network_change_notifier.h"
     22 #include "net/url_request/url_fetcher_delegate.h"
     23 
     24 class PrefService;
     25 
     26 namespace net {
     27 class HostPortPair;
     28 class HttpNetworkSession;
     29 class HttpResponseHeaders;
     30 class URLFetcher;
     31 class URLRequestContextGetter;
     32 }
     33 
     34 namespace data_reduction_proxy {
     35 
     36 // The number of days of bandwidth usage statistics that are tracked.
     37 const unsigned int kNumDaysInHistory = 60;
     38 
     39 // The number of days of bandwidth usage statistics that are presented.
     40 const unsigned int kNumDaysInHistorySummary = 30;
     41 
     42 COMPILE_ASSERT(kNumDaysInHistorySummary <= kNumDaysInHistory,
     43                DataReductionProxySettings_summary_too_long);
     44 
     45 // Values of the UMA DataReductionProxy.StartupState histogram.
     46 // This enum must remain synchronized with DataReductionProxyStartupState
     47 // in metrics/histograms/histograms.xml.
     48 enum ProxyStartupState {
     49   PROXY_NOT_AVAILABLE = 0,
     50   PROXY_DISABLED,
     51   PROXY_ENABLED,
     52   PROXY_STARTUP_STATE_COUNT,
     53 };
     54 
     55 // Values of the UMA DataReductionProxy.ProbeURL histogram.
     56 // This enum must remain synchronized with
     57 // DataReductionProxyProbeURLFetchResult in metrics/histograms/histograms.xml.
     58 // TODO(marq): Rename these histogram buckets with s/DISABLED/RESTRICTED/, so
     59 //     their names match the behavior they track.
     60 enum ProbeURLFetchResult {
     61   // The probe failed because the Internet was disconnected.
     62   INTERNET_DISCONNECTED = 0,
     63 
     64   // The probe failed for any other reason, and as a result, the proxy was
     65   // disabled.
     66   FAILED_PROXY_DISABLED,
     67 
     68   // The probe failed, but the proxy was already restricted.
     69   FAILED_PROXY_ALREADY_DISABLED,
     70 
     71   // The probe succeeded, and as a result the proxy was restricted.
     72   SUCCEEDED_PROXY_ENABLED,
     73 
     74   // The probe succeeded, but the proxy was already restricted.
     75   SUCCEEDED_PROXY_ALREADY_ENABLED,
     76 
     77   // This must always be last.
     78   PROBE_URL_FETCH_RESULT_COUNT
     79 };
     80 
     81 // Central point for configuring the data reduction proxy.
     82 // This object lives on the UI thread and all of its methods are expected to
     83 // be called from there.
     84 // TODO(marq): Convert this to be a KeyedService with an
     85 // associated factory class, and refactor the Java call sites accordingly.
     86 class DataReductionProxySettings
     87     : public net::URLFetcherDelegate,
     88       public net::NetworkChangeNotifier::IPAddressObserver {
     89  public:
     90   typedef std::vector<long long> ContentLengthList;
     91 
     92   static bool IsProxyKeySetOnCommandLine();
     93 
     94   DataReductionProxySettings(DataReductionProxyParams* params);
     95   virtual ~DataReductionProxySettings();
     96 
     97   DataReductionProxyParams* params() const {
     98     return params_.get();
     99   }
    100 
    101   // Initializes the data reduction proxy with profile and local state prefs,
    102   // and a |UrlRequestContextGetter| for canary probes. The caller must ensure
    103   // that all parameters remain alive for the lifetime of the
    104   // |DataReductionProxySettings| instance.
    105   void InitDataReductionProxySettings(
    106       PrefService* prefs,
    107       net::URLRequestContextGetter* url_request_context_getter);
    108 
    109   // Initializes the data reduction proxy with profile and local state prefs,
    110   // a |UrlRequestContextGetter| for canary probes, and a proxy configurator.
    111   // The caller must ensure that all parameters remain alive for the lifetime of
    112   // the |DataReductionProxySettings| instance.
    113   // TODO(marq): Remove when iOS supports the new interface above.
    114   void InitDataReductionProxySettings(
    115       PrefService* prefs,
    116       net::URLRequestContextGetter* url_request_context_getter,
    117       DataReductionProxyConfigurator* configurator);
    118 
    119   // Sets the |statistics_prefs_| to be used for data reduction proxy pref reads
    120   // and writes.
    121   void SetDataReductionProxyStatisticsPrefs(
    122       DataReductionProxyStatisticsPrefs* statistics_prefs);
    123 
    124   // Sets the |on_data_reduction_proxy_enabled_| callback and runs to register
    125   // the DataReductionProxyEnabled synthetic field trial.
    126   void SetOnDataReductionEnabledCallback(
    127       const base::Callback<void(bool)>& on_data_reduction_proxy_enabled);
    128 
    129   // Sets the logic the embedder uses to set the networking configuration that
    130   // causes traffic to be proxied.
    131   void SetProxyConfigurator(
    132       DataReductionProxyConfigurator* configurator);
    133 
    134   // Returns true if the proxy is enabled.
    135   bool IsDataReductionProxyEnabled();
    136 
    137   // Returns true if the alternative proxy is enabled.
    138   bool IsDataReductionProxyAlternativeEnabled() const;
    139 
    140   // Returns true if the proxy is managed by an adminstrator's policy.
    141   bool IsDataReductionProxyManaged();
    142 
    143   // Enables or disables the data reduction proxy. If a probe URL is available,
    144   // and a probe request fails at some point, the proxy won't be used until a
    145   // probe succeeds.
    146   void SetDataReductionProxyEnabled(bool enabled);
    147 
    148   // Enables or disables the alternative data reduction proxy configuration.
    149   void SetDataReductionProxyAlternativeEnabled(bool enabled);
    150 
    151   // Returns the time in microseconds that the last update was made to the
    152   // daily original and received content lengths.
    153   int64 GetDataReductionLastUpdateTime();
    154 
    155   // Returns a vector containing the total size of all HTTP content that was
    156   // received over the last |kNumDaysInHistory| before any compression by the
    157   // data reduction proxy. Each element in the vector contains one day of data.
    158   ContentLengthList GetDailyOriginalContentLengths();
    159 
    160   // Returns aggregate received and original content lengths over the specified
    161   // number of days, as well as the time these stats were last updated.
    162   void GetContentLengths(unsigned int days,
    163                          int64* original_content_length,
    164                          int64* received_content_length,
    165                          int64* last_update_time);
    166 
    167   // Records that the data reduction proxy is unreachable or not.
    168   void SetUnreachable(bool unreachable);
    169 
    170   // Returns whether the data reduction proxy is unreachable. Returns true
    171   // if no request has successfully completed through proxy, even though atleast
    172   // some of them should have.
    173   bool IsDataReductionProxyUnreachable();
    174 
    175   // Returns an vector containing the aggregate received HTTP content in the
    176   // last |kNumDaysInHistory| days.
    177   ContentLengthList GetDailyReceivedContentLengths();
    178 
    179   ContentLengthList GetDailyContentLengths(const char* pref_name);
    180 
    181   // net::URLFetcherDelegate:
    182   virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE;
    183 
    184  protected:
    185   void InitPrefMembers();
    186 
    187   // Returns a fetcher for the probe to check if OK for the proxy to use SPDY.
    188   // Virtual for testing.
    189   virtual net::URLFetcher* GetURLFetcherForAvailabilityCheck();
    190 
    191   // Virtualized for unit test support.
    192   virtual PrefService* GetOriginalProfilePrefs();
    193 
    194   // Sets the proxy configs, enabling or disabling the proxy according to
    195   // the value of |enabled| and |alternative_enabled|. Use the alternative
    196   // configuration only if |enabled| and |alternative_enabled| are true. If
    197   // |restricted| is true, only enable the fallback proxy. |at_startup| is true
    198   // when this method is called from InitDataReductionProxySettings.
    199   virtual void SetProxyConfigs(bool enabled,
    200                                bool alternative_enabled,
    201                                bool restricted,
    202                                bool at_startup);
    203 
    204   // Metrics method. Subclasses should override if they wish to provide
    205   // alternatives.
    206   virtual void RecordDataReductionInit();
    207 
    208   virtual void AddDefaultProxyBypassRules();
    209 
    210   // Writes a warning to the log that is used in backend processing of
    211   // customer feedback. Virtual so tests can mock it for verification.
    212   virtual void LogProxyState(bool enabled, bool restricted, bool at_startup);
    213 
    214   // Virtualized for mocking. Records UMA containing the result of requesting
    215   // the probe URL.
    216   virtual void RecordProbeURLFetchResult(
    217       data_reduction_proxy::ProbeURLFetchResult result);
    218 
    219   // Virtualized for mocking. Records UMA specifying whether the proxy was
    220   // enabled or disabled at startup.
    221   virtual void RecordStartupState(
    222       data_reduction_proxy::ProxyStartupState state);
    223 
    224   // Virtualized for mocking. Returns the list of network interfaces in use.
    225   virtual void GetNetworkList(net::NetworkInterfaceList* interfaces,
    226                               int policy);
    227 
    228   DataReductionProxyConfigurator* configurator() {
    229     return configurator_;
    230   }
    231 
    232   // Reset params for tests.
    233   void ResetParamsForTest(DataReductionProxyParams* params);
    234 
    235  private:
    236   friend class DataReductionProxySettingsTestBase;
    237   friend class DataReductionProxySettingsTest;
    238   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    239                            TestAuthenticationInit);
    240   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    241                            TestAuthHashGeneration);
    242   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    243                            TestAuthHashGenerationWithOriginSetViaSwitch);
    244   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    245                            TestResetDataReductionStatistics);
    246   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    247                            TestIsProxyEnabledOrManaged);
    248   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    249                            TestContentLengths);
    250   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    251                            TestGetDailyContentLengths);
    252   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    253                            TestMaybeActivateDataReductionProxy);
    254   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    255                            TestOnIPAddressChanged);
    256   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    257                            TestOnProxyEnabledPrefChange);
    258   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    259                            TestInitDataReductionProxyOn);
    260   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    261                            TestInitDataReductionProxyOff);
    262   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    263                            TestBypassList);
    264   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    265                            CheckInitMetricsWhenNotAllowed);
    266   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    267                            TestSetProxyConfigs);
    268   FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest,
    269                            TestSetProxyConfigsHoldback);
    270 
    271   // NetworkChangeNotifier::IPAddressObserver:
    272   virtual void OnIPAddressChanged() OVERRIDE;
    273 
    274   void OnProxyEnabledPrefChange();
    275   void OnProxyAlternativeEnabledPrefChange();
    276 
    277   void ResetDataReductionStatistics();
    278 
    279   void MaybeActivateDataReductionProxy(bool at_startup);
    280 
    281   // Requests the proxy probe URL, if one is set.  If unable to do so, disables
    282   // the proxy, if enabled. Otherwise enables the proxy if disabled by a probe
    283   // failure.
    284   void ProbeWhetherDataReductionProxyIsAvailable();
    285 
    286   // Disables use of the data reduction proxy on VPNs. Returns true if the
    287   // data reduction proxy has been disabled.
    288   bool DisableIfVPN();
    289 
    290   // Generic method to get a URL fetcher.
    291   net::URLFetcher* GetBaseURLFetcher(const GURL& gurl, int load_flags);
    292 
    293   std::string key_;
    294   bool restricted_by_carrier_;
    295   bool enabled_by_user_;
    296   bool disabled_on_vpn_;
    297   bool unreachable_;
    298 
    299   scoped_ptr<net::URLFetcher> fetcher_;
    300 
    301   BooleanPrefMember spdy_proxy_auth_enabled_;
    302   BooleanPrefMember data_reduction_proxy_alternative_enabled_;
    303 
    304   PrefService* prefs_;
    305   DataReductionProxyStatisticsPrefs* statistics_prefs_;
    306 
    307   net::URLRequestContextGetter* url_request_context_getter_;
    308 
    309   base::Callback<void(bool)> on_data_reduction_proxy_enabled_;
    310 
    311   DataReductionProxyConfigurator* configurator_;
    312 
    313   base::ThreadChecker thread_checker_;
    314 
    315   scoped_ptr<DataReductionProxyParams> params_;
    316 
    317   DISALLOW_COPY_AND_ASSIGN(DataReductionProxySettings);
    318 };
    319 
    320 }  // namespace data_reduction_proxy
    321 
    322 #endif  // COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_SETTINGS_H_
    323