diff options
54 files changed, 1564 insertions, 1100 deletions
diff --git a/chrome/browser/DEPS b/chrome/browser/DEPS index c6ccd40..1bf303e 100644 --- a/chrome/browser/DEPS +++ b/chrome/browser/DEPS @@ -14,6 +14,7 @@ include_rules = [ "+components/autofill/core/common", "+components/bookmarks/core/common", "+components/breakpad", + "+components/data_reduction_proxy", "+components/dom_distiller", "+components/domain_reliability", "+components/keyed_service", diff --git a/chrome/browser/android/intercept_download_resource_throttle.cc b/chrome/browser/android/intercept_download_resource_throttle.cc index da5d1af..689306f 100644 --- a/chrome/browser/android/intercept_download_resource_throttle.cc +++ b/chrome/browser/android/intercept_download_resource_throttle.cc @@ -52,7 +52,8 @@ void InterceptDownloadResourceThrottle::ProcessDownloadRequest() { request_->GetFullRequestHeaders(&headers); if (headers.HasHeader(net::HttpRequestHeaders::kAuthorization) || !(request_->response_info().headers && - request_->response_info().headers->IsChromeProxyResponse())) { + request_->response_info().headers-> + IsDataReductionProxyResponse())) { return; } #else diff --git a/chrome/browser/io_thread.cc b/chrome/browser/io_thread.cc index 1ae0e04..6ff1aea 100644 --- a/chrome/browser/io_thread.cc +++ b/chrome/browser/io_thread.cc @@ -39,12 +39,12 @@ #include "chrome/browser/net/pref_proxy_config_tracker.h" #include "chrome/browser/net/proxy_service_factory.h" #include "chrome/browser/net/sdch_dictionary_fetcher.h" -#include "chrome/browser/net/spdyproxy/http_auth_handler_spdyproxy.h" #include "chrome/common/chrome_content_client.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" +#include "components/data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy.h" #include "components/policy/core/common/policy_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/cookie_store_factory.h" @@ -101,7 +101,7 @@ #endif #if defined(OS_ANDROID) || defined(OS_IOS) -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h" #endif #if defined(OS_CHROMEOS) @@ -111,6 +111,10 @@ using content::BrowserThread; +#if defined(OS_ANDROID) || defined(OS_IOS) +using data_reduction_proxy::DataReductionProxySettings; +#endif + class SafeBrowsingURLRequestContext; // The IOThread object must outlive any tasks posted to the IO thread before the @@ -871,30 +875,46 @@ void IOThread::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist, std::string()); registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string()); - registry->RegisterStringPref(prefs::kSpdyProxyAuthOrigin, std::string()); + registry->RegisterStringPref( + data_reduction_proxy::prefs::kDataReductionProxy, std::string()); registry->RegisterBooleanPref(prefs::kEnableReferrers, true); - registry->RegisterInt64Pref(prefs::kHttpReceivedContentLength, 0); - registry->RegisterInt64Pref(prefs::kHttpOriginalContentLength, 0); + registry->RegisterInt64Pref( + data_reduction_proxy::prefs::kHttpReceivedContentLength, 0); + registry->RegisterInt64Pref( + data_reduction_proxy::prefs::kHttpOriginalContentLength, 0); #if defined(OS_ANDROID) || defined(OS_IOS) - registry->RegisterListPref(prefs::kDailyHttpOriginalContentLength); - registry->RegisterListPref(prefs::kDailyHttpReceivedContentLength); registry->RegisterListPref( - prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled); + data_reduction_proxy::prefs::kDailyHttpOriginalContentLength); + registry->RegisterListPref( + data_reduction_proxy::prefs::kDailyHttpReceivedContentLength); + registry->RegisterListPref( + data_reduction_proxy::prefs:: + kDailyOriginalContentLengthWithDataReductionProxyEnabled); registry->RegisterListPref( - prefs::kDailyContentLengthWithDataReductionProxyEnabled); + data_reduction_proxy::prefs:: + kDailyContentLengthWithDataReductionProxyEnabled); registry->RegisterListPref( - prefs::kDailyContentLengthHttpsWithDataReductionProxyEnabled); + data_reduction_proxy::prefs:: + kDailyContentLengthHttpsWithDataReductionProxyEnabled); registry->RegisterListPref( - prefs::kDailyContentLengthShortBypassWithDataReductionProxyEnabled); + data_reduction_proxy::prefs:: + kDailyContentLengthShortBypassWithDataReductionProxyEnabled + ); registry->RegisterListPref( - prefs::kDailyContentLengthLongBypassWithDataReductionProxyEnabled); + data_reduction_proxy::prefs:: + kDailyContentLengthLongBypassWithDataReductionProxyEnabled); registry->RegisterListPref( - prefs::kDailyContentLengthUnknownWithDataReductionProxyEnabled); + data_reduction_proxy::prefs:: + kDailyContentLengthUnknownWithDataReductionProxyEnabled); registry->RegisterListPref( - prefs::kDailyOriginalContentLengthViaDataReductionProxy); + data_reduction_proxy::prefs:: + kDailyOriginalContentLengthViaDataReductionProxy); registry->RegisterListPref( - prefs::kDailyContentLengthViaDataReductionProxy); - registry->RegisterInt64Pref(prefs::kDailyHttpContentLengthLastUpdateDate, 0L); + data_reduction_proxy:: + prefs::kDailyContentLengthViaDataReductionProxy); + registry->RegisterInt64Pref( + data_reduction_proxy::prefs:: + kDailyHttpContentLengthLastUpdateDate, 0L); #endif registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true); registry->RegisterBooleanPref(prefs::kQuickCheckEnabled, true); @@ -927,7 +947,7 @@ net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory( if (!spdyproxy_auth_origins_.empty()) { registry_factory->RegisterSchemeFactory( "spdyproxy", - new spdyproxy::HttpAuthHandlerSpdyProxy::Factory( + new data_reduction_proxy::HttpAuthHandlerDataReductionProxy::Factory( spdyproxy_auth_origins_)); } diff --git a/chrome/browser/net/chrome_network_delegate.cc b/chrome/browser/net/chrome_network_delegate.cc index 63a6951..8e5cf65 100644 --- a/chrome/browser/net/chrome_network_delegate.cc +++ b/chrome/browser/net/chrome_network_delegate.cc @@ -28,12 +28,12 @@ #include "chrome/browser/google/google_util.h" #include "chrome/browser/net/client_hints.h" #include "chrome/browser/net/connect_interceptor.h" -#include "chrome/browser/net/spdyproxy/data_saving_metrics.h" #include "chrome/browser/performance_monitor/performance_monitor.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/task_manager/task_manager.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_metrics.h" #include "components/domain_reliability/monitor.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" @@ -225,7 +225,7 @@ void ForwardRequestStatus( void UpdateContentLengthPrefs( int received_content_length, int original_content_length, - spdyproxy::DataReductionRequestType data_reduction_type, + data_reduction_proxy::DataReductionProxyRequestType request_type, Profile* profile) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_GE(received_content_length, 0); @@ -249,26 +249,26 @@ void UpdateContentLengthPrefs( // the browser preference will be taken. bool with_data_reduction_proxy_enabled = ProfileManager::GetActiveUserProfile()->GetPrefs()->GetBoolean( - prefs::kSpdyProxyAuthEnabled); + data_reduction_proxy::prefs::kDataReductionProxyEnabled); #else bool with_data_reduction_proxy_enabled = false; #endif - spdyproxy::UpdateContentLengthPrefs(received_content_length, - original_content_length, - with_data_reduction_proxy_enabled, - data_reduction_type, prefs); + data_reduction_proxy::UpdateContentLengthPrefs(received_content_length, + original_content_length, + with_data_reduction_proxy_enabled, + request_type, prefs); } void StoreAccumulatedContentLength( int received_content_length, int original_content_length, - spdyproxy::DataReductionRequestType data_reduction_type, + data_reduction_proxy::DataReductionProxyRequestType request_type, Profile* profile) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&UpdateContentLengthPrefs, received_content_length, original_content_length, - data_reduction_type, profile)); + request_type, profile)); } void RecordContentLengthHistograms( @@ -424,8 +424,10 @@ void ChromeNetworkDelegate::AllowAccessToAllFiles() { base::Value* ChromeNetworkDelegate::HistoricNetworkStatsInfoToValue() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); PrefService* prefs = g_browser_process->local_state(); - int64 total_received = prefs->GetInt64(prefs::kHttpReceivedContentLength); - int64 total_original = prefs->GetInt64(prefs::kHttpOriginalContentLength); + int64 total_received = prefs->GetInt64( + data_reduction_proxy::prefs::kHttpReceivedContentLength); + int64 total_original = prefs->GetInt64( + data_reduction_proxy::prefs::kHttpOriginalContentLength); base::DictionaryValue* dict = new base::DictionaryValue(); // Use strings to avoid overflow. base::Value only supports 32-bit integers. @@ -617,19 +619,19 @@ void ChromeNetworkDelegate::OnCompleted(net::URLRequest* request, int64 original_content_length = request->response_info().headers->GetInt64HeaderValue( "x-original-content-length"); - spdyproxy::DataReductionRequestType data_reduction_type = - spdyproxy::GetDataReductionRequestType(request); + data_reduction_proxy::DataReductionProxyRequestType request_type = + data_reduction_proxy::GetDataReductionProxyRequestType(request); base::TimeDelta freshness_lifetime = request->response_info().headers->GetFreshnessLifetime( request->response_info().response_time); int64 adjusted_original_content_length = - spdyproxy::GetAdjustedOriginalContentLength( - data_reduction_type, original_content_length, + data_reduction_proxy::GetAdjustedOriginalContentLength( + request_type, original_content_length, received_content_length); AccumulateContentLength(received_content_length, adjusted_original_content_length, - data_reduction_type); + request_type); RecordContentLengthHistograms(received_content_length, original_content_length, freshness_lifetime); @@ -856,12 +858,12 @@ int ChromeNetworkDelegate::OnBeforeSocketStreamConnect( void ChromeNetworkDelegate::AccumulateContentLength( int64 received_content_length, int64 original_content_length, - spdyproxy::DataReductionRequestType data_reduction_type) { + data_reduction_proxy::DataReductionProxyRequestType request_type) { DCHECK_GE(received_content_length, 0); DCHECK_GE(original_content_length, 0); StoreAccumulatedContentLength(received_content_length, original_content_length, - data_reduction_type, + request_type, reinterpret_cast<Profile*>(profile_)); received_content_length_ += received_content_length; original_content_length_ += original_content_length; diff --git a/chrome/browser/net/chrome_network_delegate.h b/chrome/browser/net/chrome_network_delegate.h index 111e136..2053180 100644 --- a/chrome/browser/net/chrome_network_delegate.h +++ b/chrome/browser/net/chrome_network_delegate.h @@ -13,7 +13,7 @@ #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/values.h" -#include "chrome/browser/net/spdyproxy/data_saving_metrics.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_metrics.h" #include "net/base/network_delegate.h" class ClientHints; @@ -186,7 +186,7 @@ class ChromeNetworkDelegate : public net::NetworkDelegate { void AccumulateContentLength( int64 received_payload_byte_count, int64 original_payload_byte_count, - spdyproxy::DataReductionRequestType data_reduction_type); + data_reduction_proxy::DataReductionProxyRequestType request_type); scoped_refptr<extensions::EventRouterForwarder> event_router_; void* profile_; diff --git a/chrome/browser/net/predictor.cc b/chrome/browser/net/predictor.cc index 38e123d..5492eab 100644 --- a/chrome/browser/net/predictor.cc +++ b/chrome/browser/net/predictor.cc @@ -26,11 +26,11 @@ #include "base/values.h" #include "chrome/browser/io_thread.h" #include "chrome/browser/net/preconnect.h" -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h" #include "chrome/browser/net/spdyproxy/proxy_advisor.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h" #include "components/user_prefs/pref_registry_syncable.h" #include "content/public/browser/browser_thread.h" #include "net/base/address_list.h" @@ -337,7 +337,8 @@ void Predictor::InitNetworkPredictor(PrefService* user_prefs, // Until then, we may create a proxy advisor when the proxy feature itself // isn't available, and the advisor instance will never send advisory // requests, which is slightly wasteful but not harmful. - if (DataReductionProxySettings::IsPreconnectHintingAllowed()) { + if (data_reduction_proxy::DataReductionProxySettings:: + IsPreconnectHintingAllowed()) { proxy_advisor_.reset(new ProxyAdvisor(user_prefs, getter)); } #endif diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.cc b/chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.cc new file mode 100644 index 0000000..bd4d571 --- /dev/null +++ b/chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.cc @@ -0,0 +1,74 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.h" + +#include "base/prefs/pref_service.h" +#include "base/prefs/scoped_user_pref_update.h" +#include "base/strings/string_util.h" +#include "chrome/browser/prefs/proxy_prefs.h" +#include "chrome/common/pref_names.h" + +DataReductionProxyChromeConfigurator::DataReductionProxyChromeConfigurator( + PrefService* prefs) : prefs_(prefs) { + DCHECK(prefs); +} + +DataReductionProxyChromeConfigurator::~DataReductionProxyChromeConfigurator() { +} + +void DataReductionProxyChromeConfigurator::Enable(bool restricted, + const std::string& primary_origin, + const std::string& fallback_origin) { + DCHECK(prefs_); + DictionaryPrefUpdate update(prefs_, prefs::kProxy); + base::DictionaryValue* dict = update.Get(); + std::string proxy_list; + std::string trimmed_fallback_origin; + base::TrimString(fallback_origin, "/", &trimmed_fallback_origin); + + if (restricted) { + DCHECK(!fallback_origin.empty()); + proxy_list = trimmed_fallback_origin; + } else { + std::string trimmed_primary_origin; + base::TrimString(primary_origin, "/", &trimmed_primary_origin); + proxy_list = trimmed_primary_origin + + (fallback_origin.empty() ? "" : "," + trimmed_fallback_origin); + } + + std::string proxy_server_config = "http=" + proxy_list + ",direct://;"; + dict->SetString("server", proxy_server_config); + dict->SetString("mode", ProxyModeToString(ProxyPrefs::MODE_FIXED_SERVERS)); + dict->SetString("bypass_list", JoinString(bypass_rules_, ", ")); +} + +void DataReductionProxyChromeConfigurator::Disable() { + DCHECK(prefs_); + DictionaryPrefUpdate update(prefs_, prefs::kProxy); + base::DictionaryValue* dict = update.Get(); + dict->SetString("mode", ProxyModeToString(ProxyPrefs::MODE_SYSTEM)); + dict->SetString("server", ""); + dict->SetString("bypass_list", ""); +} + +void DataReductionProxyChromeConfigurator::AddHostPatternToBypass( + const std::string& pattern) { + bypass_rules_.push_back(pattern); +} + +void DataReductionProxyChromeConfigurator::AddURLPatternToBypass( + const std::string& pattern) { + size_t pos = pattern.find('/'); + if (pattern.find('/', pos + 1) == pos + 1) + pos = pattern.find('/', pos + 2); + + std::string host_pattern; + if (pos != std::string::npos) + host_pattern = pattern.substr(0, pos); + else + host_pattern = pattern; + + AddHostPatternToBypass(host_pattern); +} diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.h b/chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.h new file mode 100644 index 0000000..91123ae --- /dev/null +++ b/chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.h @@ -0,0 +1,48 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_CHROME_CONFIGURATOR_H_ +#define CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_CHROME_CONFIGURATOR_H_ + +#include <string> +#include <vector> + +#include "base/gtest_prod_util.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_configurator.h" + +class PrefService; + +class DataReductionProxyChromeConfigurator + : public data_reduction_proxy::DataReductionProxyConfigurator { + public: + explicit DataReductionProxyChromeConfigurator(PrefService* prefs); + virtual ~DataReductionProxyChromeConfigurator(); + + virtual void Enable(bool restricted, + const std::string& primary_origin, + const std::string& fallback_origin) OVERRIDE; + virtual void Disable() OVERRIDE; + + // Add a host pattern to bypass. This should follow the same syntax used + // in net::ProxyBypassRules; that is, a hostname pattern, a hostname suffix + // pattern, an IP literal, a CIDR block, or the magic string '<local>'. + // Bypass settings persist for the life of this object and are applied + // each time the proxy is enabled, but are not updated while it is enabled. + virtual void AddHostPatternToBypass(const std::string& pattern) OVERRIDE; + + // Add a URL pattern to bypass the proxy. The base implementation strips + // everything in |pattern| after the first single slash and then treats it + // as a hostname pattern. Subclasses may implement other semantics. + virtual void AddURLPatternToBypass(const std::string& pattern) OVERRIDE; + + private: + FRIEND_TEST_ALL_PREFIXES(DataReductionProxyConfigTest, TestBypassList); + + PrefService* prefs_; + std::vector<std::string> bypass_rules_; + + DISALLOW_COPY_AND_ASSIGN(DataReductionProxyChromeConfigurator); +}; + +#endif // CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_CHROME_CONFIGURATOR_H_ diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator_unittest.cc b/chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator_unittest.cc new file mode 100644 index 0000000..9e41dc4 --- /dev/null +++ b/chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator_unittest.cc @@ -0,0 +1,116 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.h" + +#include <string> + +#include "base/memory/scoped_ptr.h" +#include "base/prefs/pref_registry_simple.h" +#include "base/prefs/testing_pref_service.h" +#include "base/values.h" +#include "chrome/common/pref_names.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +class DataReductionProxyConfigTest : public testing::Test { + public: + virtual void SetUp() { + PrefRegistrySimple* registry = pref_service_.registry(); + registry->RegisterDictionaryPref(prefs::kProxy); + config_.reset(new DataReductionProxyChromeConfigurator(&pref_service_)); + } + + void CheckProxyConfig( + const std::string& expected_mode, + const std::string& expected_server, + const std::string& expected_bypass_list) { + + const base::DictionaryValue* dict = + pref_service_.GetDictionary(prefs::kProxy); + std::string mode; + std::string server; + std::string bypass_list; + dict->GetString("mode", &mode); + ASSERT_EQ(expected_mode, mode); + dict->GetString("server", &server); + ASSERT_EQ(expected_server, server); + dict->GetString("bypass_list", &bypass_list); + ASSERT_EQ(expected_bypass_list, bypass_list); + } + + scoped_ptr<DataReductionProxyChromeConfigurator> config_; + TestingPrefServiceSimple pref_service_; +}; + +TEST_F(DataReductionProxyConfigTest, TestUnrestricted) { + config_->Enable(false, + "https://www.foo.com:443/", + "http://www.bar.com:80/"); + CheckProxyConfig( + "fixed_servers", + "http=https://www.foo.com:443,http://www.bar.com:80,direct://;", + ""); +} +TEST_F(DataReductionProxyConfigTest, TestUnrestrictedWithBypassRule) { + config_->AddHostPatternToBypass("<local>"); + config_->AddHostPatternToBypass("*.goo.com"); + config_->Enable(false, + "https://www.foo.com:443/", + "http://www.bar.com:80/"); + CheckProxyConfig( + "fixed_servers", + "http=https://www.foo.com:443,http://www.bar.com:80,direct://;", + "<local>, *.goo.com"); +} + +TEST_F(DataReductionProxyConfigTest, TestUnrestrictedWithoutFallback) { + config_->Enable(false, + "https://www.foo.com:443/", + ""); + CheckProxyConfig("fixed_servers", + "http=https://www.foo.com:443,direct://;", + ""); +} + +TEST_F(DataReductionProxyConfigTest, TestRestricted) { + config_->Enable(true, + "https://www.foo.com:443/", + "http://www.bar.com:80/"); + CheckProxyConfig("fixed_servers", + "http=http://www.bar.com:80,direct://;", + ""); +} + +TEST_F(DataReductionProxyConfigTest, TestDisable) { + config_->Disable(); + CheckProxyConfig("system", "", ""); +} + + +TEST_F(DataReductionProxyConfigTest, TestBypassList) { + config_->AddHostPatternToBypass("http://www.google.com"); + config_->AddHostPatternToBypass("fefe:13::abc/33"); + config_->AddURLPatternToBypass("foo.org/images/*"); + config_->AddURLPatternToBypass("http://foo.com/*"); + config_->AddURLPatternToBypass("http://baz.com:22/bar/*"); + config_->AddURLPatternToBypass("http://*bat.com/bar/*"); + + std::string expected[] = { + "http://www.google.com", + "fefe:13::abc/33", + "foo.org", + "http://foo.com", + "http://baz.com:22", + "http://*bat.com" + }; + + ASSERT_EQ(config_->bypass_rules_.size(), 6u); + int i = 0; + for (std::vector<std::string>::iterator it = config_->bypass_rules_.begin(); + it != config_->bypass_rules_.end(); ++it) { + EXPECT_EQ(expected[i++], *it); + } +} + diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.cc b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.cc index c4cf7db..aa87a12 100644 --- a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.cc +++ b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.cc @@ -7,23 +7,23 @@ #include "base/android/build_info.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" -#include "base/base64.h" #include "base/bind.h" #include "base/command_line.h" +#include "base/memory/scoped_ptr.h" #include "base/metrics/histogram.h" #include "base/prefs/pref_member.h" #include "base/prefs/pref_service.h" -#include "base/prefs/scoped_user_pref_update.h" #include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.h" #include "chrome/browser/prefs/proxy_prefs.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_configurator.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h" #include "jni/DataReductionProxySettings_jni.h" #include "net/base/auth.h" #include "net/base/host_port_pair.h" @@ -32,14 +32,13 @@ #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_status.h" -#include "url/gurl.h" using base::android::CheckException; using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF16ToJavaString; using base::android::ConvertUTF8ToJavaString; using base::android::ScopedJavaLocalRef; -using base::StringPrintf; +using data_reduction_proxy::DataReductionProxySettings; namespace { @@ -55,21 +54,6 @@ enum { NUM_SPDY_PROXY_AUTH_STATE }; -// Generates a PAC proxy string component, including trailing semicolon and -// space, for |origin|. Eg: -// "http://foo.com/" -> "PROXY foo.com:80; " -// "https://bar.com:10443" -> "HTTPS bar.coom:10443; " -// The returned strings are suitable for concatenating into a PAC string. -// If |origin| is empty, returns an empty string. -std::string ProtocolAndHostForPACString(const std::string& origin) { - if (origin.empty()) { - return std::string(); - } - GURL url = GURL(origin); - std::string protocol = url.SchemeIsSecure() ? "HTTPS " : "PROXY "; - return protocol + net::HostPortPair::FromURL(url).ToString() + "; "; -} - } // namespace DataReductionProxySettingsAndroid::DataReductionProxySettingsAndroid( @@ -83,23 +67,25 @@ DataReductionProxySettingsAndroid::~DataReductionProxySettingsAndroid() {} void DataReductionProxySettingsAndroid::InitDataReductionProxySettings( JNIEnv* env, jobject obj) { - DataReductionProxySettings::InitDataReductionProxySettings(); + scoped_ptr<data_reduction_proxy::DataReductionProxyConfigurator> + configurator( + new DataReductionProxyChromeConfigurator( + ProfileManager::GetActiveUserProfile()->GetPrefs())); + DataReductionProxySettings::InitDataReductionProxySettings( + ProfileManager::GetActiveUserProfile()->GetPrefs(), + g_browser_process->local_state(), + ProfileManager::GetActiveUserProfile()->GetRequestContext(), + configurator.Pass()); } void DataReductionProxySettingsAndroid::BypassHostPattern( JNIEnv* env, jobject obj, jstring pattern) { - DataReductionProxySettings::AddHostPatternToBypass( + config()->AddHostPatternToBypass( ConvertJavaStringToUTF8(env, pattern)); } void DataReductionProxySettingsAndroid::BypassURLPattern( JNIEnv* env, jobject obj, jstring pattern) { - AddURLPatternToBypass(ConvertJavaStringToUTF8(env, pattern)); -} - -void DataReductionProxySettingsAndroid::AddURLPatternToBypass( - const std::string& pattern) { - pac_bypass_rules_.push_back( - StringPrintf("shExpMatch(%s, '%s')", "url", pattern.c_str())); + config()->AddURLPatternToBypass(ConvertJavaStringToUTF8(env, pattern)); } jboolean DataReductionProxySettingsAndroid::IsDataReductionProxyAllowed( @@ -148,7 +134,7 @@ DataReductionProxySettingsAndroid::GetContentLengths(JNIEnv* env, int64 received_content_length; int64 last_update_internal; DataReductionProxySettings::GetContentLengths( - spdyproxy::kNumDaysInHistorySummary, + data_reduction_proxy::kNumDaysInHistorySummary, &original_content_length, &received_content_length, &last_update_internal); @@ -189,13 +175,15 @@ DataReductionProxySettingsAndroid::GetTokenForAuthChallenge(JNIEnv* env, ScopedJavaLocalRef<jlongArray> DataReductionProxySettingsAndroid::GetDailyOriginalContentLengths( JNIEnv* env, jobject obj) { - return GetDailyContentLengths(env, prefs::kDailyHttpOriginalContentLength); + return GetDailyContentLengths( + env, data_reduction_proxy::prefs::kDailyHttpOriginalContentLength); } ScopedJavaLocalRef<jlongArray> DataReductionProxySettingsAndroid::GetDailyReceivedContentLengths( JNIEnv* env, jobject obj) { - return GetDailyContentLengths(env, prefs::kDailyHttpReceivedContentLength); + return GetDailyContentLengths( + env, data_reduction_proxy::prefs::kDailyHttpReceivedContentLength); } // static @@ -206,10 +194,9 @@ bool DataReductionProxySettingsAndroid::Register(JNIEnv* env) { void DataReductionProxySettingsAndroid::AddDefaultProxyBypassRules() { DataReductionProxySettings::AddDefaultProxyBypassRules(); - // Chrome cannot authenticate with the data reduction proxy when fetching URLs // from the settings menu. - AddURLPatternToBypass("http://www.google.com/policies/privacy*"); + config()->AddURLPatternToBypass("http://www.google.com/policies/privacy*"); } void DataReductionProxySettingsAndroid::SetProxyConfigs(bool enabled, @@ -220,47 +207,28 @@ void DataReductionProxySettingsAndroid::SetProxyConfigs(bool enabled, if (fallback.empty() && enabled && restricted) enabled = false; - // Keys duplicated from proxy_config_dictionary.cc - // TODO(bengr): Move these to proxy_config_dictionary.h and reuse them here. - const char kProxyMode[] = "mode"; - const char kProxyPacURL[] = "pac_url"; - const char kProxyBypassList[] = "bypass_list"; - LogProxyState(enabled, restricted, at_startup); - PrefService* prefs = GetOriginalProfilePrefs(); - DCHECK(prefs); - DictionaryPrefUpdate update(prefs, prefs::kProxy); - base::DictionaryValue* dict = update.Get(); if (enabled) { - // Convert to a data URI and update the PAC settings. - std::string base64_pac; - base::Base64Encode(GetProxyPacScript(restricted), &base64_pac); - - dict->SetString(kProxyPacURL, - "data:application/x-ns-proxy-autoconfig;base64," + - base64_pac); - dict->SetString(kProxyMode, - ProxyModeToString(ProxyPrefs::MODE_PAC_SCRIPT)); - dict->SetString(kProxyBypassList, JoinString(BypassRules(), ", ")); - + config()->Enable(restricted, + DataReductionProxySettings::GetDataReductionProxyOrigin(), + GetDataReductionProxyFallback()); } else { - dict->SetString(kProxyMode, ProxyModeToString(ProxyPrefs::MODE_SYSTEM)); - dict->SetString(kProxyPacURL, ""); - dict->SetString(kProxyBypassList, ""); + config()->Disable(); } } ScopedJavaLocalRef<jlongArray> DataReductionProxySettingsAndroid::GetDailyContentLengths( JNIEnv* env, const char* pref_name) { - jlongArray result = env->NewLongArray(spdyproxy::kNumDaysInHistory); + jlongArray result = env->NewLongArray( + data_reduction_proxy::kNumDaysInHistory); DataReductionProxySettings::ContentLengthList lengths = DataReductionProxySettings::GetDailyContentLengths(pref_name); if (!lengths.empty()) { - DCHECK_EQ(lengths.size(), spdyproxy::kNumDaysInHistory); + DCHECK_EQ(lengths.size(), data_reduction_proxy::kNumDaysInHistory); env->SetLongArrayRegion(result, 0, lengths.size(), &lengths[0]); return ScopedJavaLocalRef<jlongArray>(env, result); } @@ -268,34 +236,7 @@ DataReductionProxySettingsAndroid::GetDailyContentLengths( return ScopedJavaLocalRef<jlongArray>(env, result); } -// TODO(bengr): Replace with our own ProxyResolver. -std::string DataReductionProxySettingsAndroid::GetProxyPacScript( - bool restricted) { - // Compose the PAC-only bypass code; these will be URL patterns that - // are matched by regular expression. Host bypasses are handled outside - // of the PAC file using the regular proxy bypass list configs. - std::string bypass_clause = - "(" + JoinString(pac_bypass_rules_, ") || (") + ")"; - - // Generate a proxy PAC that falls back to direct loading when the proxy is - // unavailable and only process HTTP traffic. - - std::string proxy_host = ProtocolAndHostForPACString( - DataReductionProxySettings::GetDataReductionProxyOrigin()); - std::string fallback_host = ProtocolAndHostForPACString( - DataReductionProxySettings::GetDataReductionProxyFallback()); - std::string hosts = restricted ? fallback_host : proxy_host + fallback_host; - std::string pac = "function FindProxyForURL(url, host) {" - " if (" + bypass_clause + ") {" - " return 'DIRECT';" - " } " - " if (url.substring(0, 5) == 'http:') {" - " return '" + hosts + "DIRECT';" - " }" - " return 'DIRECT';" - "}"; - return pac; -} + // Used by generated jni code. static jlong Init(JNIEnv* env, jobject obj) { diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.h b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.h index a90b7fa..84cc758 100644 --- a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.h +++ b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.h @@ -13,7 +13,7 @@ #include "base/gtest_prod_util.h" #include "base/memory/scoped_ptr.h" #include "base/prefs/pref_member.h" -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h" using base::android::ScopedJavaLocalRef; @@ -22,7 +22,8 @@ using base::android::ScopedJavaLocalRef; // Central point for configuring the data reduction proxy on Android. // This object lives on the UI thread and all of its methods are expected to // be called from there. -class DataReductionProxySettingsAndroid : public DataReductionProxySettings { +class DataReductionProxySettingsAndroid + : public data_reduction_proxy::DataReductionProxySettings { public: DataReductionProxySettingsAndroid(JNIEnv* env, jobject obj); // Parameter-free constructor for C++ unit tests. @@ -39,8 +40,6 @@ class DataReductionProxySettingsAndroid : public DataReductionProxySettings { // the proxy is used. void BypassURLPattern(JNIEnv* env, jobject obj, jstring pattern); - virtual void AddURLPatternToBypass(const std::string& pattern) OVERRIDE; - // JNI wrapper interfaces to the indentically-named superclass methods. jboolean IsDataReductionProxyAllowed(JNIEnv* env, jobject obj); jboolean IsDataReductionProxyPromoAllowed(JNIEnv* env, jobject obj); @@ -89,18 +88,11 @@ class DataReductionProxySettingsAndroid : public DataReductionProxySettings { private: friend class DataReductionProxySettingsAndroidTest; FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsAndroidTest, - TestBypassPACRules); - FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsAndroidTest, - TestSetProxyPac); - FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsAndroidTest, TestGetDailyContentLengths); ScopedJavaLocalRef<jlongArray> GetDailyContentLengths(JNIEnv* env, const char* pref_name); - std::string GetProxyPacScript(bool restricted); - - std::vector<std::string> pac_bypass_rules_; DISALLOW_COPY_AND_ASSIGN(DataReductionProxySettingsAndroid); }; diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_ios.h b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_ios.h index be5bf42..1a8a914 100644 --- a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_ios.h +++ b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_ios.h @@ -5,12 +5,13 @@ #ifndef CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_SETTINGS_IOS_H_ #define CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_SETTINGS_IOS_H_ -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h" +#include "components/data_reduction_proxy/content/data_reduction_proxy_settings.h" // Central point for configuring the data reduction proxy on iOS. // This object lives on the UI thread and all of its methods are expected to // be called from there. -class DataReductionProxySettingsIOS : DataReductionProxySettings { +class DataReductionProxySettingsIOS + : data_reduction_proxy::DataReductionProxySettings { public: DataReductionProxySettingsIOS(); virtual ~DataReductionProxySettingsIOS() {} diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_unittest_android.cc b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_unittest_android.cc index faa83f0..0416461 100644 --- a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_unittest_android.cc +++ b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_unittest_android.cc @@ -2,36 +2,84 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings_unittest.h" +#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/base64.h" #include "base/command_line.h" -#include "base/metrics/field_trial.h" #include "base/prefs/pref_service.h" -#include "base/prefs/scoped_user_pref_update.h" -#include "base/prefs/testing_pref_service.h" -#include "base/strings/string_number_conversions.h" -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.h" #include "chrome/browser/prefs/proxy_prefs.h" #include "chrome/common/chrome_switches.h" -#include "chrome/common/metrics/variations/variations_util.h" #include "chrome/common/pref_names.h" -#include "components/variations/entropy_provider.h" -#include "net/url_request/test_url_fetcher_factory.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings_test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" +using testing::_; +using testing::AnyNumber; +using testing::Return; + const char kDataReductionProxyOrigin[] = "https://foo.com:443/"; -const char kDataReductionProxyDevHost[] = "http://foo-dev.com:80"; -const char kDataReductionProxyOriginPAC[] = "HTTPS foo.com:443;"; -const char kDataReductionProxyFallbackPAC[] = "PROXY bar.com:80;"; +const char kDataReductionProxyDev[] = "http://foo-dev.com:80"; + +template <class C> +void data_reduction_proxy::DataReductionProxySettingsTestBase::ResetSettings() { + MockDataReductionProxySettings<C>* settings = + new MockDataReductionProxySettings<C>; + EXPECT_CALL(*settings, GetOriginalProfilePrefs()) + .Times(AnyNumber()) + .WillRepeatedly(Return(&pref_service_)); + EXPECT_CALL(*settings, GetLocalStatePrefs()) + .Times(AnyNumber()) + .WillRepeatedly(Return(&pref_service_)); + EXPECT_CALL(*settings, GetURLFetcher()).Times(0); + EXPECT_CALL(*settings, LogProxyState(_, _, _)).Times(0); + settings_.reset(settings); +} + +template <class C> +void data_reduction_proxy::DataReductionProxySettingsTestBase::SetProbeResult( + const std::string& test_url, + const std::string& response, + ProbeURLFetchResult result, + bool success, + int expected_calls) { + MockDataReductionProxySettings<C>* settings = + static_cast<MockDataReductionProxySettings<C>*>(settings_.get()); + if (0 == expected_calls) { + EXPECT_CALL(*settings, GetURLFetcher()).Times(0); + EXPECT_CALL(*settings, RecordProbeURLFetchResult(_)).Times(0); + } else { + EXPECT_CALL(*settings, RecordProbeURLFetchResult(result)).Times(1); + EXPECT_CALL(*settings, GetURLFetcher()) + .Times(expected_calls) + .WillRepeatedly(Return(new net::FakeURLFetcher( + GURL(test_url), + settings, + response, + success ? net::HTTP_OK : net::HTTP_INTERNAL_SERVER_ERROR, + success ? net::URLRequestStatus::SUCCESS : + net::URLRequestStatus::FAILED))); + } +} + +template void +data_reduction_proxy::DataReductionProxySettingsTestBase::ResetSettings< + DataReductionProxySettingsAndroid>(); + +template void +data_reduction_proxy::DataReductionProxySettingsTestBase::SetProbeResult< + DataReductionProxySettingsAndroid>(const std::string& test_url, + const std::string& response, + ProbeURLFetchResult result, + bool success, + int expected_calls); class DataReductionProxySettingsAndroidTest - : public ConcreteDataReductionProxySettingsTest< + : public data_reduction_proxy::ConcreteDataReductionProxySettingsTest< DataReductionProxySettingsAndroid> { public: // DataReductionProxySettingsTest implementation: @@ -41,18 +89,6 @@ class DataReductionProxySettingsAndroidTest DataReductionProxySettingsTestBase::SetUp(); } - void CheckProxyPacPref(const std::string& expected_pac_url, - const std::string& expected_mode) { - const base::DictionaryValue* dict = - pref_service_.GetDictionary(prefs::kProxy); - std::string mode; - std::string pac_url; - dict->GetString("mode", &mode); - ASSERT_EQ(expected_mode, mode); - dict->GetString("pac_url", &pac_url); - ASSERT_EQ(expected_pac_url, pac_url); - } - DataReductionProxySettingsAndroid* Settings() { return static_cast<DataReductionProxySettingsAndroid*>(settings_.get()); } @@ -74,76 +110,31 @@ TEST_F(DataReductionProxySettingsAndroidTest, TestGetDataReductionProxyDevOrigin) { AddProxyToCommandLine(); CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kSpdyProxyDevAuthOrigin, kDataReductionProxyDevHost); + data_reduction_proxy::switches::kDataReductionProxyDev, + kDataReductionProxyDev); ScopedJavaLocalRef<jstring> result = Settings()->GetDataReductionProxyOrigin(env_, NULL); ASSERT_TRUE(result.obj()); const base::android::JavaRef<jstring>& str_ref = result; - EXPECT_EQ(kDataReductionProxyDevHost, ConvertJavaStringToUTF8(str_ref)); -} - -// Confirm that the bypass rule functions generate the intended JavaScript -// code for the Proxy PAC. -TEST_F(DataReductionProxySettingsAndroidTest, TestBypassPACRules) { - Settings()->AddURLPatternToBypass("http://foo.com/*"); - Settings()->AddHostPatternToBypass("bar.com"); - - EXPECT_EQ(Settings()->pac_bypass_rules_.size(), 1u); - EXPECT_EQ("shExpMatch(url, 'http://foo.com/*')", - Settings()->pac_bypass_rules_[0]); - - EXPECT_EQ(Settings()->BypassRules().size(), 1u); - EXPECT_EQ("bar.com", Settings()->BypassRules()[0]); -} - -TEST_F(DataReductionProxySettingsAndroidTest, TestSetProxyPac) { - AddProxyToCommandLine(); - Settings()->AddDefaultProxyBypassRules(); - - // First check without restriction. - std::string raw_pac = Settings()->GetProxyPacScript(false); - EXPECT_NE(raw_pac.find(kDataReductionProxyOriginPAC), std::string::npos); - EXPECT_NE(raw_pac.find(kDataReductionProxyFallbackPAC), std::string::npos); - std::string pac; - base::Base64Encode(raw_pac, &pac); - std::string expected_pac_url = - "data:application/x-ns-proxy-autoconfig;base64," + pac; - Settings()->SetProxyConfigs(true, false, false); - CheckProxyPacPref(expected_pac_url, - ProxyModeToString(ProxyPrefs::MODE_PAC_SCRIPT)); - - // Now check with restriction. - raw_pac = Settings()->GetProxyPacScript(true); - // Primary proxy origin should not appear. - EXPECT_EQ(raw_pac.find(kDataReductionProxyOriginPAC), std::string::npos); - EXPECT_NE(raw_pac.find(kDataReductionProxyFallbackPAC), std::string::npos); - base::Base64Encode(raw_pac, &pac); - expected_pac_url = "data:application/x-ns-proxy-autoconfig;base64," + pac; - Settings()->SetProxyConfigs(true, true, false); - CheckProxyPacPref(expected_pac_url, - ProxyModeToString(ProxyPrefs::MODE_PAC_SCRIPT)); - - Settings()->SetProxyConfigs(false, false, false); - CheckProxyPacPref(std::string(), ProxyModeToString(ProxyPrefs::MODE_SYSTEM)); - - // Restriction is irrelevant when the proxy is disabled. - Settings()->SetProxyConfigs(false, false, false); - CheckProxyPacPref(std::string(), ProxyModeToString(ProxyPrefs::MODE_SYSTEM)); + EXPECT_EQ(kDataReductionProxyDev, ConvertJavaStringToUTF8(str_ref)); } TEST_F(DataReductionProxySettingsAndroidTest, TestGetDailyContentLengths) { ScopedJavaLocalRef<jlongArray> result = Settings()->GetDailyContentLengths( - env_, prefs::kDailyHttpOriginalContentLength); + env_, data_reduction_proxy::prefs::kDailyHttpOriginalContentLength); ASSERT_TRUE(result.obj()); jsize java_array_len = env_->GetArrayLength(result.obj()); - ASSERT_EQ(static_cast<jsize>(spdyproxy::kNumDaysInHistory), java_array_len); + ASSERT_EQ(static_cast<jsize>(data_reduction_proxy::kNumDaysInHistory), + java_array_len); jlong value; - for (size_t i = 0; i < spdyproxy::kNumDaysInHistory; ++i) { + for (size_t i = 0; i < data_reduction_proxy::kNumDaysInHistory; ++i) { env_->GetLongArrayRegion(result.obj(), i, 1, &value); ASSERT_EQ( - static_cast<long>((spdyproxy::kNumDaysInHistory - 1 - i) * 2), value); + static_cast<long>( + (data_reduction_proxy::kNumDaysInHistory - 1 - i) * 2), + value); } } diff --git a/chrome/browser/net/spdyproxy/proxy_advisor.cc b/chrome/browser/net/spdyproxy/proxy_advisor.cc index 877d409..f15851a 100644 --- a/chrome/browser/net/spdyproxy/proxy_advisor.cc +++ b/chrome/browser/net/spdyproxy/proxy_advisor.cc @@ -9,9 +9,9 @@ #include "base/memory/scoped_ptr.h" #include "base/prefs/pref_service.h" #include "base/stl_util.h" -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h" #include "content/public/browser/browser_thread.h" #include "net/base/load_flags.h" #include "net/base/request_priority.h" @@ -27,6 +27,7 @@ #endif using content::BrowserThread; +using data_reduction_proxy::DataReductionProxySettings; namespace { const char kOmniboxMotivation[] = "omnibox"; @@ -77,7 +78,9 @@ ProxyAdvisor::ProxyAdvisor(PrefService* pref_service, // pref_service may be null in mock test subclasses. if (pref_service) { - proxy_pref_member_.Init(prefs::kSpdyProxyAuthEnabled, pref_service, + proxy_pref_member_.Init( + data_reduction_proxy::prefs::kDataReductionProxyEnabled, + pref_service, base::Bind(&ProxyAdvisor::UpdateProxyState, base::Unretained(this))); proxy_pref_member_.MoveToThread( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)); diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 71ac801..3328588 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc @@ -467,7 +467,7 @@ const PolicyToPreferenceMapEntry kSimplePolicyMap[] = { #if defined(OS_ANDROID) { key::kDataCompressionProxyEnabled, - prefs::kSpdyProxyAuthEnabled, + data_reduction_proxy::prefs::kDataReductionProxyEnabled, base::Value::TYPE_BOOLEAN }, #endif // defined(OS_ANDROID) diff --git a/chrome/browser/prefs/command_line_pref_store.cc b/chrome/browser/prefs/command_line_pref_store.cc index f2d6855..9c854d8 100644 --- a/chrome/browser/prefs/command_line_pref_store.cc +++ b/chrome/browser/prefs/command_line_pref_store.cc @@ -28,7 +28,8 @@ const CommandLinePrefStore::StringSwitchToPreferenceMapEntry { switches::kAuthNegotiateDelegateWhitelist, prefs::kAuthNegotiateDelegateWhitelist }, { switches::kGSSAPILibraryName, prefs::kGSSAPILibraryName }, - { switches::kSpdyProxyAuthOrigin, prefs::kSpdyProxyAuthOrigin }, + { data_reduction_proxy::switches::kDataReductionProxy, + data_reduction_proxy::prefs::kDataReductionProxy }, { switches::kDiskCacheDir, prefs::kDiskCacheDir }, { switches::kSSLVersionMin, prefs::kSSLVersionMin }, { switches::kSSLVersionMax, prefs::kSSLVersionMax }, diff --git a/chrome/browser/profiles/profile.cc b/chrome/browser/profiles/profile.cc index bfede92..846eb95 100644 --- a/chrome/browser/profiles/profile.cc +++ b/chrome/browser/profiles/profile.cc @@ -159,11 +159,11 @@ void Profile::RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { #endif #if defined(OS_ANDROID) || defined(OS_IOS) registry->RegisterBooleanPref( - prefs::kSpdyProxyAuthEnabled, + data_reduction_proxy::prefs::kDataReductionProxyEnabled, false, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterBooleanPref( - prefs::kSpdyProxyAuthWasEnabledBefore, + data_reduction_proxy::prefs::kDataReductionProxyWasEnabledBefore, false, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); #endif // defined(OS_ANDROID) || defined(OS_IOS) diff --git a/chrome/browser/profiles/profile_impl_io_data.cc b/chrome/browser/profiles/profile_impl_io_data.cc index 9af2b75..538604e 100644 --- a/chrome/browser/profiles/profile_impl_io_data.cc +++ b/chrome/browser/profiles/profile_impl_io_data.cc @@ -49,7 +49,7 @@ #include "webkit/browser/quota/special_storage_policy.h" #if defined(OS_ANDROID) || defined(OS_IOS) -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h" #endif namespace { @@ -462,8 +462,8 @@ void ProfileImplIOData::InitializeInternal( main_cache->InitializeInfiniteCache(lazy_params_->infinite_cache_path); #if defined(OS_ANDROID) || defined(OS_IOS) - DataReductionProxySettings::InitDataReductionProxySession( - main_cache->GetSession()); + data_reduction_proxy::DataReductionProxySettings:: + InitDataReductionProxySession(main_cache->GetSession()); #endif if (chrome_browser_net::ShouldUseInMemoryCookiesAndCache()) { diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi index 4ea7509..3ee13aa 100644 --- a/chrome/chrome_browser.gypi +++ b/chrome/chrome_browser.gypi @@ -29,6 +29,7 @@ 'suggestions_proto', '../components/components.gyp:autofill_core_browser', '../components/components.gyp:cloud_devices', + '../components/components.gyp:data_reduction_proxy_browser', '../components/components.gyp:domain_reliability', '../components/components.gyp:favicon_core', '../components/components.gyp:navigation_metrics', @@ -1338,16 +1339,12 @@ 'browser/net/sdch_dictionary_fetcher.h', 'browser/net/service_providers_win.cc', 'browser/net/service_providers_win.h', - 'browser/net/spdyproxy/data_reduction_proxy_settings.cc', - 'browser/net/spdyproxy/data_reduction_proxy_settings.h', + 'browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.cc', + 'browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.h', 'browser/net/spdyproxy/data_reduction_proxy_settings_android.cc', 'browser/net/spdyproxy/data_reduction_proxy_settings_android.h', 'browser/net/spdyproxy/data_reduction_proxy_settings_ios.cc', 'browser/net/spdyproxy/data_reduction_proxy_settings_ios.h', - 'browser/net/spdyproxy/data_saving_metrics.cc', - 'browser/net/spdyproxy/data_saving_metrics.h', - 'browser/net/spdyproxy/http_auth_handler_spdyproxy.cc', - 'browser/net/spdyproxy/http_auth_handler_spdyproxy.h', 'browser/net/spdyproxy/proxy_advisor.cc', 'browser/net/spdyproxy/proxy_advisor.h', 'browser/net/sqlite_server_bound_cert_store.cc', diff --git a/chrome/chrome_tests_unit.gypi b/chrome/chrome_tests_unit.gypi index ab36376..8754df9 100644 --- a/chrome/chrome_tests_unit.gypi +++ b/chrome/chrome_tests_unit.gypi @@ -1095,11 +1095,8 @@ 'browser/net/pref_proxy_config_tracker_impl_unittest.cc', 'browser/net/probe_message_unittest.cc', 'browser/net/proxy_policy_handler_unittest.cc', - 'browser/net/spdyproxy/data_reduction_proxy_settings_unittest.cc', - 'browser/net/spdyproxy/data_reduction_proxy_settings_unittest.h', + 'browser/net/spdyproxy/data_reduction_proxy_chrome_configurator_unittest.cc', 'browser/net/spdyproxy/data_reduction_proxy_settings_unittest_android.cc', - 'browser/net/spdyproxy/data_saving_metrics_unittest.cc', - 'browser/net/spdyproxy/http_auth_handler_spdyproxy_unittest.cc', 'browser/net/sqlite_server_bound_cert_store_unittest.cc', 'browser/net/ssl_config_service_manager_pref_unittest.cc', 'browser/net/url_info_unittest.cc', @@ -1971,6 +1968,7 @@ ['OS!="ios"', { 'dependencies': [ '../components/components.gyp:autofill_content_test_support', + '../components/components.gyp:data_reduction_proxy_test_support', '../components/components_strings.gyp:components_strings', '../device/bluetooth/bluetooth.gyp:device_bluetooth_mocks', '../gpu/gpu.gyp:gpu_unittest_utils', diff --git a/chrome/common/DEPS b/chrome/common/DEPS index 7496e08..2ecbccd 100644 --- a/chrome/common/DEPS +++ b/chrome/common/DEPS @@ -5,6 +5,7 @@ include_rules = [ "+components/autofill/content/common", "+components/autofill/core/common", "+components/bookmarks/core/common", + "+components/data_reduction_proxy/common", "+components/nacl/common", "+components/password_manager/core/common", "+components/policy/core/common", diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc index 906d573..2c56c35 100644 --- a/chrome/common/chrome_switches.cc +++ b/chrome/common/chrome_switches.cc @@ -204,12 +204,6 @@ const char kCrashOnHangThreads[] = "crash-on-hang-threads"; const char kCreateBrowserOnStartupForTests[] = "create-browser-on-startup-for-tests"; -#if defined(OS_ANDROID) || defined(OS_IOS) -// If set, the data reduction proxy will only be enabled if a request for this -// URL is successful. -const char kDataReductionProxyProbeURL[] = "data-reduction-proxy-probe-url"; -#endif - // Enables a frame context menu item that toggles the frame in and out of glass // mode (Windows Vista and up only). const char kDebugEnableFrameToggle[] = "debug-enable-frame-toggle"; @@ -1191,21 +1185,6 @@ const char kSimulateOutdated[] = "simulate-outdated"; // Simulates that current version is outdated and auto-update is off. const char kSimulateOutdatedNoAU[] = "simulate-outdated-no-au"; -// Replaces the buffered data source for <audio> and <video> with a simplified -// resource loader that downloads the entire resource into memory. - -// Second origin that can be used for the spdy proxy. -const char kSpdyProxyAuthFallback[] = "spdy-proxy-auth-fallback"; - -// Origin for which SpdyProxy authentication is supported. -const char kSpdyProxyAuthOrigin[] = "spdy-proxy-auth-origin"; - -// Authentication string for the data reduction proxy. -const char kSpdyProxyAuthValue[] = "spdy-proxy-auth-value"; - -// Origin for which dev version of SpdyProxy authentication is supported. -const char kSpdyProxyDevAuthOrigin[] = "spdy-proxy-dev-auth-origin"; - // Specifies the URL where spelling service feedback data will be sent instead // of the default URL. This switch is for temporary testing only. // TODO(rouslan): Remove this flag when feedback testing is complete. Revisit by @@ -1350,11 +1329,6 @@ const char kWinHttpProxyResolver[] = "winhttp-proxy-resolver"; const char kPluginsMetadataServerURL[] = "plugins-metadata-server-url"; #endif -#if defined(OS_ANDROID) || defined(OS_IOS) -// Enable SPDY proxy. -const char kEnableSpdyProxyAuth[] = "enable-spdy-proxy-auth"; -#endif // defined(OS_ANDROID) || defined(OS_IOS) - #if defined(OS_ANDROID) // Disables the app banner <meta> tag. const char kDisableAppBanners[] = "disable-app-banners"; diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h index 3c18165..358d597 100644 --- a/chrome/common/chrome_switches.h +++ b/chrome/common/chrome_switches.h @@ -11,6 +11,7 @@ #include "base/base_switches.h" #include "components/autofill/core/common/autofill_switches.h" +#include "components/data_reduction_proxy/common/data_reduction_proxy_switches.h" #include "components/password_manager/core/common/password_manager_switches.h" #include "components/signin/core/common/signin_switches.h" #include "content/public/common/content_switches.h" @@ -66,9 +67,6 @@ extern const char kComponentUpdater[]; extern const char kConflictingModulesCheck[]; extern const char kCrashOnHangThreads[]; extern const char kCreateBrowserOnStartupForTests[]; -#if defined(OS_ANDROID) || defined(OS_IOS) -extern const char kDataReductionProxyProbeURL[]; -#endif extern const char kDebugEnableFrameToggle[]; extern const char kDebugPackedApps[]; extern const char kDiagnostics[]; @@ -324,10 +322,6 @@ extern const char kSimulateUpgrade[]; extern const char kSimulateCriticalUpdate[]; extern const char kSimulateOutdated[]; extern const char kSimulateOutdatedNoAU[]; -extern const char kSpdyProxyAuthFallback[]; -extern const char kSpdyProxyAuthOrigin[]; -extern const char kSpdyProxyAuthValue[]; -extern const char kSpdyProxyDevAuthOrigin[]; extern const char kSpellingServiceFeedbackUrl[]; extern const char kSpellingServiceFeedbackIntervalSeconds[]; extern const char kSSLVersionMax[]; @@ -370,10 +364,6 @@ extern const char kWinHttpProxyResolver[]; extern const char kPluginsMetadataServerURL[]; #endif -#if defined(OS_ANDROID) || defined(OS_IOS) -extern const char kEnableSpdyProxyAuth[]; -#endif // defined(OS_ANDROID) || defined(OS_IOS) - #if defined(OS_ANDROID) extern const char kDisableAppBanners[]; extern const char kDisableCast[]; diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index 8a5e781..807d09f 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc @@ -1794,12 +1794,6 @@ const char kDevToolsPortForwardingConfig[] = "devtools.port_forwarding_config"; const char kDevToolsRemoteEnabled[] = "devtools.remote_enabled"; #endif -#if defined(OS_ANDROID) || defined(OS_IOS) -// A boolean specifying whether a SPDY proxy is enabled. -const char kSpdyProxyAuthEnabled[] = "spdy_proxy.enabled"; -const char kSpdyProxyAuthWasEnabledBefore[] = "spdy_proxy.was_enabled_before"; -#endif // defined(OS_ANDROID) || defined(OS_IOS) - // An ID to uniquely identify this client to the invalidator service. const char kInvalidatorClientId[] = "invalidator.client_id"; @@ -1929,10 +1923,6 @@ const char kAuthNegotiateDelegateWhitelist[] = // String that specifies the name of a custom GSSAPI library to load. const char kGSSAPILibraryName[] = "auth.gssapi_library_name"; -// String that specifies the origin allowed to use SpdyProxy -// authentication, if any. -const char kSpdyProxyAuthOrigin[] = "auth.spdyproxy.origin"; - // Boolean that specifies whether to allow basic auth prompting on cross- // domain sub-content requests. const char kAllowCrossOriginAuthPrompt[] = "auth.allow_cross_origin_prompt"; @@ -1940,64 +1930,6 @@ const char kAllowCrossOriginAuthPrompt[] = "auth.allow_cross_origin_prompt"; // Boolean that specifies whether the built-in asynchronous DNS client is used. const char kBuiltInDnsClientEnabled[] = "async_dns.enabled"; -// An int64 pref that contains the total size of all HTTP content that has been -// received from the network. -const char kHttpReceivedContentLength[] = "http_received_content_length"; - -// An int64 pref that contains the total original size of all HTTP content that -// was received over the network. -const char kHttpOriginalContentLength[] = "http_original_content_length"; - -#if defined(OS_ANDROID) || defined(OS_IOS) -// A List pref that contains daily totals of the original size of all HTTP/HTTPS -// that was received from the network. -const char kDailyHttpOriginalContentLength[] = - "data_reduction.daily_original_length"; - -// A List pref that contains daily totals of the size of all HTTP/HTTPS content -// that was received from the network. -const char kDailyHttpReceivedContentLength[] = - "data_reduction.daily_received_length"; - -// A List pref that contains daily totals of the original size of all HTTP/HTTPS -// that was received while the data reduction proxy is enabled. -const char kDailyOriginalContentLengthWithDataReductionProxyEnabled[] = - "data_reduction.daily_original_length_with_data_reduction_proxy_enabled"; - -// A List pref that contains daily totals of the size of all HTTP/HTTPS -// that was received while the data reduction proxy is enabled. -const char kDailyContentLengthWithDataReductionProxyEnabled[] = - "data_reduction.daily_received_length_with_data_reduction_proxy_enabled"; - -const char kDailyContentLengthHttpsWithDataReductionProxyEnabled[] = - "data_reduction.daily_received_length_https_with_" - "data_reduction_proxy_enabled"; -const char kDailyContentLengthShortBypassWithDataReductionProxyEnabled[] = - "data_reduction.daily_received_length_short_bypass_with_" - "data_reduction_proxy_enabled"; -const char kDailyContentLengthLongBypassWithDataReductionProxyEnabled[] = - "data_reduction.daily_received_length_long_bypass_with_" - "data_reduction_proxy_enabled"; -const char kDailyContentLengthUnknownWithDataReductionProxyEnabled[] = - "data_reduction.daily_received_length_unknown_with_" - "data_reduction_proxy_enabled"; - -// A List pref that contains daily totals of the original size of all HTTP/HTTPS -// that was received via the data reduction proxy. -const char kDailyOriginalContentLengthViaDataReductionProxy[] = - "data_reduction.daily_original_length_via_data_reduction_proxy"; - -// A List pref that contains daily totals of the size of all HTTP/HTTPS -// that was received via the data reduction proxy. -const char kDailyContentLengthViaDataReductionProxy[] = - "data_reduction.daily_received_length_via_data_reduction_proxy"; - -// An int64 pref that contains an internal representation of midnight on the -// date of the last update to |kDailyHttp{Original,Received}ContentLength|. -const char kDailyHttpContentLengthLastUpdateDate[] = - "data_reduction.last_update_date"; -#endif // defined(OS_ANDROID) || defined(OS_IOS) - // A pref holding the value of the policy used to explicitly allow or deny // access to audio capture devices. When enabled or not set, the user is // prompted for device access. When disabled, access to audio capture devices diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index 5da9a11..94cee34 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h @@ -13,6 +13,7 @@ #include "components/autofill/core/common/autofill_pref_names.h" #include "components/bookmarks/core/common/bookmark_pref_names.h" +#include "components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h" #include "components/signin/core/common/signin_pref_names.h" namespace prefs { @@ -589,11 +590,6 @@ extern const char kDevToolsPortForwardingConfig[]; #if defined(OS_ANDROID) extern const char kDevToolsRemoteEnabled[]; #endif -#if defined(OS_ANDROID) || defined(OS_IOS) -// Used by Chrome Mobile. -extern const char kSpdyProxyAuthEnabled[]; -extern const char kSpdyProxyAuthWasEnabledBefore[]; -#endif // defined(OS_ANDROID) || defined(OS_IOS) extern const char kGoogleServicesPasswordHash[]; @@ -747,27 +743,10 @@ extern const char kEnableAuthNegotiatePort[]; extern const char kAuthServerWhitelist[]; extern const char kAuthNegotiateDelegateWhitelist[]; extern const char kGSSAPILibraryName[]; -extern const char kSpdyProxyAuthOrigin[]; extern const char kAllowCrossOriginAuthPrompt[]; extern const char kBuiltInDnsClientEnabled[]; -extern const char kHttpReceivedContentLength[]; -extern const char kHttpOriginalContentLength[]; -#if defined(OS_ANDROID) || defined(OS_IOS) -extern const char kDailyHttpOriginalContentLength[]; -extern const char kDailyHttpReceivedContentLength[]; -extern const char kDailyOriginalContentLengthWithDataReductionProxyEnabled[]; -extern const char kDailyContentLengthWithDataReductionProxyEnabled[]; -extern const char kDailyContentLengthHttpsWithDataReductionProxyEnabled[]; -extern const char kDailyContentLengthShortBypassWithDataReductionProxyEnabled[]; -extern const char kDailyContentLengthLongBypassWithDataReductionProxyEnabled[]; -extern const char kDailyContentLengthUnknownWithDataReductionProxyEnabled[]; -extern const char kDailyOriginalContentLengthViaDataReductionProxy[]; -extern const char kDailyContentLengthViaDataReductionProxy[]; -extern const char kDailyHttpContentLengthLastUpdateDate[]; -#endif - extern const char kRegisteredProtocolHandlers[]; extern const char kIgnoredProtocolHandlers[]; extern const char kCustomHandlersEnabled[]; diff --git a/chrome/renderer/page_load_histograms.cc b/chrome/renderer/page_load_histograms.cc index 7ff0c9c..87a9252 100644 --- a/chrome/renderer/page_load_histograms.cc +++ b/chrome/renderer/page_load_histograms.cc @@ -215,7 +215,7 @@ bool DataReductionProxyWasUsed(WebFrame* frame) { std::replace(headers.begin(), headers.end(), '\n', '\0'); scoped_refptr<net::HttpResponseHeaders> response_headers( new net::HttpResponseHeaders(headers)); - return response_headers->IsChromeProxyResponse(); + return response_headers->IsDataReductionProxyResponse(); #else return false; #endif diff --git a/components/OWNERS b/components/OWNERS index d63cd4a..af4446c 100644 --- a/components/OWNERS +++ b/components/OWNERS @@ -16,6 +16,10 @@ per-file bookmarks*=blundell@chromium.org # Temporary for the duration of the bookmarks componentization. per-file bookmarks*=droger@chromium.org +per-file chrome_proxy*=bengr@chromium.org +per-file chrome_proxy*=marq@chromium.org +per-file chrome_proxy*=bolian@chromium.org + per-file cloud_devices*=gene@chromium.org per-file cloud_devices*=noamsml@chromium.org per-file cloud_devices*=vitalybuka@chromium.org diff --git a/components/components.gyp b/components/components.gyp index c51d286..b39b8e0 100644 --- a/components/components.gyp +++ b/components/components.gyp @@ -16,6 +16,7 @@ 'breakpad.gypi', 'cloud_devices.gypi', 'cronet.gypi', + 'data_reduction_proxy.gypi', 'dom_distiller.gypi', 'domain_reliability.gypi', 'favicon.gypi', diff --git a/components/components_tests.gyp b/components/components_tests.gyp index 6d1a4b1..fa07896 100644 --- a/components/components_tests.gyp +++ b/components/components_tests.gyp @@ -65,6 +65,9 @@ 'autofill/core/common/password_form_fill_data_unittest.cc', 'autofill/core/common/save_password_progress_logger_unittest.cc', 'cloud_devices/printer_description_unittest.cc', + 'data_reduction_proxy/browser/data_reduction_proxy_metrics_unittest.cc', + 'data_reduction_proxy/browser/data_reduction_proxy_settings_unittest.cc', + 'data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy_unittest.cc', 'dom_distiller/core/article_entry_unittest.cc', 'dom_distiller/core/distiller_unittest.cc', 'dom_distiller/core/distiller_url_fetcher_unittest.cc', @@ -185,6 +188,11 @@ # Dependencies of cloud_devices 'components.gyp:cloud_devices', + # Dependencies of data_reduction_proxy + 'components.gyp:data_reduction_proxy_browser', + 'components.gyp:data_reduction_proxy_common', + 'components.gyp:data_reduction_proxy_test_support', + # Dependencies of dom_distiller 'components.gyp:distilled_page_proto', 'components.gyp:dom_distiller_core', diff --git a/components/data_reduction_proxy.gypi b/components/data_reduction_proxy.gypi new file mode 100644 index 0000000..ed6e878 --- /dev/null +++ b/components/data_reduction_proxy.gypi @@ -0,0 +1,67 @@ +# Copyright 2014 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + + +{ + 'targets': [ + { + 'target_name': 'data_reduction_proxy_browser', + 'type': 'static_library', + 'dependencies': [ + 'data_reduction_proxy_common', + '../base/base.gyp:base', + '../crypto/crypto.gyp:crypto', + '../net/net.gyp:net', + ], + 'include_dirs': [ + '..', + ], + 'sources': [ + 'data_reduction_proxy/browser/data_reduction_proxy_configurator.h', + 'data_reduction_proxy/browser/data_reduction_proxy_metrics.cc', + 'data_reduction_proxy/browser/data_reduction_proxy_metrics.h', + 'data_reduction_proxy/browser/data_reduction_proxy_settings.cc', + 'data_reduction_proxy/browser/data_reduction_proxy_settings.h', + 'data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy.cc', + 'data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy.h', + ], + }, + { + 'target_name': 'data_reduction_proxy_common', + 'type': 'static_library', + 'dependencies': [ + '../base/base.gyp:base', + ], + 'include_dirs': [ + '..', + ], + 'sources': [ + 'data_reduction_proxy/common/data_reduction_proxy_pref_names.cc', + 'data_reduction_proxy/common/data_reduction_proxy_pref_names.h', + 'data_reduction_proxy/common/data_reduction_proxy_switches.cc', + 'data_reduction_proxy/common/data_reduction_proxy_switches.h', + ], + }, + { + 'target_name': 'data_reduction_proxy_test_support', + 'type': 'static_library', + 'dependencies' : [ + 'data_reduction_proxy_browser', + 'data_reduction_proxy_common', + '../base/base.gyp:base', + '../net/net.gyp:net', + '../testing/gmock.gyp:gmock', + '../testing/gtest.gyp:gtest', + ], + 'include_dirs': [ + '..', + ], + 'sources': [ + 'data_reduction_proxy/browser/data_reduction_proxy_settings_test_utils.cc', + 'data_reduction_proxy/browser/data_reduction_proxy_settings_test_utils.h', + ], + }, + ], +} + diff --git a/components/data_reduction_proxy/DEPS b/components/data_reduction_proxy/DEPS new file mode 100644 index 0000000..a9486c4 --- /dev/null +++ b/components/data_reduction_proxy/DEPS @@ -0,0 +1,6 @@ +include_rules = [ + "+crypto", + "+net", + # Data reduction proxy is used by iOS, which does not use content. + "-content", +] diff --git a/components/data_reduction_proxy/OWNERS b/components/data_reduction_proxy/OWNERS new file mode 100644 index 0000000..6a63b53 --- /dev/null +++ b/components/data_reduction_proxy/OWNERS @@ -0,0 +1,3 @@ +bengr@chromium.org +bolian@chromium.org +marq@chromium.org diff --git a/components/data_reduction_proxy/README b/components/data_reduction_proxy/README new file mode 100644 index 0000000..0a8e069 --- /dev/null +++ b/components/data_reduction_proxy/README @@ -0,0 +1,7 @@ +The Data Reduction Proxy component contains code for a configuring and using +the data reduction proxy. The Data Reduction proxy is not allowed to depend +on content/, because it is used by iOS. If dependencies on content/ need to be +added to the Data Reduction Proxy, it will have to be make into a layered +component. See +http://www.chromium.org/developers/design-documents/layered-components-design +for more information. diff --git a/components/data_reduction_proxy/browser/data_reduction_proxy_configurator.h b/components/data_reduction_proxy/browser/data_reduction_proxy_configurator.h new file mode 100644 index 0000000..7f66e11 --- /dev/null +++ b/components/data_reduction_proxy/browser/data_reduction_proxy_configurator.h @@ -0,0 +1,49 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_CONFIGURATOR_H_ +#define COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_CONFIGURATOR_H_ + +#include <string> + +#include "base/macros.h" + +namespace data_reduction_proxy { + +// Interface for enabling and disabling the data reduction proxy configuration, +// and for adding bypass rules. This is the interface that is used to set the +// networking configuration that causes traffic to be proxied. +class DataReductionProxyConfigurator { + public: + DataReductionProxyConfigurator() {} + virtual ~DataReductionProxyConfigurator() {} + + // Enable the data reduction proxy. If |restricted|, only the fallback_origin + // will be used. + virtual void Enable(bool restricted, + const std::string& primary_origin, + const std::string& fallback_origin) = 0; + + // Disable the data reduction proxy. + virtual void Disable() = 0; + + // Adds a host pattern to bypass. This should follow the same syntax used + // in net::ProxyBypassRules; that is, a hostname pattern, a hostname suffix + // pattern, an IP literal, a CIDR block, or the magic string '<local>'. + // Bypass settings persist for the life of this object and are applied + // each time the proxy is enabled, but are not updated while it is enabled. + virtual void AddHostPatternToBypass(const std::string& pattern) = 0; + + // Adds a URL pattern to bypass the proxy. The base implementation strips + // everything in |pattern| after the first single slash and then treats it + // as a hostname pattern. + virtual void AddURLPatternToBypass(const std::string& pattern) = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(DataReductionProxyConfigurator); +}; + +} // namespace data_reduction_proxy + +#endif // COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_CONFIGURATOR_H_ diff --git a/chrome/browser/net/spdyproxy/data_saving_metrics.cc b/components/data_reduction_proxy/browser/data_reduction_proxy_metrics.cc index ed4ff02..f673a20 100644 --- a/chrome/browser/net/spdyproxy/data_saving_metrics.cc +++ b/components/data_reduction_proxy/browser/data_reduction_proxy_metrics.cc @@ -1,23 +1,24 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/net/spdyproxy/data_saving_metrics.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_metrics.h" #include "base/metrics/histogram.h" #include "base/prefs/pref_service.h" #include "base/prefs/scoped_user_pref_update.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h" -#include "chrome/common/pref_names.h" -#include "content/public/common/url_constants.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h" +#include "components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h" #include "net/base/host_port_pair.h" #include "net/http/http_response_headers.h" #include "net/proxy/proxy_retry_info.h" #include "net/proxy/proxy_service.h" #include "net/url_request/url_request_context.h" +namespace data_reduction_proxy { + namespace { // A bypass delay more than this is treated as a long delay. @@ -25,9 +26,6 @@ const int kLongBypassDelayInSeconds = 30 * 60; #if defined(OS_ANDROID) || defined(OS_IOS) -// The number of days of history stored in the content lengths prefs. -const size_t kNumDaysInHistory = 60; - // Increments an int64, stored as a string, in a ListPref at the specified // index. The value must already exist and be a string representation of a // number. @@ -328,8 +326,8 @@ bool IsBypassRequest(const net::URLRequest* request, int64* delay_seconds) { for (size_t i = 0; i < proxies.size(); ++i) { std::string proxy = net::HostPortPair::FromURL(proxies[i]).ToString(); // The retry list has the scheme prefix for https but not for http. - if (proxies[i].SchemeIs(content::kHttpsScheme)) - proxy = std::string(content::kHttpsScheme) + "://" + proxy; + if (proxies[i].SchemeIs("https")) + proxy = std::string("https://") + proxy; net::ProxyRetryInfoMap::const_iterator found = retry_map.find(proxy); if (found == retry_map.end()) @@ -349,13 +347,11 @@ bool IsBypassRequest(const net::URLRequest* request, int64* delay_seconds) { } // namespace -namespace spdyproxy { - -DataReductionRequestType GetDataReductionRequestType( +DataReductionProxyRequestType GetDataReductionProxyRequestType( const net::URLRequest* request) { - if (request->url().SchemeIs(content::kHttpsScheme)) + if (request->url().SchemeIs("https")) return HTTPS; - if (!request->url().SchemeIs(content::kHttpScheme)) { + if (!request->url().SchemeIs("http")) { NOTREACHED(); return UNKNOWN_TYPE; } @@ -366,7 +362,7 @@ DataReductionRequestType GetDataReductionRequestType( } #if defined(SPDY_PROXY_AUTH_ORIGIN) if (request->response_info().headers && - request->response_info().headers->IsChromeProxyResponse()) { + request->response_info().headers->IsDataReductionProxyResponse()) { return VIA_DATA_REDUCTION_PROXY; } #endif @@ -374,13 +370,13 @@ DataReductionRequestType GetDataReductionRequestType( } int64 GetAdjustedOriginalContentLength( - DataReductionRequestType data_reduction_type, + DataReductionProxyRequestType request_type, int64 original_content_length, int64 received_content_length) { // Since there was no indication of the original content length, presume // it is no different from the number of bytes read. if (original_content_length == -1 || - data_reduction_type != spdyproxy::VIA_DATA_REDUCTION_PROXY) { + request_type != VIA_DATA_REDUCTION_PROXY) { return received_content_length; } return original_content_length; @@ -391,7 +387,7 @@ void UpdateContentLengthPrefsForDataReductionProxy( int received_content_length, int original_content_length, bool with_data_reduction_proxy_enabled, - DataReductionRequestType data_reduction_type, + DataReductionProxyRequestType request_type, base::Time now, PrefService* prefs) { // TODO(bengr): Remove this check once the underlying cause of // http://crbug.com/287821 is fixed. For now, only continue if the current @@ -406,7 +402,7 @@ void UpdateContentLengthPrefsForDataReductionProxy( // Determine how many days it has been since the last update. int64 then_internal = prefs->GetInt64( - prefs::kDailyHttpContentLengthLastUpdateDate); + data_reduction_proxy::prefs::kDailyHttpContentLengthLastUpdateDate); // Local midnight could have been shifted due to time zone change. base::Time then_midnight = base::Time::FromInternalValue(then_internal).LocalMidnight(); @@ -419,38 +415,49 @@ void UpdateContentLengthPrefsForDataReductionProxy( // by applying our compression techniques. Totals for the last // |kNumDaysInHistory| days are maintained. DailyDataSavingUpdate total( - prefs::kDailyHttpOriginalContentLength, - prefs::kDailyHttpReceivedContentLength, + data_reduction_proxy::prefs::kDailyHttpOriginalContentLength, + data_reduction_proxy::prefs::kDailyHttpReceivedContentLength, prefs); total.UpdateForDataChange(days_since_last_update); DailyDataSavingUpdate proxy_enabled( - prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled, - prefs::kDailyContentLengthWithDataReductionProxyEnabled, + data_reduction_proxy::prefs:: + kDailyOriginalContentLengthWithDataReductionProxyEnabled, + data_reduction_proxy::prefs:: + kDailyContentLengthWithDataReductionProxyEnabled, prefs); proxy_enabled.UpdateForDataChange(days_since_last_update); DailyDataSavingUpdate via_proxy( - prefs::kDailyOriginalContentLengthViaDataReductionProxy, - prefs::kDailyContentLengthViaDataReductionProxy, + data_reduction_proxy::prefs:: + kDailyOriginalContentLengthViaDataReductionProxy, + data_reduction_proxy::prefs:: + kDailyContentLengthViaDataReductionProxy, prefs); via_proxy.UpdateForDataChange(days_since_last_update); DailyContentLengthUpdate https( - prefs::kDailyContentLengthHttpsWithDataReductionProxyEnabled, prefs); + data_reduction_proxy::prefs:: + kDailyContentLengthHttpsWithDataReductionProxyEnabled, + prefs); https.UpdateForDataChange(days_since_last_update); DailyContentLengthUpdate short_bypass( - prefs::kDailyContentLengthShortBypassWithDataReductionProxyEnabled, + data_reduction_proxy::prefs:: + kDailyContentLengthShortBypassWithDataReductionProxyEnabled, prefs); short_bypass.UpdateForDataChange(days_since_last_update); DailyContentLengthUpdate long_bypass( - prefs::kDailyContentLengthLongBypassWithDataReductionProxyEnabled, prefs); + data_reduction_proxy::prefs:: + kDailyContentLengthLongBypassWithDataReductionProxyEnabled, + prefs); long_bypass.UpdateForDataChange(days_since_last_update); DailyContentLengthUpdate unknown( - prefs::kDailyContentLengthUnknownWithDataReductionProxyEnabled, prefs); + data_reduction_proxy::prefs:: + kDailyContentLengthUnknownWithDataReductionProxyEnabled, + prefs); unknown.UpdateForDataChange(days_since_last_update); total.Add(original_content_length, received_content_length); @@ -458,7 +465,7 @@ void UpdateContentLengthPrefsForDataReductionProxy( proxy_enabled.Add(original_content_length, received_content_length); // Ignore data source cases, if exist, when // "with_data_reduction_proxy_enabled == false" - switch (data_reduction_type) { + switch (request_type) { case VIA_DATA_REDUCTION_PROXY: via_proxy.Add(original_content_length, received_content_length); break; @@ -479,8 +486,9 @@ void UpdateContentLengthPrefsForDataReductionProxy( if (days_since_last_update) { // Record the last update time in microseconds in UTC. - prefs->SetInt64(prefs::kDailyHttpContentLengthLastUpdateDate, - midnight.ToInternalValue()); + prefs->SetInt64( + data_reduction_proxy::prefs::kDailyHttpContentLengthLastUpdateDate, + midnight.ToInternalValue()); // A new day. Report the previous day's data if exists. We'll lose usage // data if the last time Chrome was run was more than a day ago. @@ -509,25 +517,29 @@ void UpdateContentLengthPrefs( int received_content_length, int original_content_length, bool with_data_reduction_proxy_enabled, - DataReductionRequestType data_reduction_type, + DataReductionProxyRequestType request_type, PrefService* prefs) { - int64 total_received = prefs->GetInt64(prefs::kHttpReceivedContentLength); - int64 total_original = prefs->GetInt64(prefs::kHttpOriginalContentLength); + int64 total_received = prefs->GetInt64( + data_reduction_proxy::prefs::kHttpReceivedContentLength); + int64 total_original = prefs->GetInt64( + data_reduction_proxy::prefs::kHttpOriginalContentLength); total_received += received_content_length; total_original += original_content_length; - prefs->SetInt64(prefs::kHttpReceivedContentLength, total_received); - prefs->SetInt64(prefs::kHttpOriginalContentLength, total_original); + prefs->SetInt64(data_reduction_proxy::prefs::kHttpReceivedContentLength, + total_received); + prefs->SetInt64(data_reduction_proxy::prefs::kHttpOriginalContentLength, + total_original); #if defined(OS_ANDROID) || defined(OS_IOS) UpdateContentLengthPrefsForDataReductionProxy( received_content_length, original_content_length, with_data_reduction_proxy_enabled, - data_reduction_type, + request_type, base::Time::Now(), prefs); #endif // defined(OS_ANDROID) || defined(OS_IOS) } -} // namespace spdyproxy +} // namespace data_reduction_proxy diff --git a/chrome/browser/net/spdyproxy/data_saving_metrics.h b/components/data_reduction_proxy/browser/data_reduction_proxy_metrics.h index b94eba9..0e4cab2 100644 --- a/chrome/browser/net/spdyproxy/data_saving_metrics.h +++ b/components/data_reduction_proxy/browser/data_reduction_proxy_metrics.h @@ -1,9 +1,9 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_NET_SPDYPROXY_DATA_SAVING_METRICS_H_ -#define CHROME_BROWSER_NET_SPDYPROXY_DATA_SAVING_METRICS_H_ +#ifndef COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_METRICS_H_ +#define COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_METRICS_H_ #include "base/time/time.h" @@ -13,13 +13,13 @@ class URLRequest; class PrefService; -namespace spdyproxy { +namespace data_reduction_proxy { -enum DataReductionRequestType { +enum DataReductionProxyRequestType { VIA_DATA_REDUCTION_PROXY, // A request served by the data reduction proxy. - // Below are reasons why a request is not served by the enabled data - // reduction proxy. We don't count off-the-record profile data in all cases. + // Below are reasons why a request is not served by the enabled data reduction + // proxy. Off-the-record profile data is not counted in all cases. HTTPS, // An https request. SHORT_BYPASS, // The client is bypassed by the proxy for a short time. LONG_BYPASS, // The client is bypassed by the proxy for a long time (due @@ -27,26 +27,27 @@ enum DataReductionRequestType { UNKNOWN_TYPE, // Any other reason not listed above. }; -// Returns DataReductionRequestType for |request|. -DataReductionRequestType GetDataReductionRequestType( +// Returns DataReductionProxyRequestType for |request|. +DataReductionProxyRequestType GetDataReductionProxyRequestType( const net::URLRequest* request); // Returns |received_content_length| as adjusted original content length if -// |original_content_length| has the invalid value (-1) or |data_reduction_type| +// |original_content_length| has the invalid value (-1) or |request_type| // is not |VIA_DATA_REDUCTION_PROXY|. int64 GetAdjustedOriginalContentLength( - DataReductionRequestType data_reduction_type, + DataReductionProxyRequestType request_type, int64 original_content_length, int64 received_content_length); #if defined(OS_ANDROID) || defined(OS_IOS) +// TODO(bengr): Remove platform-specific ifdefs. // This is only exposed for testing. It is normally called by // UpdateContentLengthPrefs. void UpdateContentLengthPrefsForDataReductionProxy( int received_content_length, int original_content_length, bool with_data_reduction_proxy_enabled, - DataReductionRequestType data_reduction_type, + DataReductionProxyRequestType request_type, base::Time now, PrefService* prefs); #endif @@ -55,9 +56,9 @@ void UpdateContentLengthPrefs( int received_content_length, int original_content_length, bool with_data_reduction_proxy_enabled, - DataReductionRequestType data_reduction_type, + DataReductionProxyRequestType request_type, PrefService* prefs); -} // namespace spdyproxy +} // namespace data_reduction_proxy -#endif // CHROME_BROWSER_NET_SPDYPROXY_DATA_SAVING_METRICS_H_ +#endif // COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_METRICS_H_ diff --git a/chrome/browser/net/spdyproxy/data_saving_metrics_unittest.cc b/components/data_reduction_proxy/browser/data_reduction_proxy_metrics_unittest.cc index 936f92e..f5e24f3 100644 --- a/chrome/browser/net/spdyproxy/data_saving_metrics_unittest.cc +++ b/components/data_reduction_proxy/browser/data_reduction_proxy_metrics_unittest.cc @@ -1,4 +1,4 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -9,8 +9,8 @@ #include "base/prefs/scoped_user_pref_update.h" #include "base/prefs/testing_pref_service.h" #include "base/strings/string_number_conversions.h" -#include "chrome/browser/net/spdyproxy/data_saving_metrics.h" -#include "chrome/common/pref_names.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_metrics.h" +#include "components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h" #include "testing/gtest/include/gtest/gtest.h" namespace { @@ -30,6 +30,10 @@ int64 GetListPrefInt64Value( #endif // defined(OS_ANDROID) || defined(OS_IOS) +} // namespace + +namespace data_reduction_proxy { + // Test UpdateContentLengthPrefs. class ChromeNetworkDataSavingMetricsTest : public testing::Test { protected: @@ -37,30 +41,43 @@ class ChromeNetworkDataSavingMetricsTest : public testing::Test { virtual void SetUp() OVERRIDE { PrefRegistrySimple* registry = pref_service_.registry(); - registry->RegisterInt64Pref(prefs::kHttpReceivedContentLength, 0); - registry->RegisterInt64Pref(prefs::kHttpOriginalContentLength, 0); + registry->RegisterInt64Pref( + data_reduction_proxy::prefs::kHttpReceivedContentLength, 0); + registry->RegisterInt64Pref( + data_reduction_proxy::prefs::kHttpOriginalContentLength, 0); #if defined(OS_ANDROID) || defined(OS_IOS) - registry->RegisterListPref(prefs::kDailyHttpOriginalContentLength); - registry->RegisterListPref(prefs::kDailyHttpReceivedContentLength); + registry->RegisterListPref(data_reduction_proxy::prefs:: + kDailyHttpOriginalContentLength); + registry->RegisterListPref(data_reduction_proxy::prefs:: + kDailyHttpReceivedContentLength); registry->RegisterListPref( - prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled); + data_reduction_proxy::prefs:: + kDailyOriginalContentLengthWithDataReductionProxyEnabled); registry->RegisterListPref( - prefs::kDailyContentLengthWithDataReductionProxyEnabled); + data_reduction_proxy::prefs:: + kDailyContentLengthWithDataReductionProxyEnabled); registry->RegisterListPref( - prefs::kDailyContentLengthHttpsWithDataReductionProxyEnabled); + data_reduction_proxy::prefs:: + kDailyContentLengthHttpsWithDataReductionProxyEnabled); registry->RegisterListPref( - prefs::kDailyContentLengthShortBypassWithDataReductionProxyEnabled); + data_reduction_proxy::prefs:: + kDailyContentLengthShortBypassWithDataReductionProxyEnabled); registry->RegisterListPref( - prefs::kDailyContentLengthLongBypassWithDataReductionProxyEnabled); + data_reduction_proxy::prefs:: + kDailyContentLengthLongBypassWithDataReductionProxyEnabled); registry->RegisterListPref( - prefs::kDailyContentLengthUnknownWithDataReductionProxyEnabled); + data_reduction_proxy::prefs:: + kDailyContentLengthUnknownWithDataReductionProxyEnabled); registry->RegisterListPref( - prefs::kDailyOriginalContentLengthViaDataReductionProxy); + data_reduction_proxy::prefs:: + kDailyOriginalContentLengthViaDataReductionProxy); registry->RegisterListPref( - prefs::kDailyContentLengthViaDataReductionProxy); + data_reduction_proxy::prefs:: + kDailyContentLengthViaDataReductionProxy); registry->RegisterInt64Pref( - prefs::kDailyHttpContentLengthLastUpdateDate, 0L); + data_reduction_proxy::prefs:: + kDailyHttpContentLengthLastUpdateDate, 0L); #endif // defined(OS_ANDROID) || defined(OS_IOS) } @@ -71,22 +88,26 @@ TEST_F(ChromeNetworkDataSavingMetricsTest, TotalLengths) { const int64 kOriginalLength = 200; const int64 kReceivedLength = 100; - spdyproxy::UpdateContentLengthPrefs( + UpdateContentLengthPrefs( kReceivedLength, kOriginalLength, - false, spdyproxy::UNKNOWN_TYPE, &pref_service_); + false, UNKNOWN_TYPE, &pref_service_); EXPECT_EQ(kReceivedLength, - pref_service_.GetInt64(prefs::kHttpReceivedContentLength)); + pref_service_.GetInt64( + data_reduction_proxy::prefs::kHttpReceivedContentLength)); EXPECT_EQ(kOriginalLength, - pref_service_.GetInt64(prefs::kHttpOriginalContentLength)); + pref_service_.GetInt64( + data_reduction_proxy::prefs::kHttpOriginalContentLength)); // Record the same numbers again, and total lengths should be dobuled. - spdyproxy::UpdateContentLengthPrefs( + UpdateContentLengthPrefs( kReceivedLength, kOriginalLength, - false, spdyproxy::UNKNOWN_TYPE, &pref_service_); + false, UNKNOWN_TYPE, &pref_service_); EXPECT_EQ(kReceivedLength * 2, - pref_service_.GetInt64(prefs::kHttpReceivedContentLength)); + pref_service_.GetInt64( + data_reduction_proxy::prefs::kHttpReceivedContentLength)); EXPECT_EQ(kOriginalLength * 2, - pref_service_.GetInt64(prefs::kHttpOriginalContentLength)); + pref_service_.GetInt64( + data_reduction_proxy::prefs::kHttpOriginalContentLength)); } #if defined(OS_ANDROID) || defined(OS_IOS) @@ -108,8 +129,10 @@ class ChromeNetworkDailyDataSavingMetricsTest ChromeNetworkDataSavingMetricsTest::SetUp(); // Only create two lists in Setup to test that adding new lists is fine. - CreatePrefList(prefs::kDailyHttpOriginalContentLength); - CreatePrefList(prefs::kDailyHttpReceivedContentLength); + CreatePrefList( + data_reduction_proxy::prefs::kDailyHttpOriginalContentLength); + CreatePrefList( + data_reduction_proxy::prefs::kDailyHttpReceivedContentLength); } base::Time FakeNow() const { @@ -164,24 +187,28 @@ class ChromeNetworkDailyDataSavingMetricsTest size_t original_via_data_reduction_proxy_count, const int64* received_via_data_reduction_proxy_values, size_t received_via_data_reduction_proxy_count) { - VerifyPrefList(prefs::kDailyHttpOriginalContentLength, + VerifyPrefList(data_reduction_proxy::prefs::kDailyHttpOriginalContentLength, original_values, original_count); - VerifyPrefList(prefs::kDailyHttpReceivedContentLength, + VerifyPrefList(data_reduction_proxy::prefs::kDailyHttpReceivedContentLength, received_values, received_count); VerifyPrefList( - prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled, + data_reduction_proxy::prefs:: + kDailyOriginalContentLengthWithDataReductionProxyEnabled, original_with_data_reduction_proxy_enabled_values, original_with_data_reduction_proxy_enabled_count); VerifyPrefList( - prefs::kDailyContentLengthWithDataReductionProxyEnabled, + data_reduction_proxy::prefs:: + kDailyContentLengthWithDataReductionProxyEnabled, received_with_data_reduction_proxy_enabled_values, received_with_data_reduction_proxy_count); VerifyPrefList( - prefs::kDailyOriginalContentLengthViaDataReductionProxy, + data_reduction_proxy::prefs:: + kDailyOriginalContentLengthViaDataReductionProxy, original_via_data_reduction_proxy_values, original_via_data_reduction_proxy_count); VerifyPrefList( - prefs::kDailyContentLengthViaDataReductionProxy, + data_reduction_proxy::prefs:: + kDailyContentLengthViaDataReductionProxy, received_via_data_reduction_proxy_values, received_via_data_reduction_proxy_count); } @@ -202,32 +229,38 @@ class ChromeNetworkDailyDataSavingMetricsTest size_t long_bypass_with_data_reduction_proxy_enabled_count, const int64* unknown_with_data_reduction_proxy_enabled_values, size_t unknown_with_data_reduction_proxy_enabled_count) { - VerifyPrefList(prefs::kDailyHttpOriginalContentLength, + VerifyPrefList(data_reduction_proxy::prefs::kDailyHttpOriginalContentLength, original_values, original_count); - VerifyPrefList(prefs::kDailyHttpReceivedContentLength, + VerifyPrefList(data_reduction_proxy::prefs::kDailyHttpReceivedContentLength, received_values, received_count); VerifyPrefList( - prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled, + data_reduction_proxy::prefs:: + kDailyOriginalContentLengthWithDataReductionProxyEnabled, original_with_data_reduction_proxy_enabled_values, original_with_data_reduction_proxy_enabled_count); VerifyPrefList( - prefs::kDailyContentLengthWithDataReductionProxyEnabled, + data_reduction_proxy::prefs:: + kDailyContentLengthWithDataReductionProxyEnabled, received_with_data_reduction_proxy_enabled_values, received_with_data_reduction_proxy_count); VerifyPrefList( - prefs::kDailyContentLengthHttpsWithDataReductionProxyEnabled, + data_reduction_proxy::prefs:: + kDailyContentLengthHttpsWithDataReductionProxyEnabled, https_with_data_reduction_proxy_enabled_values, https_with_data_reduction_proxy_enabled_count); VerifyPrefList( - prefs::kDailyContentLengthShortBypassWithDataReductionProxyEnabled, + data_reduction_proxy::prefs:: + kDailyContentLengthShortBypassWithDataReductionProxyEnabled, short_bypass_with_data_reduction_proxy_enabled_values, short_bypass_with_data_reduction_proxy_enabled_count); VerifyPrefList( - prefs::kDailyContentLengthLongBypassWithDataReductionProxyEnabled, + data_reduction_proxy::prefs:: + kDailyContentLengthLongBypassWithDataReductionProxyEnabled, long_bypass_with_data_reduction_proxy_enabled_values, long_bypass_with_data_reduction_proxy_enabled_count); VerifyPrefList( - prefs::kDailyContentLengthUnknownWithDataReductionProxyEnabled, + data_reduction_proxy::prefs:: + kDailyContentLengthUnknownWithDataReductionProxyEnabled, unknown_with_data_reduction_proxy_enabled_values, unknown_with_data_reduction_proxy_enabled_count); } @@ -243,9 +276,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, OneResponse) { int64 original[] = {kOriginalLength}; int64 received[] = {kReceivedLength}; - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); VerifyDailyDataSavingContentLengthPrefLists( original, 1, received, 1, @@ -258,17 +291,17 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, MultipleResponses) { const int64 kReceivedLength = 100; int64 original[] = {kOriginalLength}; int64 received[] = {kReceivedLength}; - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - false, spdyproxy::UNKNOWN_TYPE, + false, UNKNOWN_TYPE, FakeNow(), &pref_service_); VerifyDailyDataSavingContentLengthPrefLists( original, 1, received, 1, NULL, 0, NULL, 0, NULL, 0, NULL, 0); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::UNKNOWN_TYPE, + true, UNKNOWN_TYPE, FakeNow(), &pref_service_); original[0] += kOriginalLength; received[0] += kReceivedLength; @@ -279,9 +312,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, MultipleResponses) { original_proxy_enabled, 1, received_proxy_enabled, 1, NULL, 0, NULL, 0); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); original[0] += kOriginalLength; received[0] += kReceivedLength; @@ -294,9 +327,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, MultipleResponses) { original_proxy_enabled, 1, received_proxy_enabled, 1, original_via_proxy, 1, received_via_proxy, 1); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::UNKNOWN_TYPE, FakeNow(), &pref_service_); + true, UNKNOWN_TYPE, FakeNow(), &pref_service_); original[0] += kOriginalLength; received[0] += kReceivedLength; original_proxy_enabled[0] += kOriginalLength; @@ -306,9 +339,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, MultipleResponses) { original_proxy_enabled, 1, received_proxy_enabled, 1, original_via_proxy, 1, received_via_proxy, 1); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - false, spdyproxy::UNKNOWN_TYPE, FakeNow(), &pref_service_); + false, UNKNOWN_TYPE, FakeNow(), &pref_service_); original[0] += kOriginalLength; received[0] += kReceivedLength; VerifyDailyDataSavingContentLengthPrefLists( @@ -324,9 +357,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, RequestType) { int64 total_received[] = {0}; int64 proxy_enabled_received[] = {0}; - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kContentLength, kContentLength, - true, spdyproxy::HTTPS, + true, HTTPS, FakeNow(), &pref_service_); total_received[0] += kContentLength; proxy_enabled_received[0] += kContentLength; @@ -340,9 +373,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, RequestType) { received, 0); // unknown // Data reduction proxy is not enabled. - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kContentLength, kContentLength, - false, spdyproxy::HTTPS, + false, HTTPS, FakeNow(), &pref_service_); total_received[0] += kContentLength; VerifyDailyRequestTypeContentLengthPrefLists( @@ -353,9 +386,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, RequestType) { received, 0, // long bypass received, 0); // unknown - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kContentLength, kContentLength, - true, spdyproxy::HTTPS, + true, HTTPS, FakeNow(), &pref_service_); total_received[0] += kContentLength; proxy_enabled_received[0] += kContentLength; @@ -368,9 +401,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, RequestType) { received, 0, // long bypass received, 0); // unknown - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kContentLength, kContentLength, - true, spdyproxy::SHORT_BYPASS, + true, SHORT_BYPASS, FakeNow(), &pref_service_); total_received[0] += kContentLength; proxy_enabled_received[0] += kContentLength; @@ -383,9 +416,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, RequestType) { received, 0, // long bypass received, 0); // unknown - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kContentLength, kContentLength, - true, spdyproxy::LONG_BYPASS, + true, LONG_BYPASS, FakeNow(), &pref_service_); total_received[0] += kContentLength; proxy_enabled_received[0] += kContentLength; @@ -397,9 +430,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, RequestType) { received, 1, // long bypass received, 0); // unknown - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kContentLength, kContentLength, - true, spdyproxy::UNKNOWN_TYPE, + true, UNKNOWN_TYPE, FakeNow(), &pref_service_); total_received[0] += kContentLength; proxy_enabled_received[0] += kContentLength; @@ -416,18 +449,18 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, ForwardOneDay) { const int64 kOriginalLength = 200; const int64 kReceivedLength = 100; - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); // Forward one day. SetFakeTimeDeltaInHours(24); // Proxy not enabled. Not via proxy. - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - false, spdyproxy::UNKNOWN_TYPE, FakeNow(), &pref_service_); + false, UNKNOWN_TYPE, FakeNow(), &pref_service_); int64 original[] = {kOriginalLength, kOriginalLength}; int64 received[] = {kReceivedLength, kReceivedLength}; @@ -444,9 +477,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, ForwardOneDay) { received_via_data_reduction_proxy, 2); // Proxy enabled. Not via proxy. - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::UNKNOWN_TYPE, FakeNow(), &pref_service_); + true, UNKNOWN_TYPE, FakeNow(), &pref_service_); original[1] += kOriginalLength; received[1] += kReceivedLength; original_with_data_reduction_proxy_enabled[1] += kOriginalLength; @@ -460,9 +493,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, ForwardOneDay) { received_via_data_reduction_proxy, 2); // Proxy enabled and via proxy. - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); original[1] += kOriginalLength; received[1] += kReceivedLength; @@ -485,9 +518,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, PartialDayTimeChange) { int64 original[] = {0, kOriginalLength}; int64 received[] = {0, kReceivedLength}; - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); VerifyDailyDataSavingContentLengthPrefLists( original, 2, received, 2, @@ -497,9 +530,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, PartialDayTimeChange) { // Forward 10 hours, stay in the same day. // See kLastUpdateTime: "Now" in test is 03:45am. SetFakeTimeDeltaInHours(10); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); original[1] += kOriginalLength; received[1] += kReceivedLength; @@ -510,9 +543,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, PartialDayTimeChange) { // Forward 11 more hours, comes to tomorrow. AddFakeTimeDeltaInHours(11); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); int64 original2[] = {kOriginalLength * 2, kOriginalLength}; int64 received2[] = {kReceivedLength * 2, kReceivedLength}; @@ -525,17 +558,17 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, PartialDayTimeChange) { TEST_F(ChromeNetworkDailyDataSavingMetricsTest, ForwardMultipleDays) { const int64 kOriginalLength = 200; const int64 kReceivedLength = 100; - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); // Forward three days. SetFakeTimeDeltaInHours(3 * 24); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); int64 original[] = {kOriginalLength, 0, 0, kOriginalLength}; @@ -547,9 +580,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, ForwardMultipleDays) { // Forward four more days. AddFakeTimeDeltaInHours(4 * 24); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); int64 original2[] = { kOriginalLength, 0, 0, kOriginalLength, 0, 0, 0, kOriginalLength, @@ -564,9 +597,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, ForwardMultipleDays) { // Forward |kNumDaysInHistory| more days. AddFakeTimeDeltaInHours(kNumDaysInHistory * 24); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); int64 original3[] = {kOriginalLength}; int64 received3[] = {kReceivedLength}; @@ -577,9 +610,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, ForwardMultipleDays) { // Forward |kNumDaysInHistory| + 1 more days. AddFakeTimeDeltaInHours((kNumDaysInHistory + 1)* 24); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); VerifyDailyDataSavingContentLengthPrefLists( original3, 1, received3, 1, @@ -593,16 +626,16 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, BackwardAndForwardOneDay) { int64 original[] = {kOriginalLength}; int64 received[] = {kReceivedLength}; - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); // Backward one day. SetFakeTimeDeltaInHours(-24); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); original[0] += kOriginalLength; received[0] += kReceivedLength; @@ -613,9 +646,9 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, BackwardAndForwardOneDay) { // Then, Forward one day AddFakeTimeDeltaInHours(24); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); int64 original2[] = {kOriginalLength * 2, kOriginalLength}; int64 received2[] = {kReceivedLength * 2, kReceivedLength}; @@ -631,15 +664,15 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, BackwardTwoDays) { int64 original[] = {kOriginalLength}; int64 received[] = {kReceivedLength}; - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); // Backward two days. SetFakeTimeDeltaInHours(-2 * 24); - spdyproxy::UpdateContentLengthPrefsForDataReductionProxy( + UpdateContentLengthPrefsForDataReductionProxy( kReceivedLength, kOriginalLength, - true, spdyproxy::VIA_DATA_REDUCTION_PROXY, + true, VIA_DATA_REDUCTION_PROXY, FakeNow(), &pref_service_); VerifyDailyDataSavingContentLengthPrefLists( original, 1, received, 1, @@ -648,4 +681,4 @@ TEST_F(ChromeNetworkDailyDataSavingMetricsTest, BackwardTwoDays) { } #endif // defined(OS_ANDROID) || defined(OS_IOS) -} // namespace +} // namespace data_reduction_proxy diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings.cc b/components/data_reduction_proxy/browser/data_reduction_proxy_settings.cc index 6580d68..b3d4c71 100644 --- a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings.cc +++ b/components/data_reduction_proxy/browser/data_reduction_proxy_settings.cc @@ -1,10 +1,8 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h" - -#include <inttypes.h> +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h" #include "base/bind.h" #include "base/command_line.h" @@ -17,12 +15,9 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/prefs/proxy_prefs.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/profiles/profile_manager.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/pref_names.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_configurator.h" +#include "components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h" +#include "components/data_reduction_proxy/common/data_reduction_proxy_switches.h" #include "crypto/random.h" #include "net/base/auth.h" #include "net/base/host_port_pair.h" @@ -34,13 +29,12 @@ #include "net/http/http_response_headers.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" +#include "net/url_request/url_request_context_getter.h" #include "net/url_request/url_request_status.h" #include "url/gurl.h" using base::FieldTrialList; using base::StringPrintf; -using spdyproxy::ProbeURLFetchResult; -using spdyproxy::ProxyStartupState; namespace { @@ -51,7 +45,6 @@ const char kUMAProxyStartupStateHistogram[] = // Key of the UMA DataReductionProxy.ProbeURL histogram. const char kUMAProxyProbeURL[] = "DataReductionProxy.ProbeURL"; - const char kEnabled[] = "Enabled"; // TODO(marq): Factor this string out into a constant here and in @@ -72,19 +65,26 @@ int64 GetInt64PrefValue(const base::ListValue& list_value, size_t index) { bool IsProxyOriginSetOnCommandLine() { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); - return command_line.HasSwitch(switches::kSpdyProxyAuthOrigin); + return command_line.HasSwitch( + data_reduction_proxy::switches::kDataReductionProxy); } bool IsEnableSpdyProxyAuthSetOnCommandLine() { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); - return command_line.HasSwitch(switches::kEnableSpdyProxyAuth); + return command_line.HasSwitch( + data_reduction_proxy::switches::kEnableDataReductionProxy); } } // namespace +namespace data_reduction_proxy { + DataReductionProxySettings::DataReductionProxySettings() : restricted_by_carrier_(false), - enabled_by_user_(false) { + enabled_by_user_(false), + prefs_(NULL), + local_state_prefs_(NULL), + url_request_context_getter_(NULL) { } DataReductionProxySettings::~DataReductionProxySettings() { @@ -93,14 +93,28 @@ DataReductionProxySettings::~DataReductionProxySettings() { } void DataReductionProxySettings::InitPrefMembers() { + DCHECK(thread_checker_.CalledOnValidThread()); spdy_proxy_auth_enabled_.Init( - prefs::kSpdyProxyAuthEnabled, + prefs::kDataReductionProxyEnabled, GetOriginalProfilePrefs(), base::Bind(&DataReductionProxySettings::OnProxyEnabledPrefChange, base::Unretained(this))); } -void DataReductionProxySettings::InitDataReductionProxySettings() { +void DataReductionProxySettings::InitDataReductionProxySettings( + PrefService* prefs, + PrefService* local_state_prefs, + net::URLRequestContextGetter* url_request_context_getter, + scoped_ptr<DataReductionProxyConfigurator> config) { + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK(prefs); + DCHECK(local_state_prefs); + DCHECK(url_request_context_getter); + DCHECK(config); + prefs_ = prefs; + local_state_prefs_ = local_state_prefs; + url_request_context_getter_ = url_request_context_getter; + config_ = config.Pass(); InitPrefMembers(); RecordDataReductionInit(); @@ -123,6 +137,8 @@ void DataReductionProxySettings::InitDataReductionProxySession( // Authentication will still work if the command line parameters are used, // however there will be a round-trip overhead for each challenge/response // (typically once per session). +// TODO(bengr):Pass a configuration struct into DataReductionProxyConfigurator's +// constructor. The struct would carry everything in the preprocessor flags. #if defined(SPDY_PROXY_AUTH_ORIGIN) && defined(SPDY_PROXY_AUTH_VALUE) DCHECK(session); net::HttpAuthCache* auth_cache = session->http_auth_cache(); @@ -146,11 +162,16 @@ void DataReductionProxySettings::InitDataReductionAuthentication( crypto::RandBytes(rand, 3 * sizeof(rand[0])); std::string realm = - base::StringPrintf("%s%" PRId64, kAuthenticationRealmName, timestamp); + base::StringPrintf("%s%lld", kAuthenticationRealmName, + static_cast<long long>(timestamp)); std::string challenge = base::StringPrintf( - "%s realm=\"%s\", ps=\"%" PRId64 "-%u-%u-%u\"", + "%s realm=\"%s\", ps=\"%lld-%u-%u-%u\"", kAuthenticationRealmName, - realm.data(), timestamp, rand[0], rand[1], rand[2]); + realm.data(), + static_cast<long long>(timestamp), + rand[0], + rand[1], + rand[2]); base::string16 password = AuthHashForSalt(timestamp); DVLOG(1) << "origin: [" << auth_origin << "] realm: [" << realm @@ -168,26 +189,7 @@ void DataReductionProxySettings::InitDataReductionAuthentication( } } -void DataReductionProxySettings::AddHostPatternToBypass( - const std::string& pattern) { - bypass_rules_.push_back(pattern); -} - -void DataReductionProxySettings::AddURLPatternToBypass( - const std::string& pattern) { - size_t pos = pattern.find("/"); - if (pattern.find("/", pos + 1) == pos + 1) - pos = pattern.find("/", pos + 2); - - std::string host_pattern; - if (pos != std::string::npos) - host_pattern = pattern.substr(0, pos); - else - host_pattern = pattern; - - AddHostPatternToBypass(host_pattern); -} - +// TODO(bengr): Use a configuration struct to carry field trial state as well. // static bool DataReductionProxySettings::IsDataReductionProxyAllowed() { return IsProxyOriginSetOnCommandLine() || @@ -213,10 +215,10 @@ bool DataReductionProxySettings::IsPreconnectHintingAllowed() { // static std::string DataReductionProxySettings::GetDataReductionProxyOrigin() { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); - if (command_line.HasSwitch(switches::kSpdyProxyDevAuthOrigin)) - return command_line.GetSwitchValueASCII(switches::kSpdyProxyDevAuthOrigin); - if (command_line.HasSwitch(switches::kSpdyProxyAuthOrigin)) - return command_line.GetSwitchValueASCII(switches::kSpdyProxyAuthOrigin); + if (command_line.HasSwitch(switches::kDataReductionProxyDev)) + return command_line.GetSwitchValueASCII(switches::kDataReductionProxyDev); + if (command_line.HasSwitch(switches::kDataReductionProxy)) + return command_line.GetSwitchValueASCII(switches::kDataReductionProxy); #if defined(DATA_REDUCTION_DEV_HOST) if (FieldTrialList::FindFullName("DataCompressionProxyDevRollout") == kEnabled) { @@ -237,8 +239,10 @@ std::string DataReductionProxySettings::GetDataReductionProxyFallback() { if (GetDataReductionProxyOrigin().empty()) return std::string(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); - if (command_line.HasSwitch(switches::kSpdyProxyAuthFallback)) - return command_line.GetSwitchValueASCII(switches::kSpdyProxyAuthFallback); + if (command_line.HasSwitch(switches::kDataReductionProxyFallback)) { + return command_line.GetSwitchValueASCII( + switches::kDataReductionProxyFallback); + } #if defined(DATA_REDUCTION_FALLBACK_HOST) return DATA_REDUCTION_FALLBACK_HOST; #else @@ -312,6 +316,7 @@ DataReductionProxySettings::GetDataReductionProxies() { } void DataReductionProxySettings::SetDataReductionProxyEnabled(bool enabled) { + DCHECK(thread_checker_.CalledOnValidThread()); // Prevent configuring the proxy when it is not allowed to be used. if (!IsDataReductionProxyAllowed()) return; @@ -323,6 +328,7 @@ void DataReductionProxySettings::SetDataReductionProxyEnabled(bool enabled) { } int64 DataReductionProxySettings::GetDataReductionLastUpdateTime() { + DCHECK(thread_checker_.CalledOnValidThread()); PrefService* local_state = GetLocalStatePrefs(); int64 last_update_internal = local_state->GetInt64(prefs::kDailyHttpContentLengthLastUpdateDate); @@ -332,20 +338,23 @@ int64 DataReductionProxySettings::GetDataReductionLastUpdateTime() { DataReductionProxySettings::ContentLengthList DataReductionProxySettings::GetDailyOriginalContentLengths() { + DCHECK(thread_checker_.CalledOnValidThread()); return GetDailyContentLengths(prefs::kDailyHttpOriginalContentLength); } DataReductionProxySettings::ContentLengthList DataReductionProxySettings::GetDailyReceivedContentLengths() { + DCHECK(thread_checker_.CalledOnValidThread()); return GetDailyContentLengths(prefs::kDailyHttpReceivedContentLength); } void DataReductionProxySettings::OnURLFetchComplete( const net::URLFetcher* source) { + DCHECK(thread_checker_.CalledOnValidThread()); net::URLRequestStatus status = source->GetStatus(); if (status.status() == net::URLRequestStatus::FAILED && status.error() == net::ERR_INTERNET_DISCONNECTED) { - RecordProbeURLFetchResult(spdyproxy::INTERNET_DISCONNECTED); + RecordProbeURLFetchResult(INTERNET_DISCONNECTED); return; } @@ -364,9 +373,9 @@ void DataReductionProxySettings::OnURLFetchComplete( SetProxyConfigs(true /* enabled */, false /* restricted */, false /* at_startup */); - RecordProbeURLFetchResult(spdyproxy::SUCCEEDED_PROXY_ENABLED); + RecordProbeURLFetchResult(SUCCEEDED_PROXY_ENABLED); } else { - RecordProbeURLFetchResult(spdyproxy::SUCCEEDED_PROXY_ALREADY_ENABLED); + RecordProbeURLFetchResult(SUCCEEDED_PROXY_ALREADY_ENABLED); } } restricted_by_carrier_ = false; @@ -381,15 +390,16 @@ void DataReductionProxySettings::OnURLFetchComplete( SetProxyConfigs(true /* enabled */, true /* restricted */, false /* at_startup */); - RecordProbeURLFetchResult(spdyproxy::FAILED_PROXY_DISABLED); + RecordProbeURLFetchResult(FAILED_PROXY_DISABLED); } else { - RecordProbeURLFetchResult(spdyproxy::FAILED_PROXY_ALREADY_DISABLED); + RecordProbeURLFetchResult(FAILED_PROXY_ALREADY_DISABLED); } } restricted_by_carrier_ = true; } void DataReductionProxySettings::OnIPAddressChanged() { + DCHECK(thread_checker_.CalledOnValidThread()); if (enabled_by_user_) { DCHECK(IsDataReductionProxyAllowed()); ProbeWhetherDataReductionProxyIsAvailable(); @@ -397,6 +407,7 @@ void DataReductionProxySettings::OnIPAddressChanged() { } void DataReductionProxySettings::OnProxyEnabledPrefChange() { + DCHECK(thread_checker_.CalledOnValidThread()); if (!DataReductionProxySettings::IsDataReductionProxyAllowed()) return; MaybeActivateDataReductionProxy(false); @@ -404,16 +415,16 @@ void DataReductionProxySettings::OnProxyEnabledPrefChange() { void DataReductionProxySettings::AddDefaultProxyBypassRules() { // localhost - AddHostPatternToBypass("<local>"); + config_->AddHostPatternToBypass("<local>"); // RFC1918 private addresses. - AddHostPatternToBypass("10.0.0.0/8"); - AddHostPatternToBypass("172.16.0.0/12"); - AddHostPatternToBypass("192.168.0.0/16"); + config_->AddHostPatternToBypass("10.0.0.0/8"); + config_->AddHostPatternToBypass("172.16.0.0/12"); + config_->AddHostPatternToBypass("192.168.0.0/16"); // RFC4193 private addresses. - AddHostPatternToBypass("fc00::/7"); + config_->AddHostPatternToBypass("fc00::/7"); // IPV6 probe addresses. - AddHostPatternToBypass("*-ds.metric.gstatic.com"); - AddHostPatternToBypass("*-v4.metric.gstatic.com"); + config_->AddHostPatternToBypass("*-ds.metric.gstatic.com"); + config_->AddHostPatternToBypass("*-v4.metric.gstatic.com"); } void DataReductionProxySettings::LogProxyState( @@ -435,15 +446,17 @@ void DataReductionProxySettings::LogProxyState( } PrefService* DataReductionProxySettings::GetOriginalProfilePrefs() { - return g_browser_process->profile_manager()->GetLastUsedProfile()-> - GetOriginalProfile()->GetPrefs(); + DCHECK(thread_checker_.CalledOnValidThread()); + return prefs_; } PrefService* DataReductionProxySettings::GetLocalStatePrefs() { - return g_browser_process->local_state(); + DCHECK(thread_checker_.CalledOnValidThread()); + return local_state_prefs_; } void DataReductionProxySettings::ResetDataReductionStatistics() { + DCHECK(thread_checker_.CalledOnValidThread()); PrefService* prefs = GetLocalStatePrefs(); if (!prefs) return; @@ -451,7 +464,7 @@ void DataReductionProxySettings::ResetDataReductionStatistics() { ListPrefUpdate received_update(prefs, prefs::kDailyHttpReceivedContentLength); original_update->Clear(); received_update->Clear(); - for (size_t i = 0; i < spdyproxy::kNumDaysInHistory; ++i) { + for (size_t i = 0; i < kNumDaysInHistory; ++i) { original_update->AppendString(base::Int64ToString(0)); received_update->AppendString(base::Int64ToString(0)); } @@ -459,13 +472,14 @@ void DataReductionProxySettings::ResetDataReductionStatistics() { void DataReductionProxySettings::MaybeActivateDataReductionProxy( bool at_startup) { + DCHECK(thread_checker_.CalledOnValidThread()); PrefService* prefs = GetOriginalProfilePrefs(); // TODO(marq): Consider moving this so stats are wiped the first time the // proxy settings are actually (not maybe) turned on. if (spdy_proxy_auth_enabled_.GetValue() && - !prefs->GetBoolean(prefs::kSpdyProxyAuthWasEnabledBefore)) { - prefs->SetBoolean(prefs::kSpdyProxyAuthWasEnabledBefore, true); + !prefs->GetBoolean(prefs::kDataReductionProxyWasEnabledBefore)) { + prefs->SetBoolean(prefs::kDataReductionProxyWasEnabledBefore, true); ResetDataReductionStatistics(); } @@ -482,6 +496,7 @@ void DataReductionProxySettings::MaybeActivateDataReductionProxy( void DataReductionProxySettings::SetProxyConfigs( bool enabled, bool restricted, bool at_startup) { + DCHECK(thread_checker_.CalledOnValidThread()); // If |restricted| is true and there is no defined fallback proxy. // treat this as a disable. std::string fallback = GetDataReductionProxyFallback(); @@ -489,40 +504,22 @@ void DataReductionProxySettings::SetProxyConfigs( enabled = false; LogProxyState(enabled, restricted, at_startup); - PrefService* prefs = GetOriginalProfilePrefs(); - DCHECK(prefs); - DictionaryPrefUpdate update(prefs, prefs::kProxy); - base::DictionaryValue* dict = update.Get(); if (enabled) { - std::string proxy_list; - if (restricted) { - DCHECK(!fallback.empty()); - proxy_list = fallback; - } else { - proxy_list = GetDataReductionProxyOrigin() + - (fallback.empty() ? "" : "," + fallback); - } - - std::string proxy_server_config = "http=" + proxy_list + ",direct://;"; - dict->SetString("server", proxy_server_config); - dict->SetString("mode", - ProxyModeToString(ProxyPrefs::MODE_FIXED_SERVERS)); - dict->SetString("bypass_list", JoinString(bypass_rules_, ", ")); + config_->Enable(restricted, GetDataReductionProxyOrigin(), fallback); } else { - dict->SetString("mode", ProxyModeToString(ProxyPrefs::MODE_SYSTEM)); - dict->SetString("server", ""); - dict->SetString("bypass_list", ""); + config_->Disable(); } } // Metrics methods void DataReductionProxySettings::RecordDataReductionInit() { - ProxyStartupState state = spdyproxy::PROXY_NOT_AVAILABLE; + DCHECK(thread_checker_.CalledOnValidThread()); + ProxyStartupState state = PROXY_NOT_AVAILABLE; if (IsDataReductionProxyAllowed()) { if (IsDataReductionProxyEnabled()) - state = spdyproxy::PROXY_ENABLED; + state = PROXY_ENABLED; else - state = spdyproxy::PROXY_DISABLED; + state = PROXY_DISABLED; } RecordStartupState(state); @@ -532,21 +529,22 @@ void DataReductionProxySettings::RecordProbeURLFetchResult( ProbeURLFetchResult result) { UMA_HISTOGRAM_ENUMERATION(kUMAProxyProbeURL, result, - spdyproxy::PROBE_URL_FETCH_RESULT_COUNT); + PROBE_URL_FETCH_RESULT_COUNT); } void DataReductionProxySettings::RecordStartupState(ProxyStartupState state) { UMA_HISTOGRAM_ENUMERATION(kUMAProxyStartupStateHistogram, state, - spdyproxy::PROXY_STARTUP_STATE_COUNT); + PROXY_STARTUP_STATE_COUNT); } DataReductionProxySettings::ContentLengthList DataReductionProxySettings::GetDailyContentLengths(const char* pref_name) { + DCHECK(thread_checker_.CalledOnValidThread()); DataReductionProxySettings::ContentLengthList content_lengths; const base::ListValue* list_value = GetLocalStatePrefs()->GetList(pref_name); - if (list_value->GetSize() == spdyproxy::kNumDaysInHistory) { - for (size_t i = 0; i < spdyproxy::kNumDaysInHistory; ++i) { + if (list_value->GetSize() == kNumDaysInHistory) { + for (size_t i = 0; i < kNumDaysInHistory; ++i) { content_lengths.push_back(GetInt64PrefValue(*list_value, i)); } } @@ -558,7 +556,8 @@ void DataReductionProxySettings::GetContentLengths( int64* original_content_length, int64* received_content_length, int64* last_update_time) { - DCHECK_LE(days, spdyproxy::kNumDaysInHistory); + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK_LE(days, kNumDaysInHistory); PrefService* local_state = GetLocalStatePrefs(); if (!local_state) { *original_content_length = 0L; @@ -572,8 +571,8 @@ void DataReductionProxySettings::GetContentLengths( const base::ListValue* received_list = local_state->GetList(prefs::kDailyHttpReceivedContentLength); - if (original_list->GetSize() != spdyproxy::kNumDaysInHistory || - received_list->GetSize() != spdyproxy::kNumDaysInHistory) { + if (original_list->GetSize() != kNumDaysInHistory || + received_list->GetSize() != kNumDaysInHistory) { *original_content_length = 0L; *received_content_length = 0L; *last_update_time = 0L; @@ -583,8 +582,8 @@ void DataReductionProxySettings::GetContentLengths( int64 orig = 0L; int64 recv = 0L; // Include days from the end of the list going backwards. - for (size_t i = spdyproxy::kNumDaysInHistory - days; - i < spdyproxy::kNumDaysInHistory; ++i) { + for (size_t i = kNumDaysInHistory - days; + i < kNumDaysInHistory; ++i) { orig += GetInt64PrefValue(*original_list, i); recv += GetInt64PrefValue(*received_list, i); } @@ -617,14 +616,14 @@ base::string16 DataReductionProxySettings::AuthHashForSalt(int64 salt) { std::string key; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); - if (command_line.HasSwitch(switches::kSpdyProxyAuthOrigin)) { + if (command_line.HasSwitch(switches::kDataReductionProxy)) { // If an origin is provided via a switch, then only consider the value // that is provided by a switch. Do not use the preprocessor constant. // Don't expose SPDY_PROXY_AUTH_VALUE to a proxy passed in via the command // line. - if (!command_line.HasSwitch(switches::kSpdyProxyAuthValue)) + if (!command_line.HasSwitch(switches::kDataReductionProxyKey)) return base::string16(); - key = command_line.GetSwitchValueASCII(switches::kSpdyProxyAuthValue); + key = command_line.GetSwitchValueASCII(switches::kDataReductionProxyKey); } else { #if defined(SPDY_PROXY_AUTH_VALUE) key = SPDY_PROXY_AUTH_VALUE; @@ -636,11 +635,15 @@ base::string16 DataReductionProxySettings::AuthHashForSalt(int64 salt) { DCHECK(!key.empty()); std::string salted_key = - base::StringPrintf("%" PRId64 "%s%" PRId64, salt, key.c_str(), salt); + base::StringPrintf("%lld%s%lld", + static_cast<long long>(salt), + key.c_str(), + static_cast<long long>(salt)); return base::UTF8ToUTF16(base::MD5String(salted_key)); } net::URLFetcher* DataReductionProxySettings::GetURLFetcher() { + DCHECK(url_request_context_getter_); std::string url = GetProxyCheckURL(); if (url.empty()) return NULL; @@ -648,21 +651,19 @@ net::URLFetcher* DataReductionProxySettings::GetURLFetcher() { net::URLFetcher::GET, this); fetcher->SetLoadFlags(net::LOAD_DISABLE_CACHE | net::LOAD_BYPASS_PROXY); - // If this code ever goes multi profile, the used profile needs to be taken - // from the browser context. - Profile* profile = ProfileManager::GetActiveUserProfile(); - fetcher->SetRequestContext(profile->GetRequestContext()); + fetcher->SetRequestContext(url_request_context_getter_); // Configure max retries to be at most kMaxRetries times for 5xx errors. static const int kMaxRetries = 5; fetcher->SetMaxRetriesOn5xx(kMaxRetries); return fetcher; } -void -DataReductionProxySettings::ProbeWhetherDataReductionProxyIsAvailable() { +void DataReductionProxySettings::ProbeWhetherDataReductionProxyIsAvailable() { net::URLFetcher* fetcher = GetURLFetcher(); if (!fetcher) return; fetcher_.reset(fetcher); fetcher_->Start(); } + +} // namespace data_reduction_proxy diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h b/components/data_reduction_proxy/browser/data_reduction_proxy_settings.h index c2a4bcc..2ccc3fa 100644 --- a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h +++ b/components/data_reduction_proxy/browser/data_reduction_proxy_settings.h @@ -1,9 +1,9 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_SETTINGS_H_ -#define CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_SETTINGS_H_ +#ifndef COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_SETTINGS_H_ +#define COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_SETTINGS_H_ #include <vector> @@ -12,6 +12,8 @@ #include "base/gtest_prod_util.h" #include "base/memory/scoped_ptr.h" #include "base/prefs/pref_member.h" +#include "base/threading/thread_checker.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_configurator.h" #include "net/base/network_change_notifier.h" #include "net/url_request/url_fetcher_delegate.h" @@ -24,9 +26,10 @@ class HttpAuthCache; class HttpNetworkSession; class HttpResponseHeaders; class URLFetcher; +class URLRequestContextGetter; } -namespace spdyproxy { +namespace data_reduction_proxy { // The number of days of bandwidth usage statistics that are tracked. const unsigned int kNumDaysInHistory = 60; @@ -53,7 +56,7 @@ COMPILE_ASSERT(kNumDaysInHistorySummary <= kNumDaysInHistory, // TODO(marq): Rename these histogram buckets with s/DISABLED/RESTRICTED/, so // their names match the behavior they track. enum ProbeURLFetchResult { - // The probe failed because the internet was disconnected. + // The probe failed because the Internet was disconnected. INTERNET_DISCONNECTED = 0, // The probe failed for any other reason, and as a result, the proxy was @@ -73,8 +76,6 @@ COMPILE_ASSERT(kNumDaysInHistorySummary <= kNumDaysInHistory, PROBE_URL_FETCH_RESULT_COUNT }; -} // namespace spdyproxy - // Central point for configuring the data reduction proxy. // This object lives on the UI thread and all of its methods are expected to // be called from there. @@ -91,24 +92,20 @@ class DataReductionProxySettings DataReductionProxySettings(); virtual ~DataReductionProxySettings(); - void InitDataReductionProxySettings(); + // Initializes the data reduction proxy with profile and local state prefs, + // and a |UrlRequestContextGetter| for canary probes. The caller must ensure + // that all parameters remain alive for the lifetime of the + // |DataReductionProxySettings| instance. + void InitDataReductionProxySettings( + PrefService* prefs, + PrefService* local_state_prefs, + net::URLRequestContextGetter* url_request_context_getter, + scoped_ptr<DataReductionProxyConfigurator> config); // If proxy authentication is compiled in, pre-cache authentication // keys for all configured proxies in |session|. static void InitDataReductionProxySession(net::HttpNetworkSession* session); - // Add a host pattern to bypass. This should follow the same syntax used - // in net::ProxyBypassRules; that is, a hostname pattern, a hostname suffix - // pattern, an IP literal, a CIDR block, or the magic string '<local>'. - // Bypass settings persist for the life of this object and are applied - // each time the proxy is enabled, but are not updated while it is enabled. - void AddHostPatternToBypass(const std::string& pattern); - - // Add a URL pattern to bypass the proxy. The base implementation strips - // everything in |pattern| after the first single slash and then treats it - // as a hostname pattern. Subclasses may implement other semantics. - virtual void AddURLPatternToBypass(const std::string& pattern); - // Returns true if the data reduction proxy is allowed to be used on this // instance of Chrome. This could return false, for example, if this instance // is not part of the field trial, or if the proxy name is not configured @@ -201,12 +198,15 @@ class DataReductionProxySettings // customer feedback. Virtual so tests can mock it for verification. virtual void LogProxyState(bool enabled, bool restricted, bool at_startup); - // Accessor for unit tests. - std::vector<std::string> BypassRules() { return bypass_rules_;} - // Virtualized for mocking - virtual void RecordProbeURLFetchResult(spdyproxy::ProbeURLFetchResult result); - virtual void RecordStartupState(spdyproxy::ProxyStartupState state); + virtual void RecordProbeURLFetchResult( + data_reduction_proxy::ProbeURLFetchResult result); + virtual void RecordStartupState( + data_reduction_proxy::ProxyStartupState state); + + DataReductionProxyConfigurator* config() { + return config_.get(); + } private: friend class DataReductionProxySettingsTestBase; @@ -237,6 +237,8 @@ class DataReductionProxySettings TestInitDataReductionProxyOff); FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest, TestBypassList); + FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsTest, + CheckInitMetricsWhenNotAllowed); // NetworkChangeNotifier::IPAddressObserver: virtual void OnIPAddressChanged() OVERRIDE; @@ -262,15 +264,24 @@ class DataReductionProxySettings // the data reduction proxy feature isn't available. static base::string16 AuthHashForSalt(int64 salt); - std::vector<std::string> bypass_rules_; - bool restricted_by_carrier_; bool enabled_by_user_; scoped_ptr<net::URLFetcher> fetcher_; BooleanPrefMember spdy_proxy_auth_enabled_; + PrefService* prefs_; + PrefService* local_state_prefs_; + + net::URLRequestContextGetter* url_request_context_getter_; + + scoped_ptr<DataReductionProxyConfigurator> config_; + + base::ThreadChecker thread_checker_; + DISALLOW_COPY_AND_ASSIGN(DataReductionProxySettings); }; -#endif // CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_SETTINGS_H_ +} // namespace data_reduction_proxy + +#endif // COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_SETTINGS_H_ diff --git a/components/data_reduction_proxy/browser/data_reduction_proxy_settings_test_utils.cc b/components/data_reduction_proxy/browser/data_reduction_proxy_settings_test_utils.cc new file mode 100644 index 0000000..325500d --- /dev/null +++ b/components/data_reduction_proxy/browser/data_reduction_proxy_settings_test_utils.cc @@ -0,0 +1,247 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings_test_utils.h" + +#include "base/command_line.h" +#include "base/message_loop/message_loop.h" +#include "base/prefs/pref_registry_simple.h" +#include "base/prefs/scoped_user_pref_update.h" +#include "base/strings/string_number_conversions.h" +#include "components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h" +#include "components/data_reduction_proxy/common/data_reduction_proxy_switches.h" + +using testing::_; +using testing::AnyNumber; +using testing::Return; + +namespace { + +const char kDataReductionProxy[] = "https://foo.com:443/"; +const char kDataReductionProxyFallback[] = "http://bar.com:80"; +const char kDataReductionProxyKey[] = "12345"; + +const char kProbeURLWithOKResponse[] = "http://ok.org/"; + +const char kProxy[] = "proxy"; + +} // namespace + +namespace data_reduction_proxy { + +// Transform "normal"-looking headers (\n-separated) to the appropriate +// input format for ParseRawHeaders (\0-separated). +void HeadersToRaw(std::string* headers) { + std::replace(headers->begin(), headers->end(), '\n', '\0'); + if (!headers->empty()) + *headers += '\0'; +} + +ProbeURLFetchResult FetchResult(bool enabled, bool success) { + if (enabled) { + if (success) + return SUCCEEDED_PROXY_ALREADY_ENABLED; + return FAILED_PROXY_DISABLED; + } + if (success) + return SUCCEEDED_PROXY_ENABLED; + return FAILED_PROXY_ALREADY_DISABLED; +} + +void TestDataReductionProxyConfig::Enable(bool restricted, + const std::string& primary_origin, + const std::string& fallback_origin) { + enabled_ = true; + restricted_ = restricted; +} + +void TestDataReductionProxyConfig::Disable() { + enabled_ = false; + restricted_ = false; +} + +DataReductionProxySettingsTestBase::DataReductionProxySettingsTestBase() + : testing::Test() { +} + +DataReductionProxySettingsTestBase::~DataReductionProxySettingsTestBase() {} + +void DataReductionProxySettingsTestBase::AddProxyToCommandLine() { + CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kDataReductionProxy, kDataReductionProxy); + CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kDataReductionProxyFallback, kDataReductionProxyFallback); + CommandLine::ForCurrentProcess()->AppendSwitchASCII( + switches::kDataReductionProxyKey, kDataReductionProxyKey); +} + +// testing::Test implementation: +void DataReductionProxySettingsTestBase::SetUp() { + PrefRegistrySimple* registry = pref_service_.registry(); + registry->RegisterListPref(prefs::kDailyHttpOriginalContentLength); + registry->RegisterListPref(prefs::kDailyHttpReceivedContentLength); + registry->RegisterInt64Pref(prefs::kDailyHttpContentLengthLastUpdateDate, + 0L); + registry->RegisterDictionaryPref(kProxy); + registry->RegisterBooleanPref(prefs::kDataReductionProxyEnabled, false); + registry->RegisterBooleanPref(prefs::kDataReductionProxyWasEnabledBefore, + false); + ResetSettings(); + + ListPrefUpdate original_update(&pref_service_, + prefs::kDailyHttpOriginalContentLength); + ListPrefUpdate received_update(&pref_service_, + prefs::kDailyHttpReceivedContentLength); + for (int64 i = 0; i < kNumDaysInHistory; i++) { + original_update->Insert(0, + new base::StringValue(base::Int64ToString(2 * i))); + received_update->Insert(0, new base::StringValue(base::Int64ToString(i))); + } + last_update_time_ = base::Time::Now().LocalMidnight(); + pref_service_.SetInt64( + prefs::kDailyHttpContentLengthLastUpdateDate, + last_update_time_.ToInternalValue()); +} + +template <class C> +void DataReductionProxySettingsTestBase::ResetSettings() { + MockDataReductionProxySettings<C>* settings = + new MockDataReductionProxySettings<C>; + EXPECT_CALL(*settings, GetOriginalProfilePrefs()) + .Times(AnyNumber()) + .WillRepeatedly(Return(&pref_service_)); + EXPECT_CALL(*settings, GetLocalStatePrefs()) + .Times(AnyNumber()) + .WillRepeatedly(Return(&pref_service_)); + EXPECT_CALL(*settings, GetURLFetcher()).Times(0); + EXPECT_CALL(*settings, LogProxyState(_, _, _)).Times(0); + settings_.reset(settings); + settings_->config_.reset(new TestDataReductionProxyConfig()); +} + +// Explicitly generate required instantiations. +template void +DataReductionProxySettingsTestBase::ResetSettings<DataReductionProxySettings>(); + +template <class C> +void DataReductionProxySettingsTestBase::SetProbeResult( + const std::string& test_url, + const std::string& response, + ProbeURLFetchResult result, + bool success, + int expected_calls) { + MockDataReductionProxySettings<C>* settings = + static_cast<MockDataReductionProxySettings<C>*>(settings_.get()); + if (0 == expected_calls) { + EXPECT_CALL(*settings, GetURLFetcher()).Times(0); + EXPECT_CALL(*settings, RecordProbeURLFetchResult(_)).Times(0); + } else { + EXPECT_CALL(*settings, RecordProbeURLFetchResult(result)).Times(1); + EXPECT_CALL(*settings, GetURLFetcher()) + .Times(expected_calls) + .WillRepeatedly(Return(new net::FakeURLFetcher( + GURL(test_url), + settings, + response, + success ? net::HTTP_OK : net::HTTP_INTERNAL_SERVER_ERROR, + success ? net::URLRequestStatus::SUCCESS : + net::URLRequestStatus::FAILED))); + } +} + +// Explicitly generate required instantiations. +template void +DataReductionProxySettingsTestBase::SetProbeResult<DataReductionProxySettings>( + const std::string& test_url, + const std::string& response, + ProbeURLFetchResult result, + bool success, + int expected_calls); + +void DataReductionProxySettingsTestBase::CheckProxyConfigs( + bool expected_enabled, bool expected_restricted) { + TestDataReductionProxyConfig* config = + static_cast<TestDataReductionProxyConfig*>(settings_->config_.get()); + ASSERT_EQ(expected_restricted, config->restricted_); + ASSERT_EQ(expected_enabled, config->enabled_); +} + +void DataReductionProxySettingsTestBase::CheckProbe( + bool initially_enabled, + const std::string& probe_url, + const std::string& response, + bool request_succeeded, + bool expected_enabled, + bool expected_restricted) { + pref_service_.SetBoolean(prefs::kDataReductionProxyEnabled, + initially_enabled); + if (initially_enabled) + settings_->enabled_by_user_ = true; + settings_->restricted_by_carrier_ = false; + SetProbeResult(probe_url, + response, + FetchResult(initially_enabled, + request_succeeded && (response == "OK")), + request_succeeded, + initially_enabled ? 1 : 0); + settings_->MaybeActivateDataReductionProxy(false); + base::MessageLoop::current()->RunUntilIdle(); + CheckProxyConfigs(expected_enabled, expected_restricted); +} + +void DataReductionProxySettingsTestBase::CheckProbeOnIPChange( + const std::string& probe_url, + const std::string& response, + bool request_succeeded, + bool expected_restricted) { + SetProbeResult(probe_url, + response, + FetchResult(!settings_->restricted_by_carrier_, + request_succeeded && (response == "OK")), + request_succeeded, + 1); + settings_->OnIPAddressChanged(); + base::MessageLoop::current()->RunUntilIdle(); + CheckProxyConfigs(true, expected_restricted); +} + +void DataReductionProxySettingsTestBase::CheckOnPrefChange( + bool enabled, + bool expected_enabled) { + // Always have a sucessful probe for pref change tests. + SetProbeResult(kProbeURLWithOKResponse, + "OK", + FetchResult(enabled, true), + true, + expected_enabled ? 1 : 0); + pref_service_.SetBoolean(prefs::kDataReductionProxyEnabled, enabled); + base::MessageLoop::current()->RunUntilIdle(); + // Never expect the proxy to be restricted for pref change tests. + CheckProxyConfigs(expected_enabled, false); +} + +void DataReductionProxySettingsTestBase::CheckInitDataReductionProxy( + bool enabled_at_startup) { + AddProxyToCommandLine(); + base::MessageLoopForUI loop; + SetProbeResult(kProbeURLWithOKResponse, + "OK", + FetchResult(enabled_at_startup, true), + true, + enabled_at_startup ? 1 : 0); + scoped_ptr<DataReductionProxyConfigurator> configurator( + new TestDataReductionProxyConfig()); + scoped_refptr<net::TestURLRequestContextGetter> request_context = + new net::TestURLRequestContextGetter(base::MessageLoopProxy::current()); + settings_->InitDataReductionProxySettings( + &pref_service_, + &pref_service_, + request_context.get(), + configurator.Pass()); + + base::MessageLoop::current()->RunUntilIdle(); + CheckProxyConfigs(enabled_at_startup, false); +} + +} // namespace data_reduction_proxy diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_unittest.h b/components/data_reduction_proxy/browser/data_reduction_proxy_settings_test_utils.h index 8f25cdb..d96b46e 100644 --- a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_unittest.h +++ b/components/data_reduction_proxy/browser/data_reduction_proxy_settings_test_utils.h @@ -1,24 +1,44 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_SETTINGS_UNITTEST_H_ -#define CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_SETTINGS_UNITTEST_H_ +#ifndef COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_SETTINGS_TEST_UTILS_H_ +#define COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_SETTINGS_TEST_UTILS_H_ -#include "base/metrics/field_trial.h" -#include "base/metrics/histogram_samples.h" #include "base/prefs/testing_pref_service.h" -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_configurator.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h" #include "net/url_request/test_url_fetcher_factory.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" class PrefService; class TestingPrefServiceSimple; -using spdyproxy::ProbeURLFetchResult; -using spdyproxy::ProxyStartupState; +namespace data_reduction_proxy { + +class TestDataReductionProxyConfig : public DataReductionProxyConfigurator { + public: + TestDataReductionProxyConfig() + : enabled_(false), restricted_(false) {} + virtual ~TestDataReductionProxyConfig() {} + virtual void Enable(bool restricted, + const std::string& primary_origin, + const std::string& fallback_origin) OVERRIDE; + virtual void Disable() OVERRIDE; + virtual void AddHostPatternToBypass(const std::string& pattern) OVERRIDE {} + virtual void AddURLPatternToBypass(const std::string& pattern) OVERRIDE {} + + // True if the proxy has been enabled, i.e., only after |Enable| has been + // called. Defaults to false. + bool enabled_; + + // Describes whether the proxy has been put in a restricted mode. True if + // |Enable| is called with |restricted| set to true. Defaults to false. + bool restricted_; +}; template <class C> class MockDataReductionProxySettings : public C { @@ -65,8 +85,6 @@ class DataReductionProxySettingsTestBase : public testing::Test { bool success, int expected_calls) = 0; - void CheckProxyPref(const std::string& expected_servers, - const std::string& expected_mode); void CheckProxyConfigs(bool expected_enabled, bool expected_restricted); void CheckProbe(bool initially_enabled, const std::string& probe_url, @@ -84,8 +102,6 @@ class DataReductionProxySettingsTestBase : public testing::Test { TestingPrefServiceSimple pref_service_; scoped_ptr<DataReductionProxySettings> settings_; base::Time last_update_time_; - // This is a singleton that will clear all set field trials on destruction. - scoped_ptr<base::FieldTrialList> field_trial_list_; }; // Test implementations should be subclasses of an instantiation of this @@ -110,4 +126,6 @@ class ConcreteDataReductionProxySettingsTest } }; -#endif // CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_SETTINGS_UNITTEST_H_ +} // namespace data_reduction_proxy + +#endif // COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_DATA_REDUCTION_PROXY_SETTINGS_TEST_UTILS_H_ diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_unittest.cc b/components/data_reduction_proxy/browser/data_reduction_proxy_settings_unittest.cc index 17841fb..1ad5829 100644 --- a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_unittest.cc +++ b/components/data_reduction_proxy/browser/data_reduction_proxy_settings_unittest.cc @@ -1,282 +1,40 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings_unittest.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h" #include "base/command_line.h" #include "base/md5.h" -#include "base/metrics/field_trial.h" -#include "base/metrics/histogram_samples.h" -#include "base/metrics/statistics_recorder.h" -#include "base/prefs/pref_registry_simple.h" -#include "base/prefs/pref_service.h" -#include "base/prefs/scoped_user_pref_update.h" -#include "base/prefs/testing_pref_service.h" -#include "base/strings/string_number_conversions.h" +#include "base/message_loop/message_loop.h" #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings.h" -#include "chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.h" -#include "chrome/browser/prefs/proxy_prefs.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/metrics/variations/variations_util.h" -#include "chrome/common/pref_names.h" -#include "components/variations/entropy_provider.h" -#include "net/base/auth.h" -#include "net/base/host_port_pair.h" +#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings_test_utils.h" +#include "components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h" +#include "components/data_reduction_proxy/common/data_reduction_proxy_switches.h" #include "net/http/http_auth.h" #include "net/http/http_auth_cache.h" -#include "net/http/http_response_headers.h" -#include "net/http/http_status_code.h" -#include "net/url_request/test_url_fetcher_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" -using testing::_; -using testing::AnyNumber; -using testing::Return; +namespace { -const char kDataReductionProxyOrigin[] = "https://foo.com:443/"; -const char kDataReductionProxyDevHost[] = "http://foo-dev.com:80"; +const char kDataReductionProxy[] = "https://foo.com:443/"; +const char kDataReductionProxyDev[] = "http://foo-dev.com:80"; const char kDataReductionProxyFallback[] = "http://bar.com:80"; -const char kDataReductionProxyAuth[] = "12345"; +const char kDataReductionProxyKey[] = "12345"; const char kProbeURLWithOKResponse[] = "http://ok.org/"; const char kProbeURLWithBadResponse[] = "http://bad.org/"; const char kProbeURLWithNoResponse[] = "http://no.org/"; -// Transform "normal"-looking headers (\n-separated) to the appropriate -// input format for ParseRawHeaders (\0-separated). -void HeadersToRaw(std::string* headers) { - std::replace(headers->begin(), headers->end(), '\n', '\0'); - if (!headers->empty()) - *headers += '\0'; -} - -ProbeURLFetchResult FetchResult(bool enabled, bool success) { - if (enabled) { - if (success) - return spdyproxy::SUCCEEDED_PROXY_ALREADY_ENABLED; - else - return spdyproxy::FAILED_PROXY_DISABLED; - } else { - if (success) - return spdyproxy::SUCCEEDED_PROXY_ENABLED; - else - return spdyproxy::FAILED_PROXY_ALREADY_DISABLED; - } -} - -DataReductionProxySettingsTestBase::DataReductionProxySettingsTestBase() - : testing::Test() { -} - -DataReductionProxySettingsTestBase::~DataReductionProxySettingsTestBase() {} - -void DataReductionProxySettingsTestBase::AddProxyToCommandLine() { - CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kSpdyProxyAuthOrigin, kDataReductionProxyOrigin); - CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kSpdyProxyAuthFallback, kDataReductionProxyFallback); - CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kSpdyProxyAuthValue, kDataReductionProxyAuth); -} - -// testing::Test implementation: -void DataReductionProxySettingsTestBase::SetUp() { - PrefRegistrySimple* registry = pref_service_.registry(); - registry->RegisterListPref(prefs::kDailyHttpOriginalContentLength); - registry->RegisterListPref(prefs::kDailyHttpReceivedContentLength); - registry->RegisterInt64Pref( - prefs::kDailyHttpContentLengthLastUpdateDate, 0L); - registry->RegisterDictionaryPref(prefs::kProxy); - registry->RegisterBooleanPref(prefs::kSpdyProxyAuthEnabled, false); - registry->RegisterBooleanPref(prefs::kSpdyProxyAuthWasEnabledBefore, false); - ResetSettings(); - - ListPrefUpdate original_update(&pref_service_, - prefs::kDailyHttpOriginalContentLength); - ListPrefUpdate received_update(&pref_service_, - prefs::kDailyHttpReceivedContentLength); - for (int64 i = 0; i < spdyproxy::kNumDaysInHistory; i++) { - original_update->Insert(0, - new base::StringValue(base::Int64ToString(2 * i))); - received_update->Insert(0, new base::StringValue(base::Int64ToString(i))); - } - last_update_time_ = base::Time::Now().LocalMidnight(); - pref_service_.SetInt64( - prefs::kDailyHttpContentLengthLastUpdateDate, - last_update_time_.ToInternalValue()); -} - -template <class C> -void DataReductionProxySettingsTestBase::ResetSettings() { - MockDataReductionProxySettings<C>* settings = - new MockDataReductionProxySettings<C>; - EXPECT_CALL(*settings, GetOriginalProfilePrefs()) - .Times(AnyNumber()) - .WillRepeatedly(Return(&pref_service_)); - EXPECT_CALL(*settings, GetLocalStatePrefs()) - .Times(AnyNumber()) - .WillRepeatedly(Return(&pref_service_)); - EXPECT_CALL(*settings, GetURLFetcher()).Times(0); - EXPECT_CALL(*settings, LogProxyState(_, _, _)).Times(0); - settings_.reset(settings); -} - -// Explicitly generate required instantiations. -template void -DataReductionProxySettingsTestBase::ResetSettings<DataReductionProxySettings>(); -template void -DataReductionProxySettingsTestBase::ResetSettings< - DataReductionProxySettingsAndroid>(); - -template <class C> -void DataReductionProxySettingsTestBase::SetProbeResult( - const std::string& test_url, - const std::string& response, - ProbeURLFetchResult result, - bool success, - int expected_calls) { - MockDataReductionProxySettings<C>* settings = - static_cast<MockDataReductionProxySettings<C>*>(settings_.get()); - if (0 == expected_calls) { - EXPECT_CALL(*settings, GetURLFetcher()).Times(0); - EXPECT_CALL(*settings, RecordProbeURLFetchResult(_)).Times(0); - } else { - EXPECT_CALL(*settings, RecordProbeURLFetchResult(result)).Times(1); - EXPECT_CALL(*settings, GetURLFetcher()) - .Times(expected_calls) - .WillRepeatedly(Return(new net::FakeURLFetcher( - GURL(test_url), - settings, - response, - success ? net::HTTP_OK : net::HTTP_INTERNAL_SERVER_ERROR, - success ? net::URLRequestStatus::SUCCESS : - net::URLRequestStatus::FAILED))); - } -} - -// Explicitly generate required instantiations. -template void -DataReductionProxySettingsTestBase::SetProbeResult<DataReductionProxySettings>( - const std::string& test_url, - const std::string& response, - ProbeURLFetchResult result, - bool success, - int expected_calls); -template void -DataReductionProxySettingsTestBase::SetProbeResult< - DataReductionProxySettingsAndroid>(const std::string& test_url, - const std::string& response, - ProbeURLFetchResult result, - bool success, - int expected_calls); - -void DataReductionProxySettingsTestBase::CheckProxyPref( - const std::string& expected_servers, - const std::string& expected_mode) { - const base::DictionaryValue* dict = - pref_service_.GetDictionary(prefs::kProxy); - std::string mode; - std::string server; - dict->GetString("mode", &mode); - ASSERT_EQ(expected_mode, mode); - dict->GetString("server", &server); - ASSERT_EQ(expected_servers, server); -} - -void DataReductionProxySettingsTestBase::CheckProxyConfigs( - bool expected_enabled, bool expected_restricted) { - if (expected_enabled) { - std::string main_proxy = kDataReductionProxyOrigin; - std::string fallback_proxy = kDataReductionProxyFallback; - std::string servers = expected_restricted ? - "http=" + fallback_proxy + ",direct://;" : - "http=" + main_proxy + "," + fallback_proxy + ",direct://;"; - CheckProxyPref(servers, - ProxyModeToString(ProxyPrefs::MODE_FIXED_SERVERS)); - } else { - CheckProxyPref(std::string(), ProxyModeToString(ProxyPrefs::MODE_SYSTEM)); - } -} - -void DataReductionProxySettingsTestBase::CheckProbe( - bool initially_enabled, - const std::string& probe_url, - const std::string& response, - bool request_succeeded, - bool expected_enabled, - bool expected_restricted) { - pref_service_.SetBoolean(prefs::kSpdyProxyAuthEnabled, initially_enabled); - if (initially_enabled) - settings_->enabled_by_user_ = true; - settings_->restricted_by_carrier_ = false; - SetProbeResult(probe_url, - response, - FetchResult(initially_enabled, - request_succeeded && (response == "OK")), - request_succeeded, - initially_enabled ? 1 : 0); - settings_->MaybeActivateDataReductionProxy(false); - base::MessageLoop::current()->RunUntilIdle(); - CheckProxyConfigs(expected_enabled, expected_restricted); -} - -void DataReductionProxySettingsTestBase::CheckProbeOnIPChange( - const std::string& probe_url, - const std::string& response, - bool request_succeeded, - bool expected_restricted) { - SetProbeResult(probe_url, - response, - FetchResult(!settings_->restricted_by_carrier_, - request_succeeded && (response == "OK")), - request_succeeded, - 1); - settings_->OnIPAddressChanged(); - base::MessageLoop::current()->RunUntilIdle(); - CheckProxyConfigs(true, expected_restricted); -} - -void DataReductionProxySettingsTestBase::CheckOnPrefChange( - bool enabled, - bool expected_enabled) { - // Always have a sucessful probe for pref change tests. - SetProbeResult(kProbeURLWithOKResponse, - "OK", - FetchResult(enabled, true), - true, - expected_enabled ? 1 : 0); - pref_service_.SetBoolean(prefs::kSpdyProxyAuthEnabled, enabled); - base::MessageLoop::current()->RunUntilIdle(); - // Never expect the proxy to be restricted for pref change tests. - CheckProxyConfigs(expected_enabled, false); -} - -void DataReductionProxySettingsTestBase::CheckInitDataReductionProxy( - bool enabled_at_startup) { - AddProxyToCommandLine(); - base::MessageLoopForUI loop; - SetProbeResult(kProbeURLWithOKResponse, - "OK", - FetchResult(enabled_at_startup, true), - true, - enabled_at_startup ? 1 : 0); - settings_->InitDataReductionProxySettings(); - base::MessageLoop::current()->RunUntilIdle(); - if (enabled_at_startup) { - CheckProxyConfigs(enabled_at_startup, false); - } else { - CheckProxyPref(std::string(), ProxyModeToString(ProxyPrefs::MODE_SYSTEM)); - } -} +} // namespace +namespace data_reduction_proxy { class DataReductionProxySettingsTest : public ConcreteDataReductionProxySettingsTest< - DataReductionProxySettings> { + DataReductionProxySettings> { }; @@ -305,16 +63,16 @@ TEST_F(DataReductionProxySettingsTest, TestGetDataReductionProxyOrigin) { // SetUp() adds the origin to the command line, which should be returned here. std::string result = DataReductionProxySettings::GetDataReductionProxyOrigin(); - EXPECT_EQ(kDataReductionProxyOrigin, result); + EXPECT_EQ(kDataReductionProxy, result); } TEST_F(DataReductionProxySettingsTest, TestGetDataReductionProxyDevOrigin) { AddProxyToCommandLine(); CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kSpdyProxyDevAuthOrigin, kDataReductionProxyDevHost); + switches::kDataReductionProxyDev, kDataReductionProxyDev); std::string result = DataReductionProxySettings::GetDataReductionProxyOrigin(); - EXPECT_EQ(kDataReductionProxyDevHost, result); + EXPECT_EQ(kDataReductionProxyDev, result); } TEST_F(DataReductionProxySettingsTest, TestGetDataReductionProxies) { @@ -334,7 +92,7 @@ TEST_F(DataReductionProxySettingsTest, TestGetDataReductionProxies) { // Adding just the fallback on the command line shouldn't add a proxy unless // there was already one compiled in. CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kSpdyProxyAuthFallback, kDataReductionProxyFallback); + switches::kDataReductionProxyFallback, kDataReductionProxyFallback); proxies = DataReductionProxySettings::GetDataReductionProxies(); // So: if there weren't any proxies before, there still won't be. @@ -344,7 +102,7 @@ TEST_F(DataReductionProxySettingsTest, TestGetDataReductionProxies) { EXPECT_EQ(expected_proxy_size, proxies.size()); CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kSpdyProxyAuthOrigin, kDataReductionProxyOrigin); + switches::kDataReductionProxy, kDataReductionProxy); proxies = DataReductionProxySettings::GetDataReductionProxies(); EXPECT_EQ(2u, proxies.size()); @@ -359,7 +117,7 @@ TEST_F(DataReductionProxySettingsTest, TestGetDataReductionProxies) { TEST_F(DataReductionProxySettingsTest, TestAuthHashGeneration) { AddProxyToCommandLine(); std::string salt = "8675309"; // Jenny's number to test the hash generator. - std::string salted_key = salt + kDataReductionProxyAuth + salt; + std::string salted_key = salt + kDataReductionProxyKey + salt; base::string16 expected_hash = base::UTF8ToUTF16(base::MD5String(salted_key)); EXPECT_EQ(expected_hash, DataReductionProxySettings::AuthHashForSalt(8675309)); @@ -371,28 +129,26 @@ TEST_F(DataReductionProxySettingsTest, TestAuthHashGeneration) { TEST_F(DataReductionProxySettingsTest, TestAuthHashGenerationWithOriginSetViaSwitch) { CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kSpdyProxyAuthOrigin, kDataReductionProxyOrigin); + switches::kDataReductionProxy, kDataReductionProxy); EXPECT_EQ(base::string16(), DataReductionProxySettings::AuthHashForSalt(8675309)); } - TEST_F(DataReductionProxySettingsTest, TestIsProxyEnabledOrManaged) { settings_->InitPrefMembers(); EXPECT_FALSE(settings_->IsDataReductionProxyEnabled()); EXPECT_FALSE(settings_->IsDataReductionProxyManaged()); - pref_service_.SetBoolean(prefs::kSpdyProxyAuthEnabled, true); + pref_service_.SetBoolean(prefs::kDataReductionProxyEnabled, true); EXPECT_TRUE(settings_->IsDataReductionProxyEnabled()); EXPECT_FALSE(settings_->IsDataReductionProxyManaged()); - pref_service_.SetManagedPref(prefs::kSpdyProxyAuthEnabled, + pref_service_.SetManagedPref(prefs::kDataReductionProxyEnabled, base::Value::CreateBooleanValue(true)); EXPECT_TRUE(settings_->IsDataReductionProxyEnabled()); EXPECT_TRUE(settings_->IsDataReductionProxyManaged()); } - TEST_F(DataReductionProxySettingsTest, TestAcceptableChallenges) { AddProxyToCommandLine(); typedef struct { @@ -443,7 +199,7 @@ TEST_F(DataReductionProxySettingsTest, TestChallengeTokens) { for (int i = 0; i <= 4; ++i) { scoped_refptr<net::AuthChallengeInfo> auth_info(new net::AuthChallengeInfo); auth_info->challenger = - net::HostPortPair::FromString(kDataReductionProxyOrigin); + net::HostPortPair::FromString(kDataReductionProxy); auth_info->realm = tests[i].realm; base::string16 token = settings_->GetTokenForAuthChallenge(auth_info.get()); EXPECT_EQ(tests[i].expected_empty_token, token.empty()); @@ -455,7 +211,7 @@ TEST_F(DataReductionProxySettingsTest, TestResetDataReductionStatistics) { int64 received_content_length; int64 last_update_time; settings_->ResetDataReductionStatistics(); - settings_->GetContentLengths(spdyproxy::kNumDaysInHistory, + settings_->GetContentLengths(kNumDaysInHistory, &original_content_length, &received_content_length, &last_update_time); @@ -470,11 +226,11 @@ TEST_F(DataReductionProxySettingsTest, TestContentLengths) { int64 last_update_time; // Request |kNumDaysInHistory| days. - settings_->GetContentLengths(spdyproxy::kNumDaysInHistory, + settings_->GetContentLengths(kNumDaysInHistory, &original_content_length, &received_content_length, &last_update_time); - const unsigned int days = spdyproxy::kNumDaysInHistory; + const unsigned int days = kNumDaysInHistory; // Received content length history values are 0 to |kNumDaysInHistory - 1|. int64 expected_total_received_content_length = (days - 1L) * days / 2; // Original content length history values are 0 to @@ -485,7 +241,7 @@ TEST_F(DataReductionProxySettingsTest, TestContentLengths) { EXPECT_EQ(last_update_time_.ToInternalValue(), last_update_time); // Request |kNumDaysInHistory - 1| days. - settings_->GetContentLengths(spdyproxy::kNumDaysInHistory - 1, + settings_->GetContentLengths(kNumDaysInHistory - 1, &original_content_length, &received_content_length, &last_update_time); @@ -522,7 +278,7 @@ TEST_F(DataReductionProxySettingsTest, TestMaybeActivateDataReductionProxy) { // so it won't trigger MaybeActivateDataReductionProxy when the pref value // is set. settings_->spdy_proxy_auth_enabled_.Init( - prefs::kSpdyProxyAuthEnabled, + prefs::kDataReductionProxyEnabled, settings_->GetOriginalProfilePrefs()); // TODO(bengr): Test enabling/disabling while a probe is outstanding. @@ -543,9 +299,9 @@ TEST_F(DataReductionProxySettingsTest, TestOnIPAddressChanged) { AddProxyToCommandLine(); base::MessageLoopForUI loop; // The proxy is enabled initially. - pref_service_.SetBoolean(prefs::kSpdyProxyAuthEnabled, true); + pref_service_.SetBoolean(prefs::kDataReductionProxyEnabled, true); settings_->spdy_proxy_auth_enabled_.Init( - prefs::kSpdyProxyAuthEnabled, + prefs::kDataReductionProxyEnabled, settings_->GetOriginalProfilePrefs()); settings_->enabled_by_user_ = true; settings_->restricted_by_carrier_ = false; @@ -576,9 +332,9 @@ TEST_F(DataReductionProxySettingsTest, TestOnProxyEnabledPrefChange) { TEST_F(DataReductionProxySettingsTest, TestInitDataReductionProxyOn) { MockSettings* settings = static_cast<MockSettings*>(settings_.get()); - EXPECT_CALL(*settings, RecordStartupState(spdyproxy::PROXY_ENABLED)); + EXPECT_CALL(*settings, RecordStartupState(PROXY_ENABLED)); - pref_service_.SetBoolean(prefs::kSpdyProxyAuthEnabled, true); + pref_service_.SetBoolean(prefs::kDataReductionProxyEnabled, true); CheckInitDataReductionProxy(true); } @@ -586,18 +342,18 @@ TEST_F(DataReductionProxySettingsTest, TestInitDataReductionProxyOff) { // InitDataReductionProxySettings with the preference off will directly call // LogProxyState. MockSettings* settings = static_cast<MockSettings*>(settings_.get()); - EXPECT_CALL(*settings, RecordStartupState(spdyproxy::PROXY_DISABLED)); + EXPECT_CALL(*settings, RecordStartupState(PROXY_DISABLED)); - pref_service_.SetBoolean(prefs::kSpdyProxyAuthEnabled, false); + pref_service_.SetBoolean(prefs::kDataReductionProxyEnabled, false); CheckInitDataReductionProxy(false); } TEST_F(DataReductionProxySettingsTest, TestSetProxyFromCommandLine) { MockSettings* settings = static_cast<MockSettings*>(settings_.get()); - EXPECT_CALL(*settings, RecordStartupState(spdyproxy::PROXY_ENABLED)); + EXPECT_CALL(*settings, RecordStartupState(PROXY_ENABLED)); CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableSpdyProxyAuth); + switches::kEnableDataReductionProxy); CheckInitDataReductionProxy(true); } @@ -606,45 +362,32 @@ TEST_F(DataReductionProxySettingsTest, TestGetDailyContentLengths) { settings_->GetDailyContentLengths(prefs::kDailyHttpOriginalContentLength); ASSERT_FALSE(result.empty()); - ASSERT_EQ(spdyproxy::kNumDaysInHistory, result.size()); + ASSERT_EQ(kNumDaysInHistory, result.size()); - for (size_t i = 0; i < spdyproxy::kNumDaysInHistory; ++i) { + for (size_t i = 0; i < kNumDaysInHistory; ++i) { long expected_length = - static_cast<long>((spdyproxy::kNumDaysInHistory - 1 - i) * 2); + static_cast<long>((kNumDaysInHistory - 1 - i) * 2); ASSERT_EQ(expected_length, result[i]); } } -TEST_F(DataReductionProxySettingsTest, TestBypassList) { - settings_->AddHostPatternToBypass("http://www.google.com"); - settings_->AddHostPatternToBypass("fefe:13::abc/33"); - settings_->AddURLPatternToBypass("foo.org/images/*"); - settings_->AddURLPatternToBypass("http://foo.com/*"); - settings_->AddURLPatternToBypass("http://baz.com:22/bar/*"); - settings_->AddURLPatternToBypass("http://*bat.com/bar/*"); - - std::string expected[] = { - "http://www.google.com", - "fefe:13::abc/33", - "foo.org", - "http://foo.com", - "http://baz.com:22", - "http://*bat.com" - }; - - ASSERT_EQ(settings_->bypass_rules_.size(), 6u); - int i = 0; - for (std::vector<std::string>::iterator it = settings_->bypass_rules_.begin(); - it != settings_->bypass_rules_.end(); ++it) { - EXPECT_EQ(expected[i++], *it); - } -} - TEST_F(DataReductionProxySettingsTest, CheckInitMetricsWhenNotAllowed) { // No call to |AddProxyToCommandLine()| was made, so the proxy feature // should be unavailable. + base::MessageLoopForUI loop; EXPECT_FALSE(DataReductionProxySettings::IsDataReductionProxyAllowed()); MockSettings* settings = static_cast<MockSettings*>(settings_.get()); - EXPECT_CALL(*settings, RecordStartupState(spdyproxy::PROXY_NOT_AVAILABLE)); - settings_->InitDataReductionProxySettings(); + EXPECT_CALL(*settings, RecordStartupState(PROXY_NOT_AVAILABLE)); + + scoped_ptr<DataReductionProxyConfigurator> configurator( + new TestDataReductionProxyConfig()); + scoped_refptr<net::TestURLRequestContextGetter> request_context = + new net::TestURLRequestContextGetter(base::MessageLoopProxy::current()); + settings_->InitDataReductionProxySettings( + &pref_service_, &pref_service_, request_context.get(), + configurator.Pass()); + + base::MessageLoop::current()->RunUntilIdle(); } + +} // namespace data_reduction_proxy diff --git a/chrome/browser/net/spdyproxy/http_auth_handler_spdyproxy.cc b/components/data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy.cc index 6050639..34fa1cd9 100644 --- a/chrome/browser/net/spdyproxy/http_auth_handler_spdyproxy.cc +++ b/components/data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/net/spdyproxy/http_auth_handler_spdyproxy.h" +#include "components/data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy.h" #include <algorithm> #include <string> @@ -17,7 +17,7 @@ #include "net/http/http_auth_challenge_tokenizer.h" #include "net/http/http_request_info.h" -namespace spdyproxy { +namespace data_reduction_proxy { using net::AuthCredentials; using net::BoundNetLog; @@ -29,7 +29,7 @@ using net::HttpAuthHandlerFactory; using net::HttpRequestInfo; using net::HttpUtil; -HttpAuthHandlerSpdyProxy::Factory::Factory( +HttpAuthHandlerDataReductionProxy::Factory::Factory( const std::vector<GURL>& authorized_spdyproxy_origins) { for (unsigned int i = 0; i < authorized_spdyproxy_origins.size(); ++i) { if (authorized_spdyproxy_origins[i].possibly_invalid_spec().empty()) { @@ -40,10 +40,10 @@ HttpAuthHandlerSpdyProxy::Factory::Factory( authorized_spdyproxy_origins_ = authorized_spdyproxy_origins; } -HttpAuthHandlerSpdyProxy::Factory::~Factory() { +HttpAuthHandlerDataReductionProxy::Factory::~Factory() { } -int HttpAuthHandlerSpdyProxy::Factory::CreateAuthHandler( +int HttpAuthHandlerDataReductionProxy::Factory::CreateAuthHandler( HttpAuthChallengeTokenizer* challenge, HttpAuth::Target target, const GURL& origin, @@ -69,7 +69,8 @@ int HttpAuthHandlerSpdyProxy::Factory::CreateAuthHandler( return net::ERR_UNSUPPORTED_AUTH_SCHEME; } - scoped_ptr<HttpAuthHandler> tmp_handler(new HttpAuthHandlerSpdyProxy()); + scoped_ptr<HttpAuthHandler> tmp_handler( + new HttpAuthHandlerDataReductionProxy()); if (!tmp_handler->InitFromChallenge(challenge, target, origin, net_log)) return net::ERR_INVALID_RESPONSE; handler->swap(tmp_handler); @@ -77,28 +78,28 @@ int HttpAuthHandlerSpdyProxy::Factory::CreateAuthHandler( } HttpAuth::AuthorizationResult -HttpAuthHandlerSpdyProxy::HandleAnotherChallenge( +HttpAuthHandlerDataReductionProxy::HandleAnotherChallenge( HttpAuthChallengeTokenizer* challenge) { // SpdyProxy authentication is always a single round, so any responses // should be treated as a rejection. return HttpAuth::AUTHORIZATION_RESULT_REJECT; } -bool HttpAuthHandlerSpdyProxy::NeedsIdentity() { +bool HttpAuthHandlerDataReductionProxy::NeedsIdentity() { return true; } -bool HttpAuthHandlerSpdyProxy::AllowsDefaultCredentials() { +bool HttpAuthHandlerDataReductionProxy::AllowsDefaultCredentials() { return false; } -bool HttpAuthHandlerSpdyProxy::AllowsExplicitCredentials() { +bool HttpAuthHandlerDataReductionProxy::AllowsExplicitCredentials() { return true; } -HttpAuthHandlerSpdyProxy::~HttpAuthHandlerSpdyProxy() {} +HttpAuthHandlerDataReductionProxy::~HttpAuthHandlerDataReductionProxy() {} -bool HttpAuthHandlerSpdyProxy::Init( +bool HttpAuthHandlerDataReductionProxy::Init( HttpAuthChallengeTokenizer* challenge) { auth_scheme_ = HttpAuth::AUTH_SCHEME_SPDYPROXY; score_ = 5; @@ -106,7 +107,7 @@ bool HttpAuthHandlerSpdyProxy::Init( return ParseChallenge(challenge); } -int HttpAuthHandlerSpdyProxy::GenerateAuthTokenImpl( +int HttpAuthHandlerDataReductionProxy::GenerateAuthTokenImpl( const AuthCredentials* credentials, const HttpRequestInfo* request, const CompletionCallback&, std::string* auth_token) { DCHECK(credentials); @@ -120,7 +121,7 @@ int HttpAuthHandlerSpdyProxy::GenerateAuthTokenImpl( return net::OK; } -bool HttpAuthHandlerSpdyProxy::ParseChallenge( +bool HttpAuthHandlerDataReductionProxy::ParseChallenge( HttpAuthChallengeTokenizer* challenge) { // Verify the challenge's auth-scheme. @@ -152,7 +153,7 @@ bool HttpAuthHandlerSpdyProxy::ParseChallenge( return true; } -bool HttpAuthHandlerSpdyProxy::ParseChallengeProperty( +bool HttpAuthHandlerDataReductionProxy::ParseChallengeProperty( const std::string& name, const std::string& value) { if (LowerCaseEqualsASCII(name, "realm")) { std::string realm; @@ -167,4 +168,4 @@ bool HttpAuthHandlerSpdyProxy::ParseChallengeProperty( return true; } -} // namespace spdyproxy +} // namespace data_reduction_proxy diff --git a/chrome/browser/net/spdyproxy/http_auth_handler_spdyproxy.h b/components/data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy.h index 570128d..b18cade 100644 --- a/chrome/browser/net/spdyproxy/http_auth_handler_spdyproxy.h +++ b/components/data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy.h @@ -1,9 +1,9 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_NET_SPDYPROXY_HTTP_AUTH_HANDLER_SPDYPROXY_H_ -#define CHROME_BROWSER_NET_SPDYPROXY_HTTP_AUTH_HANDLER_SPDYPROXY_H_ +#ifndef COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_HTTP_AUTH_HANDLER_DATA_REDUCTION_PROXY_H_ +#define COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_HTTP_AUTH_HANDLER_DATA_REDUCTION_PROXY_H_ #include <string> #include <vector> @@ -12,10 +12,10 @@ #include "net/http/http_auth_handler.h" #include "net/http/http_auth_handler_factory.h" -namespace spdyproxy { +namespace data_reduction_proxy { // Code for handling http SpdyProxy authentication. -class HttpAuthHandlerSpdyProxy : public net::HttpAuthHandler { +class HttpAuthHandlerDataReductionProxy : public net::HttpAuthHandler { public: class Factory : public net::HttpAuthHandlerFactory { public: @@ -39,7 +39,7 @@ class HttpAuthHandlerSpdyProxy : public net::HttpAuthHandler { }; // Constructs a new spdyproxy handler. - HttpAuthHandlerSpdyProxy() {} + HttpAuthHandlerDataReductionProxy() {} // Overrides from net::HttpAuthHandler. virtual net::HttpAuth::AuthorizationResult HandleAnotherChallenge( @@ -49,9 +49,10 @@ class HttpAuthHandlerSpdyProxy : public net::HttpAuthHandler { virtual bool AllowsExplicitCredentials() OVERRIDE; private: - FRIEND_TEST_ALL_PREFIXES(HttpAuthHandlerSpdyProxyTest, ParseChallenge); + FRIEND_TEST_ALL_PREFIXES(HttpAuthHandlerDataReductionProxyTest, + ParseChallenge); - virtual ~HttpAuthHandlerSpdyProxy(); + virtual ~HttpAuthHandlerDataReductionProxy(); virtual bool Init(net::HttpAuthChallengeTokenizer* challenge) OVERRIDE; @@ -68,9 +69,9 @@ class HttpAuthHandlerSpdyProxy : public net::HttpAuthHandler { // Proxy server token, encoded as UTF-8. std::string ps_token_; - DISALLOW_COPY_AND_ASSIGN(HttpAuthHandlerSpdyProxy); + DISALLOW_COPY_AND_ASSIGN(HttpAuthHandlerDataReductionProxy); }; -} // namespace spdyproxy +} // namespace data_reduction_proxy -#endif // CHROME_BROWSER_NET_SPDYPROXY_HTTP_AUTH_HANDLER_SPDYPROXY_H_ +#endif // COMPONENTS_DATA_REDUCTION_PROXY_BROWSER_HTTP_AUTH_HANDLER_DATA_REDUCTION_PROXY_H_ diff --git a/chrome/browser/net/spdyproxy/http_auth_handler_spdyproxy_unittest.cc b/components/data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy_unittest.cc index fdf5bc5..ad21eb0 100644 --- a/chrome/browser/net/spdyproxy/http_auth_handler_spdyproxy_unittest.cc +++ b/components/data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy_unittest.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/net/spdyproxy/http_auth_handler_spdyproxy.h" +#include "components/data_reduction_proxy/browser/http_auth_handler_data_reduction_proxy.h" #include <string> #include <vector> @@ -25,7 +25,7 @@ const char kValidChallenge[] = "SpdyProxy realm=\"SpdyProxy\", " } // namespace -namespace spdyproxy { +namespace data_reduction_proxy { using net::ERR_INVALID_RESPONSE; using net::ERR_UNSUPPORTED_AUTH_SCHEME; @@ -39,7 +39,7 @@ using net::HttpAuthChallengeTokenizer; using net::HttpAuthHandler; using net::HttpRequestInfo; -TEST(HttpAuthHandlerSpdyProxyTest, GenerateAuthToken) { +TEST(HttpAuthHandlerDataReductionProxyTest, GenerateAuthToken) { // Verifies that challenge parsing is expected as described in individual // cases below. static const struct { @@ -88,7 +88,7 @@ TEST(HttpAuthHandlerSpdyProxyTest, GenerateAuthToken) { std::vector<GURL> authorized_origins; authorized_origins.push_back(authorized_origin); authorized_origins.push_back(authorized_origin2); - HttpAuthHandlerSpdyProxy::Factory factory(authorized_origins); + HttpAuthHandlerDataReductionProxy::Factory factory(authorized_origins); scoped_ptr<HttpAuthHandler> spdyproxy; EXPECT_EQ(tests[j].err1, factory.CreateAuthHandlerFromString( tests[j].challenge, targets[i], origin, BoundNetLog(), @@ -109,13 +109,13 @@ TEST(HttpAuthHandlerSpdyProxyTest, GenerateAuthToken) { } } -TEST(HttpAuthHandlerSpdyProxyTest, HandleAnotherChallenge) { +TEST(HttpAuthHandlerDataReductionProxyTest, HandleAnotherChallenge) { // Verifies that any repeat challenge is treated as a failure. GURL origin(kValidOrigin); GURL accepted_origin(kValidOrigin); std::vector<GURL> accepted_origins; accepted_origins.push_back(accepted_origin); - HttpAuthHandlerSpdyProxy::Factory factory(accepted_origins); + HttpAuthHandlerDataReductionProxy::Factory factory(accepted_origins); scoped_ptr<HttpAuthHandler> spdyproxy; EXPECT_EQ(OK, factory.CreateAuthHandlerFromString( kValidChallenge, HttpAuth::AUTH_PROXY, origin, @@ -127,7 +127,7 @@ TEST(HttpAuthHandlerSpdyProxyTest, HandleAnotherChallenge) { spdyproxy->HandleAnotherChallenge(&tok)); } -TEST(HttpAuthHandlerSpdyProxyTest, ParseChallenge) { +TEST(HttpAuthHandlerDataReductionProxyTest, ParseChallenge) { // Verifies that various challenge strings are parsed appropriately as // described below. static const struct { @@ -151,7 +151,7 @@ TEST(HttpAuthHandlerSpdyProxyTest, ParseChallenge) { std::vector<GURL> accepted_origins; accepted_origins.push_back(accepted_origin2); accepted_origins.push_back(accepted_origin); - HttpAuthHandlerSpdyProxy::Factory factory(accepted_origins); + HttpAuthHandlerDataReductionProxy::Factory factory(accepted_origins); for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) { std::string challenge = tests[i].challenge; scoped_ptr<HttpAuthHandler> spdyproxy; @@ -160,12 +160,12 @@ TEST(HttpAuthHandlerSpdyProxyTest, ParseChallenge) { EXPECT_EQ(tests[i].expected_rv, rv); if (rv == OK) { EXPECT_EQ(tests[i].expected_realm, spdyproxy->realm()); - HttpAuthHandlerSpdyProxy* as_spdyproxy = - static_cast<HttpAuthHandlerSpdyProxy*>(spdyproxy.get()); + HttpAuthHandlerDataReductionProxy* as_spdyproxy = + static_cast<HttpAuthHandlerDataReductionProxy*>(spdyproxy.get()); EXPECT_EQ(tests[i].expected_ps, as_spdyproxy->ps_token_); } } } -} // namespace spdyproxy +} // namespace data_reduction_proxy diff --git a/components/data_reduction_proxy/common/data_reduction_proxy_pref_names.cc b/components/data_reduction_proxy/common/data_reduction_proxy_pref_names.cc new file mode 100644 index 0000000..064caa6 --- /dev/null +++ b/components/data_reduction_proxy/common/data_reduction_proxy_pref_names.cc @@ -0,0 +1,89 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h" + +namespace data_reduction_proxy { +namespace prefs { + +// A List pref that contains daily totals of the size of all HTTPS +// content received when the data reduction proxy was enabled. +const char kDailyContentLengthHttpsWithDataReductionProxyEnabled[] = + "data_reduction.daily_received_length_https_with_" + "data_reduction_proxy_enabled"; + +// A List pref that contains daily totals of the size of all HTTP/HTTPS +// content received when a bypass of more than 30 minutes is in effect. +const char kDailyContentLengthLongBypassWithDataReductionProxyEnabled[] = + "data_reduction.daily_received_length_long_bypass_with_" + "data_reduction_proxy_enabled"; + +// A List pref that contains daily totals of the size of all HTTP/HTTPS +// content received when a bypass of less than 30 minutes is in effect. +const char kDailyContentLengthShortBypassWithDataReductionProxyEnabled[] = + "data_reduction.daily_received_length_short_bypass_with_" + "data_reduction_proxy_enabled"; + +// TODO(bengr): what is this? +const char kDailyContentLengthUnknownWithDataReductionProxyEnabled[] = + "data_reduction.daily_received_length_unknown_with_" + "data_reduction_proxy_enabled"; + +// A List pref that contains daily totals of the size of all HTTP/HTTPS +// content received via the data reduction proxy. +const char kDailyContentLengthViaDataReductionProxy[] = + "data_reduction.daily_received_length_via_data_reduction_proxy"; + +// A List pref that contains daily totals of the size of all HTTP/HTTPS +// content received while the data reduction proxy is enabled. +const char kDailyContentLengthWithDataReductionProxyEnabled[] = + "data_reduction.daily_received_length_with_data_reduction_proxy_enabled"; + +// An int64 pref that contains an internal representation of midnight on the +// date of the last update to |kDailyHttp{Original,Received}ContentLength|. +const char kDailyHttpContentLengthLastUpdateDate[] = + "data_reduction.last_update_date"; + +// A List pref that contains daily totals of the original size of all HTTP/HTTPS +// content received from the network. +const char kDailyHttpOriginalContentLength[] = + "data_reduction.daily_original_length"; + +// A List pref that contains daily totals of the size of all HTTP/HTTPS content +// received from the network. +const char kDailyHttpReceivedContentLength[] = + "data_reduction.daily_received_length"; + +// A List pref that contains daily totals of the original size of all HTTP/HTTPS +// content received via the data reduction proxy. +const char kDailyOriginalContentLengthViaDataReductionProxy[] = + "data_reduction.daily_original_length_via_data_reduction_proxy"; + +// A List pref that contains daily totals of the original size of all HTTP/HTTPS +// content received while the data reduction proxy is enabled. +const char kDailyOriginalContentLengthWithDataReductionProxyEnabled[] = + "data_reduction.daily_original_length_with_data_reduction_proxy_enabled"; + +// String that specifies the origin allowed to use data reduction proxy +// authentication, if any. +const char kDataReductionProxy[] = "auth.spdyproxy.origin"; + +// A boolean specifying whether the data reduction proxy is enabled. +const char kDataReductionProxyEnabled[] = "spdy_proxy.enabled"; + +// A boolean specifying whether the data reduction proxy was ever enabled +// before. +const char kDataReductionProxyWasEnabledBefore[] = + "spdy_proxy.was_enabled_before"; + +// An int64 pref that contains the total size of all HTTP content received from +// the network. +const char kHttpReceivedContentLength[] = "http_received_content_length"; + +// An int64 pref that contains the total original size of all HTTP content +// received over the network. +const char kHttpOriginalContentLength[] = "http_original_content_length"; + +} // namespace prefs +} // namespace data_reduction_proxy diff --git a/components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h b/components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h new file mode 100644 index 0000000..ed6379c --- /dev/null +++ b/components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h @@ -0,0 +1,34 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_DATA_REDUCTION_PROXY_COMMON_DATA_REDUCTION_PROXY_PREF_NAMES_H_ +#define COMPONENTS_DATA_REDUCTION_PROXY_COMMON_DATA_REDUCTION_PROXY_PREF_NAMES_H_ + +namespace data_reduction_proxy { +namespace prefs { + +// Alphabetical list of preference names specific to the data_reduction_proxy +// component. Keep alphabetized, and document each in the .cc file. + +extern const char kDailyContentLengthHttpsWithDataReductionProxyEnabled[]; +extern const char kDailyContentLengthLongBypassWithDataReductionProxyEnabled[]; +extern const char kDailyContentLengthShortBypassWithDataReductionProxyEnabled[]; +extern const char kDailyContentLengthUnknownWithDataReductionProxyEnabled[]; +extern const char kDailyContentLengthViaDataReductionProxy[]; +extern const char kDailyContentLengthWithDataReductionProxyEnabled[]; +extern const char kDailyHttpContentLengthLastUpdateDate[]; +extern const char kDailyHttpOriginalContentLength[]; +extern const char kDailyHttpReceivedContentLength[]; +extern const char kDailyOriginalContentLengthViaDataReductionProxy[]; +extern const char kDailyOriginalContentLengthWithDataReductionProxyEnabled[]; +extern const char kDataReductionProxy[]; +extern const char kDataReductionProxyEnabled[]; +extern const char kDataReductionProxyWasEnabledBefore[]; +extern const char kHttpOriginalContentLength[]; +extern const char kHttpReceivedContentLength[]; + +} // namespace prefs +} // namespace data_reduction_proxy + +#endif // COMPONENTS_DATA_REDUCTION_PROXY_COMMON_DATA_REDUCTION_PROXY_PREF_NAMES_H_ diff --git a/components/data_reduction_proxy/common/data_reduction_proxy_switches.cc b/components/data_reduction_proxy/common/data_reduction_proxy_switches.cc new file mode 100644 index 0000000..c7034f4 --- /dev/null +++ b/components/data_reduction_proxy/common/data_reduction_proxy_switches.cc @@ -0,0 +1,30 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/data_reduction_proxy/common/data_reduction_proxy_switches.h" + +namespace data_reduction_proxy { +namespace switches { + +// The origin of the data reduction proxy. +const char kDataReductionProxy[] = "spdy-proxy-auth-origin"; + +// The origin of the data reduction proxy dev. +const char kDataReductionProxyDev[] = "spdy-proxy-dev-auth-origin"; + +// The origin of the data reduction proxy fallback. +const char kDataReductionProxyFallback[] = "spdy-proxy-auth-fallback"; + +// A test key for data reduction proxy authentication. +const char kDataReductionProxyKey[] = "spdy-proxy-auth-value"; + +// Sets a canary URL to test before committing to using the data reduction +// proxy. Note this canary does not go through the data reduction proxy. +const char kDataReductionProxyProbeURL[] = "data-reduction-proxy-probe-url"; + +// Enable the data reduction proxy. +const char kEnableDataReductionProxy[] = "enable-spdy-proxy-auth"; + +} // namespace switches +} // namespace data_reduction_proxy diff --git a/components/data_reduction_proxy/common/data_reduction_proxy_switches.h b/components/data_reduction_proxy/common/data_reduction_proxy_switches.h new file mode 100644 index 0000000..ed09a3c --- /dev/null +++ b/components/data_reduction_proxy/common/data_reduction_proxy_switches.h @@ -0,0 +1,24 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_DATA_REDUCTION_PROXY_COMMON_DATA_REDUCTION_PROXY_SWITCHES_H_ +#define COMPONENTS_DATA_REDUCTION_PROXY_COMMON_DATA_REDUCTION_PROXY_SWITCHES_H_ + +namespace data_reduction_proxy { +namespace switches { + +// All switches in alphabetical order. The switches should be documented +// alongside the definition of their values in the .cc file. + +extern const char kDataReductionProxy[]; +extern const char kDataReductionProxyDev[]; +extern const char kDataReductionProxyFallback[]; +extern const char kDataReductionProxyKey[]; +extern const char kDataReductionProxyProbeURL[]; +extern const char kEnableDataReductionProxy[]; + +} // namespace switches +} // namespace data_reduction_proxy + +#endif // COMPONENTS_DATA_REDUCTION_PROXY_COMMON_DATA_REDUCTION_PROXY_SWITCHES_H_ diff --git a/net/http/http_network_layer_unittest.cc b/net/http/http_network_layer_unittest.cc index 7c3fcb6..06471b4 100644 --- a/net/http/http_network_layer_unittest.cc +++ b/net/http/http_network_layer_unittest.cc @@ -50,7 +50,7 @@ class HttpNetworkLayerTest : public PlatformTest { } #if defined(SPDY_PROXY_AUTH_ORIGIN) - std::string GetChromeProxy() { + std::string GetDataReductionProxy() { return HostPortPair::FromURL(GURL(SPDY_PROXY_AUTH_ORIGIN)).ToString(); } #endif @@ -355,21 +355,21 @@ TEST_F(HttpNetworkLayerTest, GET) { #if defined(SPDY_PROXY_AUTH_ORIGIN) TEST_F(HttpNetworkLayerTest, ServerTwoProxyBypassPac) { - std::string bad_proxy = GetChromeProxy(); + std::string bad_proxy = GetDataReductionProxy(); ConfigureTestDependencies(ProxyService::CreateFixedFromPacResult( "PROXY " + bad_proxy + "; PROXY good:8080")); TestProxyFallback(bad_proxy); } TEST_F(HttpNetworkLayerTest, ServerTwoProxyBypassFixed) { - std::string bad_proxy = GetChromeProxy(); + std::string bad_proxy = GetDataReductionProxy(); ConfigureTestDependencies( ProxyService::CreateFixed(bad_proxy +", good:8080")); TestProxyFallback(bad_proxy); } TEST_F(HttpNetworkLayerTest, BypassAndRetryIdempotentMethods) { - std::string bad_proxy = GetChromeProxy(); + std::string bad_proxy = GetDataReductionProxy(); const struct { std::string method; std::string content; @@ -430,14 +430,14 @@ TEST_F(HttpNetworkLayerTest, BypassAndRetryIdempotentMethods) { } TEST_F(HttpNetworkLayerTest, ServerOneProxyWithDirectBypassPac) { - std::string bad_proxy = GetChromeProxy(); + std::string bad_proxy = GetDataReductionProxy(); ConfigureTestDependencies(ProxyService::CreateFixedFromPacResult( "PROXY " + bad_proxy + "; DIRECT")); TestProxyFallbackToDirect(bad_proxy); } TEST_F(HttpNetworkLayerTest, ServerOneProxyWithDirectBypassFixed) { - std::string bad_proxy = GetChromeProxy(); + std::string bad_proxy = GetDataReductionProxy(); ConfigureTestDependencies( ProxyService::CreateFixed(bad_proxy + ", direct://")); TestProxyFallbackToDirect(bad_proxy); @@ -445,7 +445,7 @@ TEST_F(HttpNetworkLayerTest, ServerOneProxyWithDirectBypassFixed) { #if defined(DATA_REDUCTION_FALLBACK_HOST) TEST_F(HttpNetworkLayerTest, ServerTwoProxyDoubleBypassPac) { - std::string bad_proxy = GetChromeProxy(); + std::string bad_proxy = GetDataReductionProxy(); std::string bad_proxy2 = HostPortPair::FromURL(GURL(DATA_REDUCTION_FALLBACK_HOST)).ToString(); ConfigureTestDependencies(ProxyService::CreateFixedFromPacResult( @@ -454,7 +454,7 @@ TEST_F(HttpNetworkLayerTest, ServerTwoProxyDoubleBypassPac) { } TEST_F(HttpNetworkLayerTest, ServerTwoProxyDoubleBypassFixed) { - std::string bad_proxy = GetChromeProxy(); + std::string bad_proxy = GetDataReductionProxy(); std::string bad_proxy2 = HostPortPair::FromURL(GURL(DATA_REDUCTION_FALLBACK_HOST)).ToString(); ConfigureTestDependencies(ProxyService::CreateFixed( @@ -464,14 +464,14 @@ TEST_F(HttpNetworkLayerTest, ServerTwoProxyDoubleBypassFixed) { #endif TEST_F(HttpNetworkLayerTest, ServerOneProxyNoDirectBypassPac) { - std::string bad_proxy = GetChromeProxy(); + std::string bad_proxy = GetDataReductionProxy(); ConfigureTestDependencies(ProxyService::CreateFixedFromPacResult( "PROXY " + bad_proxy)); TestProxyFallbackFail(1u, bad_proxy, ""); } TEST_F(HttpNetworkLayerTest, ServerOneProxyNoDirectBypassFixed) { - std::string bad_proxy = GetChromeProxy(); + std::string bad_proxy = GetDataReductionProxy(); ConfigureTestDependencies(ProxyService::CreateFixed(bad_proxy)); TestProxyFallbackFail(1u, bad_proxy, ""); } @@ -615,7 +615,7 @@ TEST_F(HttpNetworkLayerTest, ProxyBypassIgnoredOnDirectConnectionPac) { TEST_F(HttpNetworkLayerTest, ServerFallbackWithProxyTimedBypass) { // Verify that a Chrome-Proxy: bypass=<seconds> header induces proxy // fallback to a second proxy, if configured. - std::string bad_proxy = GetChromeProxy(); + std::string bad_proxy = GetDataReductionProxy(); ConfigureTestDependencies(ProxyService::CreateFixedFromPacResult( "PROXY " + bad_proxy + "; PROXY good:8080")); @@ -637,7 +637,7 @@ TEST_F(HttpNetworkLayerTest, ServerFallbackWithProxyTimedBypass) { TEST_F(HttpNetworkLayerTest, ServerFallbackWithWrongViaHeader) { // Verify that a Via header that lacks the Chrome-Proxy induces proxy fallback // to a second proxy, if configured. - std::string chrome_proxy = GetChromeProxy(); + std::string chrome_proxy = GetDataReductionProxy(); ConfigureTestDependencies(ProxyService::CreateFixedFromPacResult( "PROXY " + chrome_proxy + "; PROXY good:8080")); @@ -656,7 +656,7 @@ TEST_F(HttpNetworkLayerTest, ServerFallbackWithWrongViaHeader) { TEST_F(HttpNetworkLayerTest, ServerFallbackWithNoViaHeader) { // Verify that the lack of a Via header induces proxy fallback to a second // proxy, if configured. - std::string chrome_proxy = GetChromeProxy(); + std::string chrome_proxy = GetDataReductionProxy(); ConfigureTestDependencies(ProxyService::CreateFixedFromPacResult( "PROXY " + chrome_proxy + "; PROXY good:8080")); @@ -672,9 +672,9 @@ TEST_F(HttpNetworkLayerTest, ServerFallbackWithNoViaHeader) { } TEST_F(HttpNetworkLayerTest, NoServerFallbackWith304Response) { - // Verify that Chrome will not be induced to bypass the Chrome proxy when - // the Chrome Proxy via header is absent on a 304. - std::string chrome_proxy = GetChromeProxy(); + // Verify that Chrome will not be induced to bypass the data reduction proxy + // when the data reduction proxy via header is absent on a 304. + std::string chrome_proxy = GetDataReductionProxy(); ConfigureTestDependencies(ProxyService::CreateFixedFromPacResult( "PROXY " + chrome_proxy + "; PROXY good:8080")); @@ -690,9 +690,10 @@ TEST_F(HttpNetworkLayerTest, NoServerFallbackWith304Response) { } TEST_F(HttpNetworkLayerTest, NoServerFallbackWithChainedViaHeader) { - // Verify that Chrome will not be induced to bypass the Chrome proxy when - // the Chrome Proxy via header is present, even if that header is chained. - std::string chrome_proxy = GetChromeProxy(); + // Verify that Chrome will not be induced to bypass the data reduction proxy + // when the data reduction proxy via header is present, even if that header + // is chained. + std::string chrome_proxy = GetDataReductionProxy(); ConfigureTestDependencies(ProxyService::CreateFixedFromPacResult( "PROXY " + chrome_proxy + "; PROXY good:8080")); @@ -710,10 +711,10 @@ TEST_F(HttpNetworkLayerTest, NoServerFallbackWithChainedViaHeader) { } TEST_F(HttpNetworkLayerTest, NoServerFallbackWithDeprecatedViaHeader) { - // Verify that Chrome will not be induced to bypass the Chrome proxy when - // the deprecated Chrome Proxy via header is present, even if that header is - // chained. - std::string chrome_proxy = GetChromeProxy(); + // Verify that Chrome will not be induced to bypass the data reduction proxy + // when the deprecated data reduction proxy via header is present, even if + // that header is chained. + std::string chrome_proxy = GetDataReductionProxy(); ConfigureTestDependencies(ProxyService::CreateFixedFromPacResult( "PROXY " + chrome_proxy + "; PROXY good:8080")); @@ -735,7 +736,7 @@ TEST_F(HttpNetworkLayerTest, ServerFallbackWithProxyTimedBypassAll) { // Verify that a Chrome-Proxy: block=<seconds> header bypasses a // a configured Chrome-Proxy and fallback and induces proxy fallback to a // third proxy, if configured. - std::string bad_proxy = GetChromeProxy(); + std::string bad_proxy = GetDataReductionProxy(); std::string fallback_proxy = GetChromeFallbackProxy(); ConfigureTestDependencies(ProxyService::CreateFixedFromPacResult( "PROXY " + bad_proxy + "; PROXY " + fallback_proxy + diff --git a/net/http/http_network_transaction.cc b/net/http/http_network_transaction.cc index 9e80573..36deb99 100644 --- a/net/http/http_network_transaction.cc +++ b/net/http/http_network_transaction.cc @@ -995,29 +995,32 @@ int HttpNetworkTransaction::DoReadHeadersComplete(int result) { if (response_.was_fetched_via_proxy) { ProxyService::DataReductionProxyBypassEventType proxy_bypass_event = ProxyService::BYPASS_EVENT_TYPE_MAX; - bool chrome_proxy_used = + bool data_reduction_proxy_used = proxy_info_.proxy_server().isDataReductionProxy(); - bool chrome_fallback_proxy_used = false; + bool data_reduction_fallback_proxy_used = false; #if defined(DATA_REDUCTION_FALLBACK_HOST) - if (!chrome_proxy_used) { - chrome_fallback_proxy_used = + if (!data_reduction_proxy_used) { + data_reduction_fallback_proxy_used = proxy_info_.proxy_server().isDataReductionProxyFallback(); } #endif - if (chrome_proxy_used || chrome_fallback_proxy_used) { - net::HttpResponseHeaders::ChromeProxyInfo chrome_proxy_info; - proxy_bypass_event = response_.headers->GetChromeProxyBypassEventType( - &chrome_proxy_info); + if (data_reduction_proxy_used || data_reduction_fallback_proxy_used) { + net::HttpResponseHeaders::DataReductionProxyInfo + data_reduction_proxy_info; + proxy_bypass_event + = response_.headers->GetDataReductionProxyBypassEventType( + &data_reduction_proxy_info); if (proxy_bypass_event < ProxyService::BYPASS_EVENT_TYPE_MAX) { ProxyService* proxy_service = session_->proxy_service(); proxy_service->RecordDataReductionProxyBypassInfo( - chrome_proxy_used, proxy_info_.proxy_server(), proxy_bypass_event); + data_reduction_proxy_used, proxy_info_.proxy_server(), + proxy_bypass_event); ProxyServer proxy_server; #if defined(DATA_REDUCTION_FALLBACK_HOST) - if (chrome_proxy_used && chrome_proxy_info.bypass_all) { + if (data_reduction_proxy_used && data_reduction_proxy_info.bypass_all) { // TODO(bengr): Rename as DATA_REDUCTION_FALLBACK_ORIGIN. GURL proxy_url(DATA_REDUCTION_FALLBACK_HOST); if (proxy_url.SchemeIsHTTPOrHTTPS()) { @@ -1030,7 +1033,7 @@ int HttpNetworkTransaction::DoReadHeadersComplete(int result) { #endif if (proxy_service->MarkProxiesAsBadUntil( proxy_info_, - chrome_proxy_info.bypass_duration, + data_reduction_proxy_info.bypass_duration, proxy_server, net_log_)) { // Only retry idempotent methods. We don't want to resubmit a POST diff --git a/net/http/http_response_headers.cc b/net/http/http_response_headers.cc index c067e8f..cc4cec4 100644 --- a/net/http/http_response_headers.cc +++ b/net/http/http_response_headers.cc @@ -1391,7 +1391,7 @@ bool HttpResponseHeaders::IsChunkEncoded() const { } #if defined(SPDY_PROXY_AUTH_ORIGIN) -bool HttpResponseHeaders::GetChromeProxyBypassDuration( +bool HttpResponseHeaders::GetDataReductionProxyBypassDuration( const std::string& action_prefix, base::TimeDelta* duration) const { void* iter = NULL; @@ -1417,8 +1417,8 @@ bool HttpResponseHeaders::GetChromeProxyBypassDuration( return false; } -bool HttpResponseHeaders::GetChromeProxyInfo( - ChromeProxyInfo* proxy_info) const { +bool HttpResponseHeaders::GetDataReductionProxyInfo( + DataReductionProxyInfo* proxy_info) const { DCHECK(proxy_info); proxy_info->bypass_all = false; proxy_info->bypass_duration = base::TimeDelta(); @@ -1426,27 +1426,30 @@ bool HttpResponseHeaders::GetChromeProxyInfo( // <duration> is the number of seconds to wait before retrying // the proxy. If the duration is 0, then the default proxy retry delay // (specified in |ProxyList::UpdateRetryInfoOnFallback|) will be used. - // 'bypass' instructs Chrome to bypass the currently connected Chrome proxy, - // whereas 'block' instructs Chrome to bypass all available Chrome proxies. + // 'bypass' instructs Chrome to bypass the currently connected data reduction + // proxy, whereas 'block' instructs Chrome to bypass all available data + // reduction proxies. // 'block' takes precedence over 'bypass', so look for it first. // TODO(bengr): Reduce checks for 'block' and 'bypass' to a single loop. - if (GetChromeProxyBypassDuration("block=", &proxy_info->bypass_duration)) { + if (GetDataReductionProxyBypassDuration( + "block=", &proxy_info->bypass_duration)) { proxy_info->bypass_all = true; return true; } // Next, look for 'bypass'. - if (GetChromeProxyBypassDuration("bypass=", &proxy_info->bypass_duration)) + if (GetDataReductionProxyBypassDuration( + "bypass=", &proxy_info->bypass_duration)) { return true; - + } return false; } -bool HttpResponseHeaders::IsChromeProxyResponse() const { +bool HttpResponseHeaders::IsDataReductionProxyResponse() const { const size_t kVersionSize = 4; - const char kChromeProxyViaValue[] = "Chrome-Compression-Proxy"; - size_t value_len = strlen(kChromeProxyViaValue); + const char kDataReductionProxyViaValue[] = "Chrome-Compression-Proxy"; + size_t value_len = strlen(kDataReductionProxyViaValue); void* iter = NULL; std::string value; @@ -1455,28 +1458,29 @@ bool HttpResponseHeaders::IsChromeProxyResponse() const { // 'Via: 1.1 Chrome-Compression-Proxy' while (EnumerateHeader(&iter, "via", &value)) { if (value.size() >= kVersionSize + value_len && - !value.compare(kVersionSize, value_len, kChromeProxyViaValue)) + !value.compare(kVersionSize, value_len, kDataReductionProxyViaValue)) return true; } // TODO(bengr): Remove deprecated header value. - const char kDeprecatedChromeProxyViaValue[] = "1.1 Chrome Compression Proxy"; + const char kDeprecatedDataReductionProxyViaValue[] = + "1.1 Chrome Compression Proxy"; iter = NULL; while (EnumerateHeader(&iter, "via", &value)) - if (value == kDeprecatedChromeProxyViaValue) + if (value == kDeprecatedDataReductionProxyViaValue) return true; return false; } ProxyService::DataReductionProxyBypassEventType -HttpResponseHeaders::GetChromeProxyBypassEventType( - ChromeProxyInfo* chrome_proxy_info) const { - DCHECK(chrome_proxy_info); - if (GetChromeProxyInfo(chrome_proxy_info)) { +HttpResponseHeaders::GetDataReductionProxyBypassEventType( + DataReductionProxyInfo* data_reduction_proxy_info) const { + DCHECK(data_reduction_proxy_info); + if (GetDataReductionProxyInfo(data_reduction_proxy_info)) { // A chrome-proxy response header is only present in a 502. For proper // reporting, this check must come before the 5xx checks below. - if (chrome_proxy_info->bypass_duration < TimeDelta::FromMinutes(30)) + if (data_reduction_proxy_info->bypass_duration < TimeDelta::FromMinutes(30)) return ProxyService::SHORT_BYPASS; return ProxyService::LONG_BYPASS; } @@ -1486,7 +1490,8 @@ HttpResponseHeaders::GetChromeProxyBypassEventType( // Fall back if a 500, 502 or 503 is returned. return ProxyService::INTERNAL_SERVER_ERROR_BYPASS; } - if (!IsChromeProxyResponse() && (response_code() != HTTP_NOT_MODIFIED)) { + if (!IsDataReductionProxyResponse() && + (response_code() != HTTP_NOT_MODIFIED)) { // A Via header might not be present in a 304. Since the goal of a 304 // response is to minimize information transfer, a sender in general // should not generate representation metadata other than Cache-Control, diff --git a/net/http/http_response_headers.h b/net/http/http_response_headers.h index 62207ed..2bf4514 100644 --- a/net/http/http_response_headers.h +++ b/net/http/http_response_headers.h @@ -269,14 +269,14 @@ class NET_EXPORT HttpResponseHeaders #if defined (SPDY_PROXY_AUTH_ORIGIN) // Contains instructions contained in the Chrome-Proxy header. - struct ChromeProxyInfo { - ChromeProxyInfo() : bypass_all(false) {} + struct DataReductionProxyInfo { + DataReductionProxyInfo() : bypass_all(false) {} - // True if Chrome should bypass all available Chrome proxies. False if only - // the currently connected Chrome proxy should be bypassed. + // True if Chrome should bypass all available data reduction proxies. False + // if only the currently connected data reduction proxy should be bypassed. bool bypass_all; - // Amount of time to bypass the Chrome proxy or proxies. + // Amount of time to bypass the data reduction proxy or proxies. base::TimeDelta bypass_duration; }; @@ -284,18 +284,20 @@ class NET_EXPORT HttpResponseHeaders // delay. Sets |proxy_info->bypass_duration| to the specified delay if greater // than 0, and to 0 otherwise to indicate that the default proxy delay // (as specified in |ProxyList::UpdateRetryInfoOnFallback|) should be used. - // If all available Chrome proxies should by bypassed, |bypass_all| is set to - // true. |proxy_info| must be non-NULL. - bool GetChromeProxyInfo(ChromeProxyInfo* proxy_info) const; - - // Returns true if response headers contain the Chrome proxy Via header value. - bool IsChromeProxyResponse() const; + // If all available data reduction proxies should by bypassed, |bypass_all| is + // set to true. |proxy_info| must be non-NULL. + bool GetDataReductionProxyInfo(DataReductionProxyInfo* proxy_info) const; // Returns the reason why the Chrome proxy should be bypassed or not, and // populates |proxy_info| with information on how long to bypass if // applicable. ProxyService::DataReductionProxyBypassEventType - GetChromeProxyBypassEventType(ChromeProxyInfo* proxy_info) const; + GetDataReductionProxyBypassEventType( + DataReductionProxyInfo* proxy_info) const; + + // Returns true if response headers contain the data reduction proxy Via + // header value. + bool IsDataReductionProxyResponse() const; #endif // Creates a Value for use with the NetLog containing the response headers. @@ -399,8 +401,8 @@ class NET_EXPORT HttpResponseHeaders #if defined(SPDY_PROXY_AUTH_ORIGIN) // Searches for the specified Chrome-Proxy action, and if present interprets // its value as a duration in seconds. - bool GetChromeProxyBypassDuration(const std::string& action_prefix, - base::TimeDelta* duration) const; + bool GetDataReductionProxyBypassDuration(const std::string& action_prefix, + base::TimeDelta* duration) const; #endif // We keep a list of ParsedHeader objects. These tell us where to locate the diff --git a/net/http/http_response_headers_unittest.cc b/net/http/http_response_headers_unittest.cc index f73e176..361b5ee 100644 --- a/net/http/http_response_headers_unittest.cc +++ b/net/http/http_response_headers_unittest.cc @@ -2093,17 +2093,17 @@ TEST(HttpResponseHeadersTest, GetProxyBypassInfo) { scoped_refptr<net::HttpResponseHeaders> parsed( new net::HttpResponseHeaders(headers)); - net::HttpResponseHeaders::ChromeProxyInfo chrome_proxy_info; + net::HttpResponseHeaders::DataReductionProxyInfo data_reduction_proxy_info; EXPECT_EQ(tests[i].expected_result, - parsed->GetChromeProxyInfo(&chrome_proxy_info)); + parsed->GetDataReductionProxyInfo(&data_reduction_proxy_info)); EXPECT_EQ(tests[i].expected_retry_delay, - chrome_proxy_info.bypass_duration.InSeconds()); + data_reduction_proxy_info.bypass_duration.InSeconds()); EXPECT_EQ(tests[i].expected_bypass_all, - chrome_proxy_info.bypass_all); + data_reduction_proxy_info.bypass_all); } } -TEST(HttpResponseHeadersTest, IsChromeProxyResponse) { +TEST(HttpResponseHeadersTest, IsDataReductionProxyResponse) { const struct { const char* headers; bool expected_result; @@ -2173,11 +2173,11 @@ TEST(HttpResponseHeadersTest, IsChromeProxyResponse) { scoped_refptr<net::HttpResponseHeaders> parsed( new net::HttpResponseHeaders(headers)); - EXPECT_EQ(tests[i].expected_result, parsed->IsChromeProxyResponse()); + EXPECT_EQ(tests[i].expected_result, parsed->IsDataReductionProxyResponse()); } } -TEST(HttpResponseHeadersTest, GetChromeProxyBypassEventType) { +TEST(HttpResponseHeadersTest, GetDataReductionProxyBypassEventType) { const struct { const char* headers; net::ProxyService::DataReductionProxyBypassEventType expected_result; @@ -2244,9 +2244,9 @@ TEST(HttpResponseHeadersTest, GetChromeProxyBypassEventType) { HeadersToRaw(&headers); scoped_refptr<net::HttpResponseHeaders> parsed( new net::HttpResponseHeaders(headers)); - net::HttpResponseHeaders::ChromeProxyInfo chrome_proxy_info; + net::HttpResponseHeaders::DataReductionProxyInfo chrome_proxy_info; EXPECT_EQ(tests[i].expected_result, - parsed->GetChromeProxyBypassEventType(&chrome_proxy_info)); + parsed->GetDataReductionProxyBypassEventType(&chrome_proxy_info)); } } #endif // defined(SPDY_PROXY_AUTH_ORIGIN) |