diff options
48 files changed, 762 insertions, 777 deletions
diff --git a/android_webview/browser/net/android_stream_reader_url_request_job_unittest.cc b/android_webview/browser/net/android_stream_reader_url_request_job_unittest.cc index a5170da..e66a16e0 100644 --- a/android_webview/browser/net/android_stream_reader_url_request_job_unittest.cc +++ b/android_webview/browser/net/android_stream_reader_url_request_job_unittest.cc @@ -164,9 +164,10 @@ class AndroidStreamReaderURLRequestJobTest : public Test { stream_reader_delegate.Pass(), stream_reader.Pass()); // The Interceptor is owned by the |factory_|. - TestJobInterceptor* interceptor = new TestJobInterceptor; - interceptor->set_main_intercept_job(test_stream_reader_job); - factory_.AddInterceptor(interceptor); + TestJobInterceptor* protocol_handler = new TestJobInterceptor; + protocol_handler->set_main_intercept_job(test_stream_reader_job); + bool set_protocol = factory_.SetProtocolHandler("http", protocol_handler); + DCHECK(set_protocol); } MessageLoop loop_; diff --git a/android_webview/browser/net/aw_url_request_context_getter.cc b/android_webview/browser/net/aw_url_request_context_getter.cc index b488b55..92b10e1 100644 --- a/android_webview/browser/net/aw_url_request_context_getter.cc +++ b/android_webview/browser/net/aw_url_request_context_getter.cc @@ -103,7 +103,6 @@ void AwURLRequestContextGetter::Init() { chrome::kDataScheme, new net::DataProtocolHandler()); DCHECK(set_protocol); job_factory->AddInterceptor(new AwRequestInterceptor()); - url_request_context_->set_job_factory(job_factory.get()); // TODO(mnaganov): Fix URLRequestContextBuilder to use proper threads. net::HttpNetworkSession::Params network_session_params; @@ -118,9 +117,9 @@ void AwURLRequestContextGetter::Init() { main_http_factory_.reset(main_cache); url_request_context_->set_http_transaction_factory(main_cache); - OnNetworkStackInitialized(url_request_context_.get(), - job_factory.get()); - job_factory_ = job_factory.Pass(); + job_factory_ = CreateAndroidJobFactoryAndCookieMonster( + url_request_context_.get(), job_factory.Pass()); + url_request_context_->set_job_factory(job_factory_.get()); } void AwURLRequestContextGetter::PopulateNetworkSessionParams( diff --git a/android_webview/browser/net/init_native_callback.h b/android_webview/browser/net/init_native_callback.h index cf204e9..69855b6 100644 --- a/android_webview/browser/net/init_native_callback.h +++ b/android_webview/browser/net/init_native_callback.h @@ -5,8 +5,11 @@ #ifndef ANDROID_WEBVIEW_BROWSER_NET_INIT_NATIVE_CALLBACK_H_ #define ANDROID_WEBVIEW_BROWSER_NET_INIT_NATIVE_CALLBACK_H_ +#include "base/memory/scoped_ptr.h" + namespace net { class URLRequestContext; +class URLRequestJobFactory; } // namespace net namespace android_webview { @@ -15,8 +18,9 @@ class AwURLRequestJobFactory; // This is called on the IO thread when the network URLRequestContext has been // initialized but not used. Note that the UI thread is blocked during this // call. -void OnNetworkStackInitialized(net::URLRequestContext* context, - AwURLRequestJobFactory* job_factory); +scoped_ptr<net::URLRequestJobFactory> CreateAndroidJobFactoryAndCookieMonster( + net::URLRequestContext* context, + scoped_ptr<AwURLRequestJobFactory> job_factory); } // namespace android_webview diff --git a/android_webview/native/android_protocol_handler.cc b/android_webview/native/android_protocol_handler.cc index a5da6fd..907881b 100644 --- a/android_webview/native/android_protocol_handler.cc +++ b/android_webview/native/android_protocol_handler.cc @@ -20,6 +20,7 @@ #include "net/base/net_errors.h" #include "net/base/net_util.h" #include "net/http/http_util.h" +#include "net/url_request/protocol_intercept_job_factory.h" #include "net/url_request/url_request.h" using android_webview::InputStream; @@ -66,22 +67,18 @@ class AndroidStreamReaderURLRequestJobDelegateImpl }; class AssetFileProtocolInterceptor : - public net::URLRequestJobFactory::Interceptor { + public net::URLRequestJobFactory::ProtocolHandler { public: - AssetFileProtocolInterceptor(); virtual ~AssetFileProtocolInterceptor() OVERRIDE; - virtual net::URLRequestJob* MaybeIntercept( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const OVERRIDE; - virtual net::URLRequestJob* MaybeInterceptRedirect( - const GURL& location, - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const OVERRIDE; - virtual net::URLRequestJob* MaybeInterceptResponse( + static scoped_ptr<net::URLRequestJobFactory> CreateURLRequestJobFactory( + scoped_ptr<net::URLRequestJobFactory> base_job_factory); + virtual net::URLRequestJob* MaybeCreateJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) const OVERRIDE; private: + AssetFileProtocolInterceptor(); + // file:///android_asset/ const std::string asset_prefix_; // file:///android_res/ @@ -196,7 +193,19 @@ AssetFileProtocolInterceptor::AssetFileProtocolInterceptor() AssetFileProtocolInterceptor::~AssetFileProtocolInterceptor() { } -net::URLRequestJob* AssetFileProtocolInterceptor::MaybeIntercept( +// static +scoped_ptr<net::URLRequestJobFactory> +AssetFileProtocolInterceptor::CreateURLRequestJobFactory( + scoped_ptr<net::URLRequestJobFactory> base_job_factory) { + scoped_ptr<net::URLRequestJobFactory> top_job_factory( + new net::ProtocolInterceptJobFactory( + base_job_factory.Pass(), + scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>( + new AssetFileProtocolInterceptor()))); + return top_job_factory.Pass(); +} + +net::URLRequestJob* AssetFileProtocolInterceptor::MaybeCreateJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) const { if (!request->url().SchemeIsFile()) return NULL; @@ -213,19 +222,6 @@ net::URLRequestJob* AssetFileProtocolInterceptor::MaybeIntercept( new AndroidStreamReaderURLRequestJobDelegateImpl())); } -net::URLRequestJob* AssetFileProtocolInterceptor::MaybeInterceptRedirect( - const GURL& location, - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const { - return NULL; -} - -net::URLRequestJob* AssetFileProtocolInterceptor::MaybeInterceptResponse( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const { - return NULL; -} - } // namespace namespace android_webview { @@ -235,18 +231,18 @@ bool RegisterAndroidProtocolHandler(JNIEnv* env) { } // static -void RegisterAndroidProtocolsOnIOThread( - net::URLRequestContext* context, - AwURLRequestJobFactory* job_factory) { +scoped_ptr<net::URLRequestJobFactory> CreateAndroidRequestJobFactory( + scoped_ptr<AwURLRequestJobFactory> job_factory) { // Register content://. Note that even though a scheme is // registered here, it cannot be used by child processes until access to it is // granted via ChildProcessSecurityPolicy::GrantScheme(). This is done in // AwContentBrowserClient. // The job factory takes ownership of the handler. - job_factory->SetProtocolHandler(android_webview::kContentScheme, - new ContentSchemeProtocolHandler()); - // The job factory takes ownership of the interceptor. - job_factory->AddInterceptor(new AssetFileProtocolInterceptor()); + bool set_protocol = job_factory->SetProtocolHandler( + android_webview::kContentScheme, new ContentSchemeProtocolHandler()); + DCHECK(set_protocol); + return AssetFileProtocolInterceptor::CreateURLRequestJobFactory( + job_factory.PassAs<net::URLRequestJobFactory>()); } // Set a context object to be used for resolving resource queries. This can diff --git a/android_webview/native/android_protocol_handler.h b/android_webview/native/android_protocol_handler.h index 0fde454..a26c802 100644 --- a/android_webview/native/android_protocol_handler.h +++ b/android_webview/native/android_protocol_handler.h @@ -6,9 +6,11 @@ #define ANDROID_WEBVIEW_NATIVE_ANDROID_PROTOCOL_HANDLER_H_ #include "base/android/jni_android.h" +#include "base/memory/scoped_ptr.h" namespace net { class URLRequestContext; +class URLRequestJobFactory; } // namespace net namespace android_webview { @@ -24,11 +26,11 @@ class AwURLRequestJobFactory; // (file:///android_asset/ and file:///android_res/), see // http://developer.android.com/reference/android/webkit/ // WebSettings.html#setAllowFileAccess(boolean) -void RegisterAndroidProtocolsOnIOThread( - net::URLRequestContext* context, - AwURLRequestJobFactory* job_factory); +scoped_ptr<net::URLRequestJobFactory> CreateAndroidRequestJobFactory( + scoped_ptr<AwURLRequestJobFactory> job_factory); bool RegisterAndroidProtocolHandler(JNIEnv* env); + } // namespace android_webview #endif // ANDROID_WEBVIEW_NATIVE_ANDROID_PROTOCOL_HANDLER_H_ diff --git a/android_webview/native/cookie_manager.cc b/android_webview/native/cookie_manager.cc index a3986c4..868dcbe 100644 --- a/android_webview/native/cookie_manager.cc +++ b/android_webview/native/cookie_manager.cc @@ -348,9 +348,7 @@ static void SetAcceptFileSchemeCookies(JNIEnv* env, jobject obj, return CookieManager::GetInstance()->SetAcceptFileSchemeCookies(accept); } -void SetCookieMonsterOnNetworkStackInit( - net::URLRequestContext* context, - AwURLRequestJobFactory* job_factory) { +void SetCookieMonsterOnNetworkStackInit(net::URLRequestContext* context) { CookieManager::GetInstance()->SetCookieMonster(context); } diff --git a/android_webview/native/cookie_manager.h b/android_webview/native/cookie_manager.h index 897a051..a953509 100644 --- a/android_webview/native/cookie_manager.h +++ b/android_webview/native/cookie_manager.h @@ -14,11 +14,10 @@ class URLRequestContext; namespace android_webview { class AwURLRequestJobFactory; -void SetCookieMonsterOnNetworkStackInit(net::URLRequestContext* context, - AwURLRequestJobFactory* job_factory); +void SetCookieMonsterOnNetworkStackInit(net::URLRequestContext* context); bool RegisterCookieManager(JNIEnv* env); -} // namespace android_webview; +} // namespace android_webview #endif // ANDROID_WEBVIEW_NATIVE_COOKIE_MANAGER_H_ diff --git a/android_webview/native/net_init_native_callback.cc b/android_webview/native/net_init_native_callback.cc index 3e7ff82..585282f 100644 --- a/android_webview/native/net_init_native_callback.cc +++ b/android_webview/native/net_init_native_callback.cc @@ -4,16 +4,19 @@ #include "android_webview/browser/net/init_native_callback.h" +#include "android_webview/browser/net/aw_url_request_job_factory.h" #include "android_webview/native/android_protocol_handler.h" #include "android_webview/native/cookie_manager.h" +#include "net/url_request/url_request_job_factory.h" namespace android_webview { class AwURLRequestJobFactory; -void OnNetworkStackInitialized(net::URLRequestContext* context, - AwURLRequestJobFactory* job_factory) { - RegisterAndroidProtocolsOnIOThread(context, job_factory); - SetCookieMonsterOnNetworkStackInit(context, job_factory); +scoped_ptr<net::URLRequestJobFactory> CreateAndroidJobFactoryAndCookieMonster( + net::URLRequestContext* context, + scoped_ptr<AwURLRequestJobFactory> job_factory) { + SetCookieMonsterOnNetworkStackInit(context); + return CreateAndroidRequestJobFactory(job_factory.Pass()); } -} +} // namespace android_webview diff --git a/chrome/browser/component_updater/component_updater_interceptor.cc b/chrome/browser/component_updater/component_updater_interceptor.cc deleted file mode 100644 index 41d7eae..0000000 --- a/chrome/browser/component_updater/component_updater_interceptor.cc +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2011 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/component_updater/component_updater_interceptor.h" - -#include "base/file_util.h" -#include "base/threading/thread_restrictions.h" -#include "content/public/browser/browser_thread.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_test_job.h" -#include "testing/gtest/include/gtest/gtest.h" - -using content::BrowserThread; - -ComponentUpdateInterceptor::ComponentUpdateInterceptor() - : hit_count_(0) { - net::URLRequest::Deprecated::RegisterRequestInterceptor(this); -} - -ComponentUpdateInterceptor::~ComponentUpdateInterceptor() { - net::URLRequest::Deprecated::UnregisterRequestInterceptor(this); -} - -net::URLRequestJob* ComponentUpdateInterceptor::MaybeIntercept( - net::URLRequest* request, net::NetworkDelegate* network_delegate) { - EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO)); - if (request->url().scheme() != "http" || - request->url().host() != "localhost") { - return NULL; - } - - // It's ok to do a blocking disk access on this thread; this class - // is just used for tests. - base::ThreadRestrictions::ScopedAllowIO allow_io; - - ResponseMap::iterator it = responses_.find(request->url()); - if (it == responses_.end()) { - return NULL; - } - const Response& response = it->second; - ++hit_count_; - - std::string contents; - EXPECT_TRUE(file_util::ReadFileToString(response.data_path, &contents)); - - return new net::URLRequestTestJob(request, - network_delegate, - response.headers, - contents, - true); -} - -void ComponentUpdateInterceptor::SetResponse(const std::string& url, - const std::string& headers, - const FilePath& path) { - // It's ok to do a blocking disk access on this thread; this class - // is just used for tests. - base::ThreadRestrictions::ScopedAllowIO allow_io; - GURL gurl(url); - EXPECT_EQ("http", gurl.scheme()); - EXPECT_EQ("localhost", gurl.host()); - EXPECT_TRUE(file_util::PathExists(path)); - Response response = { path, headers }; - responses_[gurl] = response; -} diff --git a/chrome/browser/component_updater/component_updater_interceptor.h b/chrome/browser/component_updater/component_updater_interceptor.h deleted file mode 100644 index 67b9199..0000000 --- a/chrome/browser/component_updater/component_updater_interceptor.h +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2011 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_COMPONENT_UPDATER_COMPONENT_UPDATER_INTERCEPTOR_H_ -#define CHROME_BROWSER_COMPONENT_UPDATER_COMPONENT_UPDATER_INTERCEPTOR_H_ - -#include <map> -#include <string> - -#include "base/compiler_specific.h" -#include "base/file_path.h" -#include "googleurl/src/gurl.h" -#include "net/url_request/url_request.h" - -#if !defined(UNIT_TEST) -#error "use this class only in unit tests" -#endif - -// This url request interceptor lets us respond to localhost http request urls -// with the contents of files on disk for use in tests. -class ComponentUpdateInterceptor - : public net::URLRequest::Interceptor, - public base::RefCountedThreadSafe<ComponentUpdateInterceptor> { - public: - ComponentUpdateInterceptor(); - - // When requests for |url| arrive, respond with the contents of |path|. The - // hostname of |url| must be "localhost" to avoid DNS lookups, and the scheme - // must be "http". - void SetResponse(const std::string& url, - const std::string& headers, - const FilePath& path); - - // Returns how many requests have been issued that have a stored reply. - int hit_count() const { return hit_count_; } - - private: - // When computing matches, this ignores the query parameters of the url. - virtual net::URLRequestJob* MaybeIntercept( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) OVERRIDE; - - friend class base::RefCountedThreadSafe<ComponentUpdateInterceptor>; - - virtual ~ComponentUpdateInterceptor(); - - struct Response { - FilePath data_path; - std::string headers; - }; - - typedef std::map<GURL, Response> ResponseMap; - ResponseMap responses_; - int hit_count_; - - DISALLOW_COPY_AND_ASSIGN(ComponentUpdateInterceptor); -}; - -#endif // CHROME_BROWSER_COMPONENT_UPDATER_COMPONENT_UPDATER_INTERCEPTOR_H_ diff --git a/chrome/browser/component_updater/test/component_updater_service_unittest.cc b/chrome/browser/component_updater/test/component_updater_service_unittest.cc index 10a30ec..c886819 100644 --- a/chrome/browser/component_updater/test/component_updater_service_unittest.cc +++ b/chrome/browser/component_updater/test/component_updater_service_unittest.cc @@ -11,13 +11,13 @@ #include "base/message_loop.h" #include "base/path_service.h" #include "base/values.h" -#include "chrome/browser/component_updater/component_updater_interceptor.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_paths.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_browser_thread.h" #include "content/public/test/test_notification_tracker.h" +#include "content/test/net/url_request_prepackaged_interceptor.h" #include "googleurl/src/gurl.h" #include "libxml/globals.h" #include "net/url_request/url_fetcher.h" @@ -120,11 +120,6 @@ const uint8 abag_hash[] = {0x01,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06, 0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06,0x06, 0x06,0x01}; -const char header_ok_reply[] = - "HTTP/1.1 200 OK\0" - "Content-type: text/html\0" - "\0"; - const char expected_crx_url[] = "http://localhost/download/jebgalgnebhfojomionfpkfelancnnkf.crx"; @@ -245,19 +240,17 @@ TEST_F(ComponentUpdaterTest, CheckCrxSleep) { io_thread.StartIOThread(); file_thread.Start(); - scoped_refptr<ComponentUpdateInterceptor> - interceptor(new ComponentUpdateInterceptor()); + content::URLRequestPrepackagedInterceptor interceptor; CrxComponent com; RegisterComponent(&com, kTestComponent_abag, Version("1.1")); - const char expected_update_url[] = + const GURL expected_update_url( "http://localhost/upd?extra=foo&x=id%3D" - "abagagagagagagagagagagagagagagag%26v%3D1.1%26uc"; + "abagagagagagagagagagagagagagagag%26v%3D1.1%26uc"); - interceptor->SetResponse(expected_update_url, - header_ok_reply, - test_file("updatecheck_reply_1.xml")); + interceptor.SetResponse(expected_update_url, + test_file("updatecheck_reply_1.xml")); // We loop twice, but there are no updates so we expect two sleep messages. test_configurator()->SetLoopCount(2); @@ -274,7 +267,7 @@ TEST_F(ComponentUpdaterTest, CheckCrxSleep) { EXPECT_EQ(chrome::NOTIFICATION_COMPONENT_UPDATER_SLEEPING, ev2.type); TestNotificationTracker::Event ev3 = notification_tracker().at(2); EXPECT_EQ(chrome::NOTIFICATION_COMPONENT_UPDATER_SLEEPING, ev2.type); - EXPECT_EQ(2, interceptor->hit_count()); + EXPECT_EQ(2, interceptor.GetHitCount()); EXPECT_EQ(0, static_cast<TestInstaller*>(com.installer)->error()); EXPECT_EQ(0, static_cast<TestInstaller*>(com.installer)->install_count()); @@ -284,9 +277,8 @@ TEST_F(ComponentUpdaterTest, CheckCrxSleep) { // Loop twice again but this case we simulate a server error by returning // an empty file. - interceptor->SetResponse(expected_update_url, - header_ok_reply, - test_file("updatecheck_reply_empty")); + interceptor.SetResponse(expected_update_url, + test_file("updatecheck_reply_empty")); notification_tracker().Reset(); test_configurator()->SetLoopCount(2); @@ -301,7 +293,7 @@ TEST_F(ComponentUpdaterTest, CheckCrxSleep) { EXPECT_EQ(chrome::NOTIFICATION_COMPONENT_UPDATER_SLEEPING, ev2.type); ev3 = notification_tracker().at(2); EXPECT_EQ(chrome::NOTIFICATION_COMPONENT_UPDATER_SLEEPING, ev2.type); - EXPECT_EQ(4, interceptor->hit_count()); + EXPECT_EQ(4, interceptor.GetHitCount()); EXPECT_EQ(0, static_cast<TestInstaller*>(com.installer)->error()); EXPECT_EQ(0, static_cast<TestInstaller*>(com.installer)->install_count()); @@ -326,30 +318,29 @@ TEST_F(ComponentUpdaterTest, InstallCrx) { io_thread.StartIOThread(); file_thread.Start(); - scoped_refptr<ComponentUpdateInterceptor> - interceptor(new ComponentUpdateInterceptor()); + content::URLRequestPrepackagedInterceptor interceptor; CrxComponent com1; RegisterComponent(&com1, kTestComponent_jebg, Version("0.9")); CrxComponent com2; RegisterComponent(&com2, kTestComponent_abag, Version("2.2")); - const char expected_update_url_1[] = + const GURL expected_update_url_1( "http://localhost/upd?extra=foo&x=id%3D" "jebgalgnebhfojomionfpkfelancnnkf%26v%3D0.9%26uc&x=id%3D" - "abagagagagagagagagagagagagagagag%26v%3D2.2%26uc"; + "abagagagagagagagagagagagagagagag%26v%3D2.2%26uc"); - const char expected_update_url_2[] = + const GURL expected_update_url_2( "http://localhost/upd?extra=foo&x=id%3D" "abagagagagagagagagagagagagagagag%26v%3D2.2%26uc&x=id%3D" - "jebgalgnebhfojomionfpkfelancnnkf%26v%3D1.0%26uc"; + "jebgalgnebhfojomionfpkfelancnnkf%26v%3D1.0%26uc"); - interceptor->SetResponse(expected_update_url_1, header_ok_reply, - test_file("updatecheck_reply_1.xml")); - interceptor->SetResponse(expected_update_url_2, header_ok_reply, - test_file("updatecheck_reply_1.xml")); - interceptor->SetResponse(expected_crx_url, header_ok_reply, - test_file("jebgalgnebhfojomionfpkfelancnnkf.crx")); + interceptor.SetResponse(expected_update_url_1, + test_file("updatecheck_reply_1.xml")); + interceptor.SetResponse(expected_update_url_2, + test_file("updatecheck_reply_1.xml")); + interceptor.SetResponse(GURL(expected_crx_url), + test_file("jebgalgnebhfojomionfpkfelancnnkf.crx")); test_configurator()->SetLoopCount(2); @@ -358,7 +349,7 @@ TEST_F(ComponentUpdaterTest, InstallCrx) { EXPECT_EQ(0, static_cast<TestInstaller*>(com1.installer)->error()); EXPECT_EQ(1, static_cast<TestInstaller*>(com1.installer)->install_count()); - EXPECT_EQ(3, interceptor->hit_count()); + EXPECT_EQ(3, interceptor.GetHitCount()); ASSERT_EQ(5ul, notification_tracker().size()); @@ -389,27 +380,25 @@ TEST_F(ComponentUpdaterTest, ProdVersionCheck) { io_thread.StartIOThread(); file_thread.Start(); - scoped_refptr<ComponentUpdateInterceptor> - interceptor(new ComponentUpdateInterceptor()); + content::URLRequestPrepackagedInterceptor interceptor; CrxComponent com; RegisterComponent(&com, kTestComponent_jebg, Version("0.9")); - const char expected_update_url[] = + const GURL expected_update_url( "http://localhost/upd?extra=foo&x=id%3D" - "jebgalgnebhfojomionfpkfelancnnkf%26v%3D0.9%26uc"; + "jebgalgnebhfojomionfpkfelancnnkf%26v%3D0.9%26uc"); - interceptor->SetResponse(expected_update_url, - header_ok_reply, - test_file("updatecheck_reply_2.xml")); - interceptor->SetResponse(expected_crx_url, header_ok_reply, - test_file("jebgalgnebhfojomionfpkfelancnnkf.crx")); + interceptor.SetResponse(expected_update_url, + test_file("updatecheck_reply_2.xml")); + interceptor.SetResponse(GURL(expected_crx_url), + test_file("jebgalgnebhfojomionfpkfelancnnkf.crx")); test_configurator()->SetLoopCount(1); component_updater()->Start(); message_loop.Run(); - EXPECT_EQ(1, interceptor->hit_count()); + EXPECT_EQ(1, interceptor.GetHitCount()); EXPECT_EQ(0, static_cast<TestInstaller*>(com.installer)->error()); EXPECT_EQ(0, static_cast<TestInstaller*>(com.installer)->install_count()); diff --git a/chrome/browser/extensions/api/management/management_browsertest.cc b/chrome/browser/extensions/api/management/management_browsertest.cc index c7a8fa6..e0949d2 100644 --- a/chrome/browser/extensions/api/management/management_browsertest.cc +++ b/chrome/browser/extensions/api/management/management_browsertest.cc @@ -6,7 +6,6 @@ #include "base/bind_helpers.h" #include "base/memory/ref_counted.h" #include "base/stl_util.h" -#include "chrome/browser/extensions/autoupdate_interceptor.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_service.h" @@ -27,6 +26,7 @@ #include "content/public/browser/notification_service.h" #include "content/public/browser/render_view_host.h" #include "content/public/test/browser_test_utils.h" +#include "content/test/net/url_request_prepackaged_interceptor.h" #include "net/url_request/url_fetcher.h" using extensions::Extension; @@ -250,14 +250,14 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { NotificationListener notification_listener; FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. - scoped_refptr<extensions::AutoUpdateInterceptor> interceptor( - new extensions::AutoUpdateInterceptor()); + content::URLRequestPrepackagedInterceptor interceptor; net::URLFetcher::SetEnableInterceptionForTests(true); - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", - basedir.AppendASCII("manifest_v2.xml")); - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", - basedir.AppendASCII("v2.crx")); + interceptor.SetResponseIgnoreQuery( + GURL("http://localhost/autoupdate/manifest"), + basedir.AppendASCII("manifest_v2.xml")); + interceptor.SetResponseIgnoreQuery(GURL("http://localhost/autoupdate/v2.crx"), + basedir.AppendASCII("v2.crx")); // Install version 1 of the extension. ExtensionTestMessageListener listener1("v1 installed", false); @@ -298,9 +298,10 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { // Now try doing an update to version 3, which has been incorrectly // signed. This should fail. - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", - basedir.AppendASCII("manifest_v3.xml")); - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v3.crx", + interceptor.SetResponseIgnoreQuery( + GURL("http://localhost/autoupdate/manifest"), + basedir.AppendASCII("manifest_v3.xml")); + interceptor.SetResponseIgnoreQuery(GURL("http://localhost/autoupdate/v3.crx"), basedir.AppendASCII("v3.crx")); service->updater()->CheckNow(params); @@ -335,13 +336,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, NotificationListener notification_listener; FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. - scoped_refptr<extensions::AutoUpdateInterceptor> interceptor( - new extensions::AutoUpdateInterceptor()); + content::URLRequestPrepackagedInterceptor interceptor; net::URLFetcher::SetEnableInterceptionForTests(true); - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", - basedir.AppendASCII("manifest_v2.xml")); - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", + interceptor.SetResponseIgnoreQuery( + GURL("http://localhost/autoupdate/manifest"), + basedir.AppendASCII("manifest_v2.xml")); + interceptor.SetResponseIgnoreQuery(GURL("http://localhost/autoupdate/v2.crx"), basedir.AppendASCII("v2.crx")); // Install version 1 of the extension. @@ -411,13 +412,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_ExternalUrlUpdate) { FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. - scoped_refptr<extensions::AutoUpdateInterceptor> interceptor( - new extensions::AutoUpdateInterceptor()); + content::URLRequestPrepackagedInterceptor interceptor; net::URLFetcher::SetEnableInterceptionForTests(true); - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", - basedir.AppendASCII("manifest_v2.xml")); - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", + interceptor.SetResponseIgnoreQuery( + GURL("http://localhost/autoupdate/manifest"), + basedir.AppendASCII("manifest_v2.xml")); + interceptor.SetResponseIgnoreQuery(GURL("http://localhost/autoupdate/v2.crx"), basedir.AppendASCII("v2.crx")); const size_t size_before = service->extensions()->size(); @@ -497,13 +498,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalPolicyRefresh) { FilePath basedir = test_data_dir_.AppendASCII("autoupdate"); // Note: This interceptor gets requests on the IO thread. - scoped_refptr<extensions::AutoUpdateInterceptor> interceptor( - new extensions::AutoUpdateInterceptor()); + content::URLRequestPrepackagedInterceptor interceptor; net::URLFetcher::SetEnableInterceptionForTests(true); - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", - basedir.AppendASCII("manifest_v2.xml")); - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", + interceptor.SetResponseIgnoreQuery( + GURL("http://localhost/autoupdate/manifest"), + basedir.AppendASCII("manifest_v2.xml")); + interceptor.SetResponseIgnoreQuery(GURL("http://localhost/autoupdate/v2.crx"), basedir.AppendASCII("v2.crx")); const size_t size_before = service->extensions()->size(); @@ -572,13 +573,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ASSERT_TRUE(service->disabled_extensions()->is_empty()); // Note: This interceptor gets requests on the IO thread. - scoped_refptr<extensions::AutoUpdateInterceptor> interceptor( - new extensions::AutoUpdateInterceptor()); + content::URLRequestPrepackagedInterceptor interceptor; net::URLFetcher::SetEnableInterceptionForTests(true); - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest", - basedir.AppendASCII("manifest_v2.xml")); - interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx", + interceptor.SetResponseIgnoreQuery( + GURL("http://localhost/autoupdate/manifest"), + basedir.AppendASCII("manifest_v2.xml")); + interceptor.SetResponseIgnoreQuery(GURL("http://localhost/autoupdate/v2.crx"), basedir.AppendASCII("v2.crx")); // Check that the policy is initially empty. diff --git a/chrome/browser/extensions/autoupdate_interceptor.cc b/chrome/browser/extensions/autoupdate_interceptor.cc deleted file mode 100644 index febc9cf..0000000 --- a/chrome/browser/extensions/autoupdate_interceptor.cc +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) 2011 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/extensions/autoupdate_interceptor.h" - -#include "base/bind.h" -#include "base/file_util.h" -#include "base/threading/thread_restrictions.h" -#include "content/public/browser/browser_thread.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_test_job.h" -#include "testing/gtest/include/gtest/gtest.h" - -using content::BrowserThread; - -namespace extensions { - -// This is a specialized version of net::URLRequestTestJob that lets us specify -// response data and make sure the response code is 200, which the autoupdate -// code relies on. -class AutoUpdateTestRequestJob : public net::URLRequestTestJob { - public: - AutoUpdateTestRequestJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const std::string& response_data) - : net::URLRequestTestJob(request, - network_delegate, - net::URLRequestTestJob::test_headers(), - response_data, - true) { - } - - virtual int GetResponseCode() const { return 200; } - - private: - ~AutoUpdateTestRequestJob() {} -}; - - -AutoUpdateInterceptor::AutoUpdateInterceptor() { - net::URLRequest::Deprecated::RegisterRequestInterceptor(this); -} - -AutoUpdateInterceptor::~AutoUpdateInterceptor() { - net::URLRequest::Deprecated::UnregisterRequestInterceptor(this); -} - -net::URLRequestJob* AutoUpdateInterceptor::MaybeIntercept( - net::URLRequest* request, net::NetworkDelegate* network_delegate) { - EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO)); - if (request->url().scheme() != "http" || - request->url().host() != "localhost") { - return NULL; - } - - // It's ok to do a blocking disk access on this thread; this class - // is just used for tests. - base::ThreadRestrictions::ScopedAllowIO allow_io; - - // Search for this request's url, ignoring any query parameters. - GURL url = request->url(); - if (url.has_query()) { - GURL::Replacements replacements; - replacements.ClearQuery(); - url = url.ReplaceComponents(replacements); - } - std::map<GURL, FilePath>::iterator i = responses_.find(url); - if (i == responses_.end()) { - return NULL; - } - std::string contents; - EXPECT_TRUE(file_util::ReadFileToString(i->second, &contents)); - - return new AutoUpdateTestRequestJob(request, network_delegate, contents); -} - - -void AutoUpdateInterceptor::SetResponse(const std::string url, - const FilePath& path) { - EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO)); - // It's ok to do a blocking disk access on this thread; this class - // is just used for tests. - base::ThreadRestrictions::ScopedAllowIO allow_io; - GURL gurl(url); - EXPECT_EQ("http", gurl.scheme()); - EXPECT_EQ("localhost", gurl.host()); - EXPECT_TRUE(file_util::PathExists(path)); - responses_[gurl] = path; -} - - -void AutoUpdateInterceptor::SetResponseOnIOThread(const std::string url, - const FilePath& path) { - BrowserThread::PostTask( - BrowserThread::IO, FROM_HERE, - base::Bind(&AutoUpdateInterceptor::SetResponse, this, url, path)); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/autoupdate_interceptor.h b/chrome/browser/extensions/autoupdate_interceptor.h deleted file mode 100644 index cfc06590..0000000 --- a/chrome/browser/extensions/autoupdate_interceptor.h +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2011 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_EXTENSIONS_AUTOUPDATE_INTERCEPTOR_H_ -#define CHROME_BROWSER_EXTENSIONS_AUTOUPDATE_INTERCEPTOR_H_ - -#include <map> -#include <string> - -#include "googleurl/src/gurl.h" -#include "net/url_request/url_request.h" - -namespace extensions { - -// This url request interceptor lets us respond to localhost http request urls -// with the contents of files on disk for use in tests. -class AutoUpdateInterceptor - : public net::URLRequest::Interceptor, - public base::RefCountedThreadSafe<AutoUpdateInterceptor> { - public: - AutoUpdateInterceptor(); - - // When computing matches, this ignores query parameters (since the autoupdate - // fetch code appends a bunch of them to manifest fetches). - virtual net::URLRequestJob* MaybeIntercept( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) OVERRIDE; - - // When requests for |url| arrive, respond with the contents of |path|. The - // hostname of |url| must be "localhost" to avoid DNS lookups, and the scheme - // must be "http" so MaybeIntercept can ignore "chrome" and other schemes. - // Also, the match for |url| will ignore any query parameters. - void SetResponse(const std::string url, const FilePath& path); - - // A helper function to call SetResponse on the I/O thread. - void SetResponseOnIOThread(const std::string url, const FilePath& path); - - private: - friend class base::RefCountedThreadSafe<AutoUpdateInterceptor>; - - virtual ~AutoUpdateInterceptor(); - - std::map<GURL, FilePath> responses_; - - DISALLOW_COPY_AND_ASSIGN(AutoUpdateInterceptor); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_AUTOUPDATE_INTERCEPTOR_H_ diff --git a/chrome/browser/extensions/extension_disabled_ui_browsertest.cc b/chrome/browser/extensions/extension_disabled_ui_browsertest.cc index 1f88dd9..5033c65 100644 --- a/chrome/browser/extensions/extension_disabled_ui_browsertest.cc +++ b/chrome/browser/extensions/extension_disabled_ui_browsertest.cc @@ -5,7 +5,6 @@ #include "base/file_path.h" #include "base/files/scoped_temp_dir.h" #include "chrome/app/chrome_command_ids.h" -#include "chrome/browser/extensions/autoupdate_interceptor.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_prefs.h" #include "chrome/browser/extensions/extension_service.h" @@ -17,6 +16,7 @@ #include "chrome/browser/ui/global_error/global_error_service_factory.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" +#include "content/test/net/url_request_prepackaged_interceptor.h" #include "net/url_request/url_fetcher.h" using extensions::Extension; @@ -189,15 +189,14 @@ IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, InstallIncreasingPermissionExtensionV1(); // Note: This interceptor gets requests on the IO thread. - scoped_refptr<extensions::AutoUpdateInterceptor> interceptor( - new extensions::AutoUpdateInterceptor()); + content::URLRequestPrepackagedInterceptor interceptor; net::URLFetcher::SetEnableInterceptionForTests(true); - interceptor->SetResponseOnIOThread( - "http://localhost/autoupdate/updates.xml", + interceptor.SetResponseIgnoreQuery( + GURL("http://localhost/autoupdate/updates.xml"), test_data_dir_.AppendASCII("permissions_increase") .AppendASCII("updates.xml")); - interceptor->SetResponseOnIOThread( - "http://localhost/autoupdate/v2.crx", + interceptor.SetResponseIgnoreQuery( + GURL("http://localhost/autoupdate/v2.crx"), scoped_temp_dir_.path().AppendASCII("permissions2.crx")); extensions::ExtensionUpdater::CheckParams params; diff --git a/chrome/browser/extensions/user_script_listener_unittest.cc b/chrome/browser/extensions/user_script_listener_unittest.cc index b0fc268..f43e5c0 100644 --- a/chrome/browser/extensions/user_script_listener_unittest.cc +++ b/chrome/browser/extensions/user_script_listener_unittest.cc @@ -17,6 +17,7 @@ #include "content/public/browser/resource_controller.h" #include "content/public/browser/resource_throttle.h" #include "net/url_request/url_request.h" +#include "net/url_request/url_request_filter.h" #include "net/url_request/url_request_test_job.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" @@ -101,17 +102,23 @@ scoped_refptr<Extension> LoadExtension(const std::string& filename, class UserScriptListenerTest : public ExtensionServiceTestBase, - public net::URLRequest::Interceptor { + public net::URLRequestJobFactory::ProtocolHandler { public: UserScriptListenerTest() { - net::URLRequest::Deprecated::RegisterRequestInterceptor(this); + net::URLRequestFilter::GetInstance()->AddHostnameProtocolHandler( + "http", "google.com", this); + net::URLRequestFilter::GetInstance()->AddHostnameProtocolHandler( + "http", "example.com", this); } ~UserScriptListenerTest() { - net::URLRequest::Deprecated::UnregisterRequestInterceptor(this); + net::URLRequestFilter::GetInstance()->RemoveHostnameHandler("http", + "google.com"); + net::URLRequestFilter::GetInstance()->RemoveHostnameHandler("http", + "example.com"); } - virtual void SetUp() { + virtual void SetUp() OVERRIDE { ExtensionServiceTestBase::SetUp(); InitializeEmptyExtensionService(); @@ -121,14 +128,15 @@ class UserScriptListenerTest listener_ = new UserScriptListener(); } - virtual void TearDown() { + virtual void TearDown() OVERRIDE { listener_ = NULL; MessageLoop::current()->RunUntilIdle(); } - // net::URLRequest::Interceptor - virtual net::URLRequestJob* MaybeIntercept( - net::URLRequest* request, net::NetworkDelegate* network_delegate) { + // net::URLRequestJobFactory::ProtocolHandler + virtual net::URLRequestJob* MaybeCreateJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate) const OVERRIDE { return new SimpleTestJob(request, network_delegate); } diff --git a/chrome/browser/net/chrome_network_delegate.cc b/chrome/browser/net/chrome_network_delegate.cc index a352093..c66e515 100644 --- a/chrome/browser/net/chrome_network_delegate.cc +++ b/chrome/browser/net/chrome_network_delegate.cc @@ -24,6 +24,7 @@ #include "chrome/browser/extensions/extension_process_manager.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/google/google_util.h" +#include "chrome/browser/net/connect_interceptor.h" #include "chrome/browser/net/load_time_stats.h" #include "chrome/browser/performance_monitor/performance_monitor.h" #include "chrome/browser/prefs/pref_service.h" @@ -292,6 +293,12 @@ void ChromeNetworkDelegate::set_cookie_settings( cookie_settings_ = cookie_settings; } +void ChromeNetworkDelegate::set_predictor( + chrome_browser_net::Predictor* predictor) { + connect_interceptor_.reset( + new chrome_browser_net::ConnectInterceptor(predictor)); +} + // static void ChromeNetworkDelegate::NeverThrottleRequests() { g_never_throttle_requests_ = true; @@ -394,6 +401,9 @@ int ChromeNetworkDelegate::OnBeforeURLRequest( if (force_safe_search && rv == net::OK && new_url->is_empty()) ForceGoogleSafeSearch(request, new_url); + if (connect_interceptor_) + connect_interceptor_->WitnessURLRequest(request); + return rv; } diff --git a/chrome/browser/net/chrome_network_delegate.h b/chrome/browser/net/chrome_network_delegate.h index 598e51b..90e7a75 100644 --- a/chrome/browser/net/chrome_network_delegate.h +++ b/chrome/browser/net/chrome_network_delegate.h @@ -25,7 +25,9 @@ class Value; } namespace chrome_browser_net { +class ConnectInterceptor; class LoadTimeStats; +class Predictor; } namespace extensions { @@ -72,6 +74,9 @@ class ChromeNetworkDelegate : public net::NetworkDelegate { // the header file. Here we just forward-declare it. void set_cookie_settings(CookieSettings* cookie_settings); + // Causes requested URLs to be fed to |predictor| via ConnectInterceptor. + void set_predictor(chrome_browser_net::Predictor* predictor); + void set_load_time_stats(chrome_browser_net::LoadTimeStats* load_time_stats) { load_time_stats_ = load_time_stats; } @@ -167,6 +172,8 @@ class ChromeNetworkDelegate : public net::NetworkDelegate { scoped_refptr<ExtensionInfoMap> extension_info_map_; + scoped_ptr<chrome_browser_net::ConnectInterceptor> connect_interceptor_; + // Weak, owned by our owner. BooleanPrefMember* enable_referrers_; BooleanPrefMember* enable_do_not_track_; diff --git a/chrome/browser/net/connect_interceptor.cc b/chrome/browser/net/connect_interceptor.cc index c1d6dea..d40bc06 100644 --- a/chrome/browser/net/connect_interceptor.cc +++ b/chrome/browser/net/connect_interceptor.cc @@ -27,11 +27,10 @@ ConnectInterceptor::ConnectInterceptor(Predictor* predictor) ConnectInterceptor::~ConnectInterceptor() { } -net::URLRequestJob* ConnectInterceptor::MaybeIntercept( - net::URLRequest* request, net::NetworkDelegate* network_delegate) const { +void ConnectInterceptor::WitnessURLRequest(net::URLRequest* request) const { GURL request_scheme_host(Predictor::CanonicalizeUrl(request->url())); if (request_scheme_host == GURL::EmptyGURL()) - return NULL; + return; // Learn what URLs are likely to be needed during next startup. predictor_->LearnAboutInitialNavigation(request_scheme_host); @@ -74,7 +73,7 @@ net::URLRequestJob* ConnectInterceptor::MaybeIntercept( // We don't update the RecentlySeen() time because any preconnections // need to be made at the first navigation (i.e., when referer was loaded) // and wouldn't have waited for this current request navigation. - return NULL; + return; } } timed_cache_.SetRecentlySeen(request_scheme_host); @@ -84,19 +83,7 @@ net::URLRequestJob* ConnectInterceptor::MaybeIntercept( // predictions now for subresources or for redirected hosts. if ((request->load_flags() & net::LOAD_SUB_FRAME) || redirected_host) predictor_->PredictFrameSubresources(request_scheme_host); - return NULL; -} - -net::URLRequestJob* ConnectInterceptor::MaybeInterceptResponse( - net::URLRequest* request, net::NetworkDelegate* network_delegate) const { - return NULL; -} - -net::URLRequestJob* ConnectInterceptor::MaybeInterceptRedirect( - const GURL& location, - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const { - return NULL; + return; } ConnectInterceptor::TimedCache::TimedCache(const base::TimeDelta& max_duration) diff --git a/chrome/browser/net/connect_interceptor.h b/chrome/browser/net/connect_interceptor.h index afc27af..3372ad8 100644 --- a/chrome/browser/net/connect_interceptor.h +++ b/chrome/browser/net/connect_interceptor.h @@ -7,8 +7,14 @@ #include "base/containers/mru_cache.h" #include "base/gtest_prod_util.h" +#include "base/memory/scoped_ptr.h" #include "base/time.h" -#include "net/url_request/url_request_job_factory.h" + +class GURL; + +namespace net { +class URLRequest; +} namespace chrome_browser_net { @@ -17,26 +23,15 @@ class Predictor; //------------------------------------------------------------------------------ // An interceptor to monitor URLRequests so that we can do speculative DNS // resolution and/or speculative TCP preconnections. -class ConnectInterceptor : public net::URLRequestJobFactory::Interceptor { +class ConnectInterceptor { public: // Construction includes registration as an URL. explicit ConnectInterceptor(Predictor* predictor); // Destruction includes unregistering. virtual ~ConnectInterceptor(); - protected: - // Overridden from net::URLRequest::Interceptor: // Learn about referrers, and optionally preconnect based on history. - virtual net::URLRequestJob* MaybeIntercept( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const OVERRIDE; - virtual net::URLRequestJob* MaybeInterceptResponse( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const OVERRIDE; - virtual net::URLRequestJob* MaybeInterceptRedirect( - const GURL& location, - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const OVERRIDE; + void WitnessURLRequest(net::URLRequest* request) const; private: // Provide access to local class TimedCache for testing. diff --git a/chrome/browser/net/http_intercept_job_factory.cc b/chrome/browser/net/http_intercept_job_factory.cc deleted file mode 100644 index e3f2e77..0000000 --- a/chrome/browser/net/http_intercept_job_factory.cc +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2011 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/http_intercept_job_factory.h" - -#include "base/stl_util.h" -#include "googleurl/src/gurl.h" -#include "net/base/load_flags.h" -#include "net/url_request/url_request_job_manager.h" - -class GURL; - -namespace net { - -const char* kHttpScheme = "http"; -const char* kHttpsScheme = "https"; - -HttpInterceptJobFactory::HttpInterceptJobFactory( - const URLRequestJobFactory* job_factory, - ProtocolHandler* protocol_handler) - : job_factory_(job_factory), - protocol_handler_(protocol_handler) { -} - -HttpInterceptJobFactory::~HttpInterceptJobFactory() {} - -bool HttpInterceptJobFactory::SetProtocolHandler( - const std::string& scheme, ProtocolHandler* protocol_handler) { - NOTREACHED(); - return false; -} - -void HttpInterceptJobFactory::AddInterceptor(Interceptor* interceptor) { - // Interceptor addition is not allowed. - NOTREACHED(); -} - -URLRequestJob* HttpInterceptJobFactory::MaybeCreateJobWithInterceptor( - URLRequest* request, NetworkDelegate* network_delegate) const { - return job_factory_->MaybeCreateJobWithInterceptor(request, network_delegate); -} - -URLRequestJob* HttpInterceptJobFactory::MaybeCreateJobWithProtocolHandler( - const std::string& scheme, - URLRequest* request, - NetworkDelegate* network_delegate) const { - DCHECK(CalledOnValidThread()); - if (scheme == kHttpScheme || scheme == kHttpsScheme) - return protocol_handler_->MaybeCreateJob(request, network_delegate); - return job_factory_->MaybeCreateJobWithProtocolHandler( - scheme, request, network_delegate); -} - -URLRequestJob* HttpInterceptJobFactory::MaybeInterceptRedirect( - const GURL& location, - URLRequest* request, - NetworkDelegate* network_delegate) const { - return job_factory_->MaybeInterceptRedirect( - location, request, network_delegate); -} - -URLRequestJob* HttpInterceptJobFactory::MaybeInterceptResponse( - URLRequest* request, NetworkDelegate* network_delegate) const { - return job_factory_->MaybeInterceptResponse(request, network_delegate); -} - -bool HttpInterceptJobFactory::IsHandledProtocol( - const std::string& scheme) const { - DCHECK(CalledOnValidThread()); - if (scheme == kHttpScheme || scheme == kHttpsScheme) - return true; - return job_factory_->IsHandledProtocol(scheme); -} - -bool HttpInterceptJobFactory::IsHandledURL(const GURL& url) const { - if (url.scheme() == kHttpScheme || url.scheme() == kHttpsScheme) - return true; - return job_factory_->IsHandledURL(url); -} - -} // namespace net diff --git a/chrome/browser/policy/device_management_service_browsertest.cc b/chrome/browser/policy/device_management_service_browsertest.cc index 4e6a032..69b29f0 100644 --- a/chrome/browser/policy/device_management_service_browsertest.cc +++ b/chrome/browser/policy/device_management_service_browsertest.cc @@ -8,15 +8,19 @@ #include "chrome/browser/policy/cloud_policy_constants.h" #include "chrome/browser/policy/device_management_service.h" #include "chrome/test/base/in_process_browser_test.h" +#include "content/public/browser/browser_thread.h" #include "net/base/upload_bytes_element_reader.h" #include "net/base/upload_data_stream.h" #include "net/test/test_server.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_request.h" +#include "net/url_request/url_request_filter.h" +#include "net/url_request/url_request_job_factory.h" #include "net/url_request/url_request_test_job.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +using content::BrowserThread; using testing::DoAll; using testing::Invoke; using testing::InvokeWithoutArgs; @@ -29,68 +33,89 @@ namespace policy { // Dummy service URL for testing with request interception enabled. const char kServiceUrl[] = "http://example.com/device_management"; -// Interceptor implementation that returns test data back to the service. -class CannedResponseInterceptor : public net::URLRequest::Interceptor { +// During construction and destruction of CannedResponseInterceptor tasks are +// posted to the IO thread to add and remove an interceptor for URLRequest's of +// |service_url|. The interceptor returns test data back to the service. +class CannedResponseInterceptor { public: explicit CannedResponseInterceptor(const GURL& service_url) - : service_url_(service_url) { - net::URLRequest::Deprecated::RegisterRequestInterceptor(this); + : delegate_(new Delegate(service_url)) { + BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, + base::Bind(&Delegate::Register, + base::Unretained(delegate_))); } virtual ~CannedResponseInterceptor() { - net::URLRequest::Deprecated::UnregisterRequestInterceptor(this); + BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, delegate_); } - // net::URLRequest::Interceptor overrides. - virtual net::URLRequestJob* MaybeIntercept( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) OVERRIDE { - em::DeviceManagementRequest dm_request; - const net::UploadDataStream* upload = request->get_upload(); - if (request->url().GetOrigin() == service_url_.GetOrigin() && - request->url().path() == service_url_.path() && - upload != NULL && - upload->element_readers().size() == 1 && - upload->element_readers()[0]->AsBytesReader()) { - std::string response_data; - const net::UploadBytesElementReader* bytes_reader = - upload->element_readers()[0]->AsBytesReader(); - ConstructResponse(bytes_reader->bytes(), - bytes_reader->length(), - &response_data); - return new net::URLRequestTestJob(request, - network_delegate, - net::URLRequestTestJob::test_headers(), - response_data, - true); + private: + class Delegate : public net::URLRequestJobFactory::ProtocolHandler { + public: + explicit Delegate(const GURL& service_url) : service_url_(service_url) {} + ~Delegate() { + net::URLRequestFilter::GetInstance()->RemoveHostnameHandler( + "http", "example.com"); } - return NULL; - } + void Register() { + net::URLRequestFilter::GetInstance()->AddHostnameProtocolHandler( + "http", "example.com", this); + } - private: - void ConstructResponse(const char* request_data, - uint64 request_data_length, - std::string* response_data) { - em::DeviceManagementRequest request; - ASSERT_TRUE(request.ParseFromArray(request_data, request_data_length)); - em::DeviceManagementResponse response; - if (request.has_register_request()) { - response.mutable_register_response()->set_device_management_token( - "fake_token"); - } else if (request.has_unregister_request()) { - response.mutable_unregister_response(); - } else if (request.has_policy_request()) { - response.mutable_policy_response()->add_response(); - } else if (request.has_auto_enrollment_request()) { - response.mutable_auto_enrollment_response(); - } else { - FAIL() << "Failed to parse request."; + // net::URLRequestJobFactory::ProtocolHandler overrides. + virtual net::URLRequestJob* MaybeCreateJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate) const OVERRIDE { + const net::UploadDataStream* upload = request->get_upload(); + if (request->url().GetOrigin() == service_url_.GetOrigin() && + request->url().path() == service_url_.path() && + upload != NULL && + upload->element_readers().size() == 1 && + upload->element_readers()[0]->AsBytesReader()) { + std::string response_data; + const net::UploadBytesElementReader* bytes_reader = + upload->element_readers()[0]->AsBytesReader(); + ConstructResponse(bytes_reader->bytes(), + bytes_reader->length(), + &response_data); + return new net::URLRequestTestJob( + request, + network_delegate, + net::URLRequestTestJob::test_headers(), + response_data, + true); + } + + return NULL; } - ASSERT_TRUE(response.SerializeToString(response_data)); - } - const GURL service_url_; + private: + void ConstructResponse(const char* request_data, + uint64 request_data_length, + std::string* response_data) const { + em::DeviceManagementRequest request; + ASSERT_TRUE(request.ParseFromArray(request_data, request_data_length)); + em::DeviceManagementResponse response; + if (request.has_register_request()) { + response.mutable_register_response()->set_device_management_token( + "fake_token"); + } else if (request.has_unregister_request()) { + response.mutable_unregister_response(); + } else if (request.has_policy_request()) { + response.mutable_policy_response()->add_response(); + } else if (request.has_auto_enrollment_request()) { + response.mutable_auto_enrollment_response(); + } else { + FAIL() << "Failed to parse request."; + } + ASSERT_TRUE(response.SerializeToString(response_data)); + } + + const GURL service_url_; + }; + + Delegate* delegate_; }; class DeviceManagementServiceIntegrationTest diff --git a/chrome/browser/policy/policy_browsertest.cc b/chrome/browser/policy/policy_browsertest.cc index 8632a2d2..abc0207 100644 --- a/chrome/browser/policy/policy_browsertest.cc +++ b/chrome/browser/policy/policy_browsertest.cc @@ -148,8 +148,18 @@ void RedirectHostsToTestData(const char* const urls[], size_t size) { for (size_t i = 0; i < size; ++i) { const GURL url(urls[i]); EXPECT_TRUE(url.is_valid()); - filter->AddHostnameHandler(url.scheme(), url.host(), - URLRequestMockHTTPJob::Factory); + filter->AddUrlHandler(url, URLRequestMockHTTPJob::Factory); + } +} + +// Remove filters for requests to the hosts in |urls|. +void UndoRedirectHostsToTestData(const char* const urls[], size_t size) { + // Map the given hosts to the test data dir. + net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); + for (size_t i = 0; i < size; ++i) { + const GURL url(urls[i]); + EXPECT_TRUE(url.is_valid()); + filter->RemoveUrlHandler(url); } } @@ -162,21 +172,42 @@ net::URLRequestJob* FailedJobFactory( request, network_delegate, net::ERR_CONNECTION_RESET); } -// Filters requests to the |host| such that they fail. Run on IO thread. -void MakeRequestFailOnIO(const std::string& host) { - net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); - filter->AddHostnameHandler("http", host, &FailedJobFactory); - filter->AddHostnameHandler("https", host, &FailedJobFactory); -} +// While |MakeRequestFail| is in scope URLRequests to |host| will fail. +class MakeRequestFail { + public: + // Sets up the filter on IO thread such that requests to |host| fail. + explicit MakeRequestFail(const std::string& host) : host_(host) { + BrowserThread::PostTaskAndReply( + BrowserThread::IO, FROM_HERE, + base::Bind(MakeRequestFailOnIO, host_), + MessageLoop::QuitClosure()); + content::RunMessageLoop(); + } + ~MakeRequestFail() { + BrowserThread::PostTaskAndReply( + BrowserThread::IO, FROM_HERE, + base::Bind(UndoMakeRequestFailOnIO, host_), + MessageLoop::QuitClosure()); + content::RunMessageLoop(); + } -// Sets up the filter on IO thread such that requests to |host| fail. -void MakeRequestFail(const std::string& host) { - BrowserThread::PostTaskAndReply( - BrowserThread::IO, FROM_HERE, - base::Bind(MakeRequestFailOnIO, host), - MessageLoop::QuitClosure()); - content::RunMessageLoop(); -} + private: + // Filters requests to the |host| such that they fail. Run on IO thread. + static void MakeRequestFailOnIO(const std::string& host) { + net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); + filter->AddHostnameHandler("http", host, &FailedJobFactory); + filter->AddHostnameHandler("https", host, &FailedJobFactory); + } + + // Remove filters for requests to the |host|. Run on IO thread. + static void UndoMakeRequestFailOnIO(const std::string& host) { + net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); + filter->RemoveHostnameHandler("http", host); + filter->RemoveHostnameHandler("https", host); + } + + const std::string host_; +}; // Verifies that the given url |spec| can be opened. This assumes that |spec| // points at empty.html in the test data dir. @@ -615,7 +646,7 @@ IN_PROC_BROWSER_TEST_F(PolicyTest, ClearSiteDataOnExit) { } IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) { - MakeRequestFail("search.example"); + MakeRequestFail make_request_fail("search.example"); // Verifies that a default search is made using the provider configured via // policy. Also checks that default search can be completely disabled. @@ -685,7 +716,7 @@ IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) { IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) { // Makes the requests fail since all we want to check is that the redirection // is done properly. - MakeRequestFail("google.com"); + MakeRequestFail make_request_fail("google.com"); // Verifies that requests to Google Search engine with the SafeSearch // enabled set the safe=active&ssui=on parameters at the end of the query. @@ -738,7 +769,7 @@ IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) { } IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) { - MakeRequestFail("search.example"); + MakeRequestFail make_request_fail("search.example"); chrome::search::EnableInstantExtendedAPIForTesting(); @@ -1416,6 +1447,12 @@ IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) { CheckURLIsBlocked(browser(), kURLS[1]); CheckCanOpenURL(browser(), kURLS[2]); CheckCanOpenURL(browser(), kURLS[3]); + + BrowserThread::PostTaskAndReply( + BrowserThread::IO, FROM_HERE, + base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)), + MessageLoop::QuitClosure()); + content::RunMessageLoop(); } // Flaky on Linux. http://crbug.com/155459 diff --git a/chrome/browser/printing/print_dialog_cloud_interative_uitest.cc b/chrome/browser/printing/print_dialog_cloud_interative_uitest.cc index 4f67ada..071c9b8 100644 --- a/chrome/browser/printing/print_dialog_cloud_interative_uitest.cc +++ b/chrome/browser/printing/print_dialog_cloud_interative_uitest.cc @@ -166,15 +166,16 @@ class PrintDialogCloudTest : public InProcessBrowserTest { } }; - virtual void SetUp() { + virtual void SetUp() OVERRIDE { TestController::GetInstance()->set_result(false); InProcessBrowserTest::SetUp(); } - virtual void TearDown() { + virtual void TearDown() OVERRIDE { if (handler_added_) { - net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); - filter->RemoveHostnameHandler(scheme_, host_name_); + BrowserThread::PostTask( + BrowserThread::IO, FROM_HERE, + base::Bind(UnregisterTestHandlers, scheme_, host_name_)); handler_added_ = false; TestController::GetInstance()->set_delegate(NULL); } @@ -187,14 +188,14 @@ class PrintDialogCloudTest : public InProcessBrowserTest { // individual test functions seems to fix that. void AddTestHandlers() { if (!handler_added_) { - net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); GURL cloud_print_service_url = CloudPrintURL(browser()->profile()). GetCloudPrintServiceURL(); scheme_ = cloud_print_service_url.scheme(); host_name_ = cloud_print_service_url.host(); - filter->AddHostnameHandler(scheme_, host_name_, - &PrintDialogCloudTest::Factory); + BrowserThread::PostTask( + BrowserThread::IO, FROM_HERE, + base::Bind(RegisterTestHandlers, scheme_, host_name_)); handler_added_ = true; GURL cloud_print_dialog_url = @@ -218,6 +219,18 @@ class PrintDialogCloudTest : public InProcessBrowserTest { std::string("application/pdf"), false)); } + private: + static void RegisterTestHandlers(const std::string& scheme, + const std::string& host_name) { + net::URLRequestFilter::GetInstance()->AddHostnameHandler( + scheme, host_name, &PrintDialogCloudTest::Factory); + } + static void UnregisterTestHandlers(const std::string& scheme, + const std::string& host_name) { + net::URLRequestFilter::GetInstance()->RemoveHostnameHandler(scheme, + host_name); + } + bool handler_added_; std::string scheme_; std::string host_name_; diff --git a/chrome/browser/profiles/off_the_record_profile_io_data.cc b/chrome/browser/profiles/off_the_record_profile_io_data.cc index dfc9b81..37a3f73 100644 --- a/chrome/browser/profiles/off_the_record_profile_io_data.cc +++ b/chrome/browser/profiles/off_the_record_profile_io_data.cc @@ -16,6 +16,7 @@ #include "chrome/browser/io_thread.h" #include "chrome/browser/net/about_protocol_handler.h" #include "chrome/browser/net/chrome_net_log.h" +#include "chrome/browser/net/chrome_network_delegate.h" #include "chrome/browser/net/chrome_url_request_context.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" diff --git a/chrome/browser/profiles/profile_impl_io_data.cc b/chrome/browser/profiles/profile_impl_io_data.cc index e927363..861e3f6 100644 --- a/chrome/browser/profiles/profile_impl_io_data.cc +++ b/chrome/browser/profiles/profile_impl_io_data.cc @@ -15,6 +15,7 @@ #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h" #include "chrome/browser/io_thread.h" #include "chrome/browser/net/chrome_net_log.h" +#include "chrome/browser/net/chrome_network_delegate.h" #include "chrome/browser/net/clear_on_exit_policy.h" #include "chrome/browser/net/connect_interceptor.h" #include "chrome/browser/net/http_server_properties_manager.h" @@ -313,6 +314,8 @@ void ProfileImplIOData::LazyInitializeInternal( command_line.HasSwitch(switches::kVisitURLs)); bool playback_mode = command_line.HasSwitch(switches::kPlaybackMode); + network_delegate()->set_predictor(predictor_.get()); + // Initialize context members. ApplyProfileParamsToContext(main_context); @@ -419,11 +422,11 @@ void ProfileImplIOData::LazyInitializeInternal( scoped_ptr<net::URLRequestJobFactoryImpl> main_job_factory( new net::URLRequestJobFactoryImpl()); - SetUpJobFactory(main_job_factory.get(), - profile_params->protocol_handler_interceptor.Pass(), - network_delegate(), - main_context->ftp_transaction_factory(), - main_context->ftp_auth_cache()); + SetUpJobFactoryDefaults(main_job_factory.get(), + profile_params->protocol_handler_interceptor.Pass(), + network_delegate(), + main_context->ftp_transaction_factory(), + main_context->ftp_auth_cache()); main_job_factory_ = main_job_factory.Pass(); main_context->set_job_factory(main_job_factory_.get()); @@ -478,11 +481,12 @@ void ProfileImplIOData:: // job_factory::IsHandledProtocol return true, which prevents attempts to // handle the protocol externally. We pass NULL in to // SetUpJobFactory() to get this effect. - SetUpJobFactory(extensions_job_factory.get(), - scoped_ptr<net::URLRequestJobFactoryImpl::Interceptor>(NULL), - NULL, - extensions_context->ftp_transaction_factory(), - extensions_context->ftp_auth_cache()); + SetUpJobFactoryDefaults( + extensions_job_factory.get(), + scoped_ptr<net::URLRequestJobFactoryImpl::Interceptor>(NULL), + NULL, + extensions_context->ftp_transaction_factory(), + extensions_context->ftp_auth_cache()); extensions_job_factory_ = extensions_job_factory.Pass(); extensions_context->set_job_factory(extensions_job_factory_.get()); } @@ -556,16 +560,17 @@ ProfileImplIOData::InitializeAppRequestContext( scoped_ptr<net::HttpTransactionFactory>(app_http_cache)); // Overwrite the job factory that we inherit from the main context so - // that we can later provide our own handles for storage related protocols. + // that we can later provide our own handlers for storage related protocols. // Install all the usual protocol handlers unless we are in a browser plugin // guest process, in which case only web-safe schemes are allowed. scoped_ptr<net::URLRequestJobFactoryImpl> job_factory( new net::URLRequestJobFactoryImpl()); if (!partition_descriptor.in_memory) { - SetUpJobFactory(job_factory.get(), protocol_handler_interceptor.Pass(), - network_delegate(), - context->ftp_transaction_factory(), - context->ftp_auth_cache()); + SetUpJobFactoryDefaults( + job_factory.get(), protocol_handler_interceptor.Pass(), + network_delegate(), + context->ftp_transaction_factory(), + context->ftp_auth_cache()); } context->SetJobFactory(job_factory.PassAs<net::URLRequestJobFactory>()); @@ -656,21 +661,6 @@ chrome_browser_net::LoadTimeStats* ProfileImplIOData::GetLoadTimeStats( return io_thread_globals->load_time_stats.get(); } -void ProfileImplIOData::SetUpJobFactory( - net::URLRequestJobFactoryImpl* job_factory, - scoped_ptr<net::URLRequestJobFactory::Interceptor> - protocol_handler_interceptor, - net::NetworkDelegate* network_delegate, - net::FtpTransactionFactory* ftp_transaction_factory, - net::FtpAuthCache* ftp_auth_cache) const { - SetUpJobFactoryDefaults(job_factory, protocol_handler_interceptor.Pass(), - network_delegate, ftp_transaction_factory, - ftp_auth_cache); - - job_factory->AddInterceptor( - new chrome_browser_net::ConnectInterceptor(predictor_.get())); -} - void ProfileImplIOData::ClearNetworkingHistorySinceOnIOThread( base::Time time, const base::Closure& completion) { diff --git a/chrome/browser/profiles/profile_impl_io_data.h b/chrome/browser/profiles/profile_impl_io_data.h index 04b66b2..0f79bd0 100644 --- a/chrome/browser/profiles/profile_impl_io_data.h +++ b/chrome/browser/profiles/profile_impl_io_data.h @@ -172,13 +172,6 @@ class ProfileImplIOData : public ProfileIOData { virtual chrome_browser_net::LoadTimeStats* GetLoadTimeStats( IOThread::Globals* io_thread_globals) const OVERRIDE; - void SetUpJobFactory(net::URLRequestJobFactoryImpl* job_factory, - scoped_ptr<net::URLRequestJobFactory::Interceptor> - protocol_handler_interceptor, - net::NetworkDelegate* network_delegate, - net::FtpTransactionFactory* ftp_transaction_factory, - net::FtpAuthCache* ftp_auth_cache) const; - // Deletes all network related data since |time|. It deletes transport // security state since |time| and also deletes HttpServerProperties data. // Works asynchronously, however if the |completion| callback is non-null, diff --git a/chrome/browser/profiles/profile_io_data.h b/chrome/browser/profiles/profile_io_data.h index ef91f6a..948e016 100644 --- a/chrome/browser/profiles/profile_io_data.h +++ b/chrome/browser/profiles/profile_io_data.h @@ -24,6 +24,7 @@ #include "net/url_request/url_request_job_factory.h" class ChromeHttpUserAgentSettings; +class ChromeNetworkDelegate; class CookieSettings; class DesktopNotificationService; class ExtensionInfoMap; @@ -269,7 +270,7 @@ class ProfileIOData { void set_server_bound_cert_service( net::ServerBoundCertService* server_bound_cert_service) const; - net::NetworkDelegate* network_delegate() const { + ChromeNetworkDelegate* network_delegate() const { return network_delegate_.get(); } @@ -433,7 +434,7 @@ class ProfileIOData { mutable scoped_ptr<ChromeURLDataManagerBackend> chrome_url_data_manager_backend_; mutable scoped_ptr<net::ServerBoundCertService> server_bound_cert_service_; - mutable scoped_ptr<net::NetworkDelegate> network_delegate_; + mutable scoped_ptr<ChromeNetworkDelegate> network_delegate_; mutable scoped_ptr<net::FraudulentCertificateReporter> fraudulent_certificate_reporter_; mutable scoped_ptr<net::ProxyService> proxy_service_; diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi index 6d11a08..74b2047 100644 --- a/chrome/chrome_browser.gypi +++ b/chrome/chrome_browser.gypi @@ -1116,8 +1116,6 @@ 'browser/net/gaia/gaia_oauth_fetcher.h', 'browser/net/load_timing_observer.cc', 'browser/net/load_timing_observer.h', - 'browser/net/http_intercept_job_factory.cc', - 'browser/net/http_intercept_job_factory.h', 'browser/net/http_pipelining_compatibility_client.cc', 'browser/net/http_pipelining_compatibility_client.h', 'browser/net/http_server_properties_manager.h', diff --git a/chrome/chrome_tests.gypi b/chrome/chrome_tests.gypi index 3a8f941..90626f8 100644 --- a/chrome/chrome_tests.gypi +++ b/chrome/chrome_tests.gypi @@ -1030,8 +1030,6 @@ 'browser/extensions/app_background_page_apitest.cc', 'browser/extensions/app_notification_browsertest.cc', 'browser/extensions/app_process_apitest.cc', - 'browser/extensions/autoupdate_interceptor.cc', - 'browser/extensions/autoupdate_interceptor.h', 'browser/extensions/background_page_apitest.cc', 'browser/extensions/background_scripts_apitest.cc', 'browser/extensions/chrome_app_api_browsertest.cc', diff --git a/chrome/chrome_tests_unit.gypi b/chrome/chrome_tests_unit.gypi index e8521a7..46f8d14 100644 --- a/chrome/chrome_tests_unit.gypi +++ b/chrome/chrome_tests_unit.gypi @@ -613,8 +613,6 @@ 'browser/chromeos/version_loader_unittest.cc', 'browser/chromeos/web_socket_proxy_helper_unittest.cc', 'browser/command_updater_unittest.cc', - 'browser/component_updater/component_updater_interceptor.cc', - 'browser/component_updater/component_updater_interceptor.h', 'browser/component_updater/test/component_installers_unittest.cc', 'browser/component_updater/test/component_updater_service_unittest.cc', 'browser/content_settings/content_settings_default_provider_unittest.cc', diff --git a/content/content_tests.gypi b/content/content_tests.gypi index 6772c61..4ffc731 100644 --- a/content/content_tests.gypi +++ b/content/content_tests.gypi @@ -116,6 +116,8 @@ 'test/net/url_request_failed_job.h', 'test/net/url_request_mock_http_job.cc', 'test/net/url_request_mock_http_job.h', + 'test/net/url_request_prepackaged_interceptor.cc', + 'test/net/url_request_prepackaged_interceptor.h', 'test/net/url_request_slow_download_job.cc', 'test/net/url_request_slow_download_job.h', 'test/net/url_request_slow_http_job.cc', diff --git a/content/test/net/url_request_abort_on_end_job.cc b/content/test/net/url_request_abort_on_end_job.cc index 67d10a4..4d49145 100644 --- a/content/test/net/url_request_abort_on_end_job.cc +++ b/content/test/net/url_request_abort_on_end_job.cc @@ -19,26 +19,33 @@ namespace content { namespace { + const char kPageContent[] = "some data\r\n"; + +net::URLRequestJob* JobFactory( + net::URLRequest* request, + net::NetworkDelegate* network_delegate, + const std::string& scheme) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + return new URLRequestAbortOnEndJob(request, network_delegate); +} + +void AddUrlHandlerOnIOThread() { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); + filter->AddUrlHandler(GURL(URLRequestAbortOnEndJob::k400AbortOnEndUrl), + &JobFactory); } +} // anonymous namespace + const char URLRequestAbortOnEndJob::k400AbortOnEndUrl[] = "http://url.handled.by.abort.on.end/400"; // static void URLRequestAbortOnEndJob::AddUrlHandler() { - net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); - filter->AddUrlHandler(GURL(k400AbortOnEndUrl), - &URLRequestAbortOnEndJob::Factory); -} - -// static -net::URLRequestJob* URLRequestAbortOnEndJob::Factory( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const std::string& scheme) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); - return new URLRequestAbortOnEndJob(request, network_delegate); + BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, + base::Bind(AddUrlHandlerOnIOThread)); } // Private const version. diff --git a/content/test/net/url_request_abort_on_end_job.h b/content/test/net/url_request_abort_on_end_job.h index b3d9375..fd31e07 100644 --- a/content/test/net/url_request_abort_on_end_job.h +++ b/content/test/net/url_request_abort_on_end_job.h @@ -22,6 +22,9 @@ class URLRequestAbortOnEndJob : public net::URLRequestJob { public: static const char k400AbortOnEndUrl[]; + URLRequestAbortOnEndJob(net::URLRequest* request, + net::NetworkDelegate* network_delegate); + // net::URLRequestJob virtual void Start() OVERRIDE; virtual bool GetMimeType(std::string* mime_type) const OVERRIDE; @@ -30,15 +33,9 @@ class URLRequestAbortOnEndJob : public net::URLRequestJob { int buf_size, int* bytes_read) OVERRIDE; - static net::URLRequestJob* Factory(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const std::string& scheme); - static void AddUrlHandler(); private: - URLRequestAbortOnEndJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate); virtual ~URLRequestAbortOnEndJob(); void GetResponseInfoConst(net::HttpResponseInfo* info) const; diff --git a/content/test/net/url_request_prepackaged_interceptor.cc b/content/test/net/url_request_prepackaged_interceptor.cc new file mode 100644 index 0000000..c78e12a --- /dev/null +++ b/content/test/net/url_request_prepackaged_interceptor.cc @@ -0,0 +1,158 @@ +// Copyright (c) 2012 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 "content/test/net/url_request_prepackaged_interceptor.h" + +#include "base/file_util.h" +#include "base/threading/thread_restrictions.h" +#include "content/public/browser/browser_thread.h" +#include "net/url_request/url_request.h" +#include "net/url_request/url_request_file_job.h" +#include "net/url_request/url_request_filter.h" +#include "testing/gtest/include/gtest/gtest.h" + +using content::BrowserThread; + +namespace content { + +namespace { + +class URLRequestPrepackagedJob : public net::URLRequestFileJob { + public: + URLRequestPrepackagedJob(net::URLRequest* request, + net::NetworkDelegate* network_delegate, + const FilePath& file_path) + : net::URLRequestFileJob(request, network_delegate, file_path) {} + + virtual int GetResponseCode() const { return 200; } + + private: + virtual ~URLRequestPrepackagedJob() {} + + DISALLOW_COPY_AND_ASSIGN(URLRequestPrepackagedJob); +}; + +} // namespace + +class URLRequestPrepackagedInterceptor::Delegate + : public net::URLRequestJobFactory::ProtocolHandler { + public: + Delegate() : hit_count_(0) {} + virtual ~Delegate() { + net::URLRequestFilter::GetInstance()->RemoveHostnameHandler("http", + "localhost"); + } + + void Register() { + net::URLRequestFilter::GetInstance()->AddHostnameProtocolHandler( + "http", "localhost", this); + } + + // When requests for |url| arrive, respond with the contents of |path|. The + // hostname of |url| must be "localhost" to avoid DNS lookups, and the scheme + // must be "http". + void SetResponse(const GURL& url, + const FilePath& path, + bool ignore_query) { + CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + // It's ok to do a blocking disk access on this thread; this class + // is just used for tests. + base::ThreadRestrictions::ScopedAllowIO allow_io; + EXPECT_TRUE(file_util::PathExists(path)); + if (ignore_query) { + ignore_query_responses_[url] = path; + } else { + responses_[url] = path; + } + } + + // Returns how many requests have been issued that have a stored reply. + int GetHitCount() const { + base::AutoLock auto_lock(hit_count_lock_); + return hit_count_; + } + + private: + typedef std::map<GURL, FilePath> ResponseMap; + + // When computing matches, this ignores the query parameters of the url. + virtual net::URLRequestJob* MaybeCreateJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate) const OVERRIDE { + CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + if (request->url().scheme() != "http" || + request->url().host() != "localhost") { + return NULL; + } + + ResponseMap::const_iterator it = responses_.find(request->url()); + if (it == responses_.end()) { + // Search for this request's url, ignoring any query parameters. + GURL url = request->url(); + if (url.has_query()) { + GURL::Replacements replacements; + replacements.ClearQuery(); + url = url.ReplaceComponents(replacements); + } + it = ignore_query_responses_.find(url); + if (it == ignore_query_responses_.end()) + return NULL; + } + { + base::AutoLock auto_lock(hit_count_lock_); + ++hit_count_; + } + + return new URLRequestPrepackagedJob(request, + network_delegate, + it->second); + } + + ResponseMap responses_; + ResponseMap ignore_query_responses_; + + mutable base::Lock hit_count_lock_; + mutable int hit_count_; + + DISALLOW_COPY_AND_ASSIGN(Delegate); +}; + + +URLRequestPrepackagedInterceptor::URLRequestPrepackagedInterceptor() + : delegate_(new Delegate) { + BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, + base::Bind(&Delegate::Register, + base::Unretained(delegate_))); +} + +URLRequestPrepackagedInterceptor::~URLRequestPrepackagedInterceptor() { + BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, delegate_); +} + +void URLRequestPrepackagedInterceptor::SetResponse(const GURL& url, + const FilePath& path) { + CHECK_EQ("http", url.scheme()); + CHECK_EQ("localhost", url.host()); + BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, + base::Bind(&Delegate::SetResponse, + base::Unretained(delegate_), url, path, + false)); +} + +void URLRequestPrepackagedInterceptor::SetResponseIgnoreQuery( + const GURL& url, + const FilePath& path) { + CHECK_EQ("http", url.scheme()); + CHECK_EQ("localhost", url.host()); + BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, + base::Bind(&Delegate::SetResponse, + base::Unretained(delegate_), url, path, + true)); +} + +int URLRequestPrepackagedInterceptor::GetHitCount() { + return delegate_->GetHitCount(); +} + +} // namespace content diff --git a/content/test/net/url_request_prepackaged_interceptor.h b/content/test/net/url_request_prepackaged_interceptor.h new file mode 100644 index 0000000..88b2291 --- /dev/null +++ b/content/test/net/url_request_prepackaged_interceptor.h @@ -0,0 +1,47 @@ +// Copyright (c) 2012 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_COMPONENT_UPDATER_COMPONENT_UPDATER_INTERCEPTOR_H_ +#define CHROME_BROWSER_COMPONENT_UPDATER_COMPONENT_UPDATER_INTERCEPTOR_H_ + +#include "base/basictypes.h" + +class FilePath; +class GURL; + +namespace content { + +// Intercepts HTTP requests and gives pre-defined responses to specified URLs. +// The pre-defined responses are loaded from files on disk. The interception +// occurs while the URLRequestPrepackagedInterceptor is alive. +class URLRequestPrepackagedInterceptor { + public: + URLRequestPrepackagedInterceptor(); + virtual ~URLRequestPrepackagedInterceptor(); + + // When requests for |url| arrive, respond with the contents of |path|. The + // hostname of |url| must be "localhost" to avoid DNS lookups, and the scheme + // must be "http". + void SetResponse(const GURL& url, const FilePath& path); + + // Identical to SetResponse except that query parameters are ignored on + // incoming URLs when comparing against |url|. + void SetResponseIgnoreQuery(const GURL& url, const FilePath& path); + + // Returns how many requests have been issued that have a stored reply. + int GetHitCount(); + + private: + class Delegate; + + // After creation, |delegate_| lives on the IO thread, and a task to delete + // it is posted from ~URLRequestPrepackagedInterceptor(). + Delegate* delegate_; + + DISALLOW_COPY_AND_ASSIGN(URLRequestPrepackagedInterceptor); +}; + +} // namespace content + +#endif // CHROME_BROWSER_COMPONENT_UPDATER_COMPONENT_UPDATER_INTERCEPTOR_H_ diff --git a/net/net.gyp b/net/net.gyp index c2e7365..7cb13a6 100644 --- a/net/net.gyp +++ b/net/net.gyp @@ -855,6 +855,8 @@ 'url_request/ftp_protocol_handler.cc', 'url_request/ftp_protocol_handler.h', 'url_request/http_user_agent_settings.h', + 'url_request/protocol_intercept_job_factory.cc', + 'url_request/protocol_intercept_job_factory.h', 'url_request/static_http_user_agent_settings.cc', 'url_request/static_http_user_agent_settings.h', 'url_request/url_fetcher.cc', diff --git a/net/proxy/proxy_script_fetcher_impl_unittest.cc b/net/proxy/proxy_script_fetcher_impl_unittest.cc index a061bea..5f9990f 100644 --- a/net/proxy/proxy_script_fetcher_impl_unittest.cc +++ b/net/proxy/proxy_script_fetcher_impl_unittest.cc @@ -44,30 +44,6 @@ struct FetchResult { string16 text; }; -// CheckNoRevocationFlagSetInterceptor causes a test failure if a request is -// seen that doesn't set a load flag to bypass revocation checking. -class CheckNoRevocationFlagSetInterceptor : - public URLRequestJobFactory::Interceptor { - public: - virtual URLRequestJob* MaybeIntercept( - URLRequest* request, NetworkDelegate* network_delegate) const OVERRIDE { - EXPECT_TRUE(request->load_flags() & LOAD_DISABLE_CERT_REVOCATION_CHECKING); - return NULL; - } - - virtual URLRequestJob* MaybeInterceptRedirect( - const GURL& location, - URLRequest* request, - NetworkDelegate* network_delegate) const OVERRIDE { - return NULL; - } - - virtual URLRequestJob* MaybeInterceptResponse( - URLRequest* request, NetworkDelegate* network_delegate) const OVERRIDE { - return NULL; - } -}; - // A non-mock URL request which can access http:// and file:// urls. class RequestContext : public URLRequestContext { public: @@ -90,10 +66,7 @@ class RequestContext : public URLRequestContext { storage_.set_http_transaction_factory(new HttpCache( network_session, HttpCache::DefaultBackend::InMemory(0))); - scoped_ptr<URLRequestJobFactoryImpl> factory(new URLRequestJobFactoryImpl); - factory->AddInterceptor(new CheckNoRevocationFlagSetInterceptor); - url_request_job_factory_ = factory.Pass(); - set_job_factory(url_request_job_factory_.get()); + set_job_factory(new URLRequestJobFactoryImpl()); } virtual ~RequestContext() { @@ -116,7 +89,9 @@ GURL GetTestFileUrl(const std::string& relpath) { } // Really simple NetworkDelegate so we can allow local file access on ChromeOS -// without introducing layering violations. +// without introducing layering violations. Also causes a test failure if a +// request is seen that doesn't set a load flag to bypass revocation checking. + class BasicNetworkDelegate : public NetworkDelegate { public: BasicNetworkDelegate() {} @@ -126,6 +101,7 @@ class BasicNetworkDelegate : public NetworkDelegate { virtual int OnBeforeURLRequest(URLRequest* request, const CompletionCallback& callback, GURL* new_url) OVERRIDE { + EXPECT_TRUE(request->load_flags() & LOAD_DISABLE_CERT_REVOCATION_CHECKING); return OK; } diff --git a/net/url_request/protocol_intercept_job_factory.cc b/net/url_request/protocol_intercept_job_factory.cc new file mode 100644 index 0000000..1a1a95f --- /dev/null +++ b/net/url_request/protocol_intercept_job_factory.cc @@ -0,0 +1,74 @@ +// Copyright (c) 2011 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 "net/url_request/protocol_intercept_job_factory.h" + +#include "base/stl_util.h" +#include "googleurl/src/gurl.h" +#include "net/base/load_flags.h" +#include "net/url_request/url_request_job_manager.h" + +class GURL; + +namespace net { + +ProtocolInterceptJobFactory::ProtocolInterceptJobFactory( + scoped_ptr<URLRequestJobFactory> job_factory, + scoped_ptr<ProtocolHandler> protocol_handler) + : job_factory_(job_factory.Pass()), + protocol_handler_(protocol_handler.Pass()) { +} + +ProtocolInterceptJobFactory::~ProtocolInterceptJobFactory() {} + +bool ProtocolInterceptJobFactory::SetProtocolHandler( + const std::string& scheme, ProtocolHandler* protocol_handler) { + return job_factory_->SetProtocolHandler(scheme, protocol_handler); +} + +void ProtocolInterceptJobFactory::AddInterceptor(Interceptor* interceptor) { + return job_factory_->AddInterceptor(interceptor); +} + +URLRequestJob* ProtocolInterceptJobFactory::MaybeCreateJobWithInterceptor( + URLRequest* request, NetworkDelegate* network_delegate) const { + return job_factory_->MaybeCreateJobWithInterceptor(request, network_delegate); +} + +URLRequestJob* ProtocolInterceptJobFactory::MaybeCreateJobWithProtocolHandler( + const std::string& scheme, + URLRequest* request, + NetworkDelegate* network_delegate) const { + DCHECK(CalledOnValidThread()); + URLRequestJob* job = protocol_handler_->MaybeCreateJob(request, + network_delegate); + if (job) + return job; + return job_factory_->MaybeCreateJobWithProtocolHandler( + scheme, request, network_delegate); +} + +URLRequestJob* ProtocolInterceptJobFactory::MaybeInterceptRedirect( + const GURL& location, + URLRequest* request, + NetworkDelegate* network_delegate) const { + return job_factory_->MaybeInterceptRedirect( + location, request, network_delegate); +} + +URLRequestJob* ProtocolInterceptJobFactory::MaybeInterceptResponse( + URLRequest* request, NetworkDelegate* network_delegate) const { + return job_factory_->MaybeInterceptResponse(request, network_delegate); +} + +bool ProtocolInterceptJobFactory::IsHandledProtocol( + const std::string& scheme) const { + return job_factory_->IsHandledProtocol(scheme); +} + +bool ProtocolInterceptJobFactory::IsHandledURL(const GURL& url) const { + return job_factory_->IsHandledURL(url); +} + +} // namespace net diff --git a/chrome/browser/net/http_intercept_job_factory.h b/net/url_request/protocol_intercept_job_factory.h index 7e78d3d..13bfc1c 100644 --- a/chrome/browser/net/http_intercept_job_factory.h +++ b/net/url_request/protocol_intercept_job_factory.h @@ -1,12 +1,14 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright (c) 2012 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_HTTP_INTERCEPT_JOB_FACTORY_H_ -#define CHROME_BROWSER_NET_HTTP_INTERCEPT_JOB_FACTORY_H_ +#ifndef NET_URL_REQUEST_PROTOCOL_INTERCEPT_JOB_FACTORY_H_ +#define NET_URL_REQUEST_PROTOCOL_INTERCEPT_JOB_FACTORY_H_ #include "base/basictypes.h" #include "base/compiler_specific.h" +#include "base/memory/scoped_ptr.h" +#include "net/base/net_export.h" #include "net/url_request/url_request_job_factory.h" class GURL; @@ -16,14 +18,15 @@ namespace net { class URLRequest; class URLRequestJob; -// This class acts as a wrapper for URLRequestJobFactory. It handles HTTP and -// HTTPS jobs using |protocol_handler_|, but forwards all other schemes to the -// old job factory to be handled there. -class HttpInterceptJobFactory : public URLRequestJobFactory { +// This class acts as a wrapper for URLRequestJobFactory. |protocol_handler_| is +// given the option of creating a URLRequestJob for each potential URLRequest. +// If |protocol_handler_| does not create a job (i.e. MaybeCreateJob() returns +// NULL) the URLRequest is forwarded to the |job_factory_| to be handled there. +class NET_EXPORT ProtocolInterceptJobFactory : public URLRequestJobFactory { public: - HttpInterceptJobFactory(const URLRequestJobFactory* job_factory, - ProtocolHandler* protocol_handler); - virtual ~HttpInterceptJobFactory(); + ProtocolInterceptJobFactory(scoped_ptr<URLRequestJobFactory> job_factory, + scoped_ptr<ProtocolHandler> protocol_handler); + virtual ~ProtocolInterceptJobFactory(); // URLRequestJobFactory implementation virtual bool SetProtocolHandler(const std::string& scheme, @@ -45,12 +48,12 @@ class HttpInterceptJobFactory : public URLRequestJobFactory { virtual bool IsHandledURL(const GURL& url) const OVERRIDE; private: - const URLRequestJobFactory* job_factory_; - ProtocolHandler* protocol_handler_; + scoped_ptr<URLRequestJobFactory> job_factory_; + scoped_ptr<ProtocolHandler> protocol_handler_; - DISALLOW_COPY_AND_ASSIGN(HttpInterceptJobFactory); + DISALLOW_COPY_AND_ASSIGN(ProtocolInterceptJobFactory); }; } // namespace net -#endif // CHROME_BROWSER_NET_HTTP_INTERCEPT_JOB_FACTORY_H_ +#endif // NET_URL_REQUEST_PROTOCOL_INTERCEPT_JOB_FACTORY_H_ diff --git a/net/url_request/url_request.h b/net/url_request/url_request.h index 4081e75..8be1c94 100644 --- a/net/url_request/url_request.h +++ b/net/url_request/url_request.h @@ -187,9 +187,7 @@ class NET_EXPORT URLRequest : NON_EXPORTED_BASE(public base::NonThreadSafe), class NET_EXPORT Deprecated { private: // TODO(willchan): Kill off these friend declarations. - friend class extensions::AutoUpdateInterceptor; friend class ::ChildProcessSecurityPolicyTest; - friend class ::ComponentUpdateInterceptor; friend class ::TestAutomationProvider; friend class ::URLRequestAutomationJob; friend class TestInterceptor; @@ -198,11 +196,9 @@ class NET_EXPORT URLRequest : NON_EXPORTED_BASE(public base::NonThreadSafe), friend class appcache::AppCacheRequestHandlerTest; friend class appcache::AppCacheURLRequestJobTest; friend class content::ResourceDispatcherHostTest; - friend class extensions::UserScriptListenerTest; friend class fileapi::FileSystemDirURLRequestJobTest; friend class fileapi::FileSystemURLRequestJobTest; friend class fileapi::FileWriterDelegateTest; - friend class policy::CannedResponseInterceptor; friend class webkit_blob::BlobURLRequestJobTest; // Use URLRequestJobFactory::ProtocolHandler instead. diff --git a/net/url_request/url_request_filter.cc b/net/url_request/url_request_filter.cc index 01b6069..81ffa1d 100644 --- a/net/url_request/url_request_filter.cc +++ b/net/url_request/url_request_filter.cc @@ -10,6 +10,18 @@ namespace net { +namespace { + +URLRequestJob* ProtocolHandlerFactory( + URLRequestJobFactory::ProtocolHandler* protocol_handler, + URLRequest* request, + NetworkDelegate* network_delegate, + const std::string& scheme) { + return protocol_handler->MaybeCreateJob(request, network_delegate); +} + +} // namespace + URLRequestFilter* URLRequestFilter::shared_instance_ = NULL; URLRequestFilter::~URLRequestFilter() {} @@ -31,7 +43,23 @@ URLRequestFilter* URLRequestFilter::GetInstance() { void URLRequestFilter::AddHostnameHandler(const std::string& scheme, const std::string& hostname, URLRequest::ProtocolFactory* factory) { - hostname_handler_map_[make_pair(scheme, hostname)] = factory; + AddHostnameCallback(scheme, hostname, base::Bind(factory)); +} + +void URLRequestFilter::AddHostnameProtocolHandler( + const std::string& scheme, + const std::string& hostname, + URLRequestJobFactory::ProtocolHandler* protocol_handler) { + AddHostnameCallback(scheme, hostname, base::Bind(ProtocolHandlerFactory, + protocol_handler)); +} + +void URLRequestFilter::AddHostnameCallback( + const std::string& scheme, + const std::string& hostname, + base::Callback<URLRequest::ProtocolFactory> callback) { + DCHECK_EQ(0u, hostname_handler_map_.count(make_pair(scheme, hostname))); + hostname_handler_map_[make_pair(scheme, hostname)] = callback; // Register with the ProtocolFactory. URLRequest::Deprecated::RegisterProtocolFactory( @@ -68,6 +96,7 @@ bool URLRequestFilter::AddUrlHandler( URLRequest::ProtocolFactory* factory) { if (!url.is_valid()) return false; + DCHECK_EQ(0u, url_handler_map_.count(url.spec())); url_handler_map_[url.spec()] = factory; // Register with the ProtocolFactory. @@ -130,7 +159,7 @@ URLRequestJob* URLRequestFilter::FindRequestHandler( HostnameHandlerMap::iterator i = hostname_handler_map_.find(make_pair(scheme, hostname)); if (i != hostname_handler_map_.end()) - job = i->second(request, network_delegate, scheme); + job = i->second.Run(request, network_delegate, scheme); if (!job) { // Not in the hostname map, check the url map. diff --git a/net/url_request/url_request_filter.h b/net/url_request/url_request_filter.h index c039300..060820e 100644 --- a/net/url_request/url_request_filter.h +++ b/net/url_request/url_request_filter.h @@ -22,9 +22,11 @@ #include <map> #include <string> +#include "base/callback.h" #include "base/hash_tables.h" #include "net/base/net_export.h" #include "net/url_request/url_request.h" +#include "net/url_request/url_request_job_factory.h" class GURL; @@ -35,7 +37,7 @@ class NET_EXPORT URLRequestFilter { public: // scheme,hostname -> ProtocolFactory typedef std::map<std::pair<std::string, std::string>, - URLRequest::ProtocolFactory*> HostnameHandlerMap; + base::Callback<URLRequest::ProtocolFactory> > HostnameHandlerMap; typedef base::hash_map<std::string, URLRequest::ProtocolFactory*> UrlHandlerMap; @@ -49,6 +51,10 @@ class NET_EXPORT URLRequestFilter { void AddHostnameHandler(const std::string& scheme, const std::string& hostname, URLRequest::ProtocolFactory* factory); + void AddHostnameProtocolHandler( + const std::string& scheme, + const std::string& hostname, + URLRequestJobFactory::ProtocolHandler* protocol_handler); void RemoveHostnameHandler(const std::string& scheme, const std::string& hostname); @@ -83,6 +89,11 @@ class NET_EXPORT URLRequestFilter { int hit_count_; private: + void AddHostnameCallback( + const std::string& scheme, + const std::string& hostname, + base::Callback<URLRequest::ProtocolFactory> callback); + // Singleton instance. static URLRequestFilter* shared_instance_; diff --git a/net/url_request/url_request_filter_unittest.cc b/net/url_request/url_request_filter_unittest.cc index 9f11675..53204ba 100644 --- a/net/url_request/url_request_filter_unittest.cc +++ b/net/url_request/url_request_filter_unittest.cc @@ -35,6 +35,19 @@ URLRequestJob* FactoryB(URLRequest* request, return job_b; } +URLRequestTestJob* job_c; + +class TestProtocolHandler : public URLRequestJobFactory::ProtocolHandler { + public: + virtual ~TestProtocolHandler() {} + + virtual URLRequestJob* MaybeCreateJob( + URLRequest* request, NetworkDelegate* network_delegate) const OVERRIDE { + job_c = new URLRequestTestJob(request, network_delegate); + return job_c; + } +}; + TEST(URLRequestFilter, BasicMatching) { TestDelegate delegate; TestURLRequestContext request_context; @@ -67,23 +80,11 @@ TEST(URLRequestFilter, BasicMatching) { &request_2, request_context.network_delegate(), url_2.scheme()) == NULL); EXPECT_EQ(1, URLRequestFilter::GetInstance()->hit_count()); - // Check we can overwrite URL handler. - EXPECT_TRUE(URLRequestFilter::GetInstance()->AddUrlHandler(url_1, - &FactoryB)); - { - scoped_refptr<URLRequestJob> found = URLRequestFilter::Factory( - &request_1, request_context.network_delegate(), url_1.scheme()); - EXPECT_EQ(job_b, found); - EXPECT_TRUE(job_b != NULL); - job_b = NULL; - } - EXPECT_EQ(2, URLRequestFilter::GetInstance()->hit_count()); - // Check we can remove URL matching. URLRequestFilter::GetInstance()->RemoveUrlHandler(url_1); EXPECT_TRUE(URLRequestFilter::Factory( &request_1, request_context.network_delegate(), url_1.scheme()) == NULL); - EXPECT_EQ(URLRequestFilter::GetInstance()->hit_count(), 2); + EXPECT_EQ(1, URLRequestFilter::GetInstance()->hit_count()); // Check hostname matching. URLRequestFilter::GetInstance()->ClearHandlers(); @@ -103,27 +104,30 @@ TEST(URLRequestFilter, BasicMatching) { // Check we don't match other hostnames. EXPECT_TRUE(URLRequestFilter::Factory( &request_2, request_context.network_delegate(), url_2.scheme()) == NULL); - EXPECT_EQ(URLRequestFilter::GetInstance()->hit_count(), 1); - - // Check we can overwrite hostname handler. - URLRequestFilter::GetInstance()->AddHostnameHandler(url_1.scheme(), - url_1.host(), - &FactoryA); - { - scoped_refptr<URLRequestJob> found = URLRequestFilter::Factory( - &request_1, request_context.network_delegate(), url_1.scheme()); - EXPECT_EQ(job_a, found); - EXPECT_TRUE(job_a != NULL); - job_a = NULL; - } - EXPECT_EQ(2, URLRequestFilter::GetInstance()->hit_count()); + EXPECT_EQ(1, URLRequestFilter::GetInstance()->hit_count()); // Check we can remove hostname matching. URLRequestFilter::GetInstance()->RemoveHostnameHandler(url_1.scheme(), url_1.host()); EXPECT_TRUE(URLRequestFilter::Factory( &request_1, request_context.network_delegate(), url_1.scheme()) == NULL); - EXPECT_EQ(2, URLRequestFilter::GetInstance()->hit_count()); + EXPECT_EQ(1, URLRequestFilter::GetInstance()->hit_count()); + + // Check ProtocolHandler matching. + URLRequestFilter::GetInstance()->ClearHandlers(); + EXPECT_EQ(0, URLRequestFilter::GetInstance()->hit_count()); + TestProtocolHandler test_protocol_handler; + URLRequestFilter::GetInstance()->AddHostnameProtocolHandler( + url_1.scheme(), url_1.host(), &test_protocol_handler); + { + scoped_refptr<URLRequestJob> found = URLRequestFilter::Factory( + &request_1, request_context.network_delegate(), url_1.scheme()); + EXPECT_EQ(job_c, found); + EXPECT_TRUE(job_c != NULL); + job_c = NULL; + } + EXPECT_EQ(1, URLRequestFilter::GetInstance()->hit_count()); + URLRequestFilter::GetInstance()->ClearHandlers(); } } // namespace diff --git a/net/url_request/url_request_test_util.cc b/net/url_request/url_request_test_util.cc index 9697b1f..c9038ed 100644 --- a/net/url_request/url_request_test_util.cc +++ b/net/url_request/url_request_test_util.cc @@ -544,27 +544,14 @@ const std::string& ScopedCustomUrlRequestTestHttpHost::value() { TestJobInterceptor::TestJobInterceptor() : main_intercept_job_(NULL) { } -URLRequestJob* TestJobInterceptor::MaybeIntercept( - URLRequest* request, - NetworkDelegate* network_delegate) const { +URLRequestJob* TestJobInterceptor::MaybeCreateJob( + URLRequest* request, + NetworkDelegate* network_delegate) const { URLRequestJob* job = main_intercept_job_; main_intercept_job_ = NULL; return job; } -URLRequestJob* TestJobInterceptor::MaybeInterceptRedirect( - const GURL& location, - URLRequest* request, - NetworkDelegate* network_delegate) const { - return NULL; -} - -URLRequestJob* TestJobInterceptor::MaybeInterceptResponse( - URLRequest* request, - NetworkDelegate* network_delegate) const { - return NULL; -} - void TestJobInterceptor::set_main_intercept_job(URLRequestJob* job) { main_intercept_job_ = job; } diff --git a/net/url_request/url_request_test_util.h b/net/url_request/url_request_test_util.h index 323efb2..488d5f2 100644 --- a/net/url_request/url_request_test_util.h +++ b/net/url_request/url_request_test_util.h @@ -300,19 +300,12 @@ class ScopedCustomUrlRequestTestHttpHost { //----------------------------------------------------------------------------- -// A simple Interceptor that returns a pre-built URLRequestJob only once. -class TestJobInterceptor : public URLRequestJobFactory::Interceptor { +// A simple ProtocolHandler that returns a pre-built URLRequestJob only once. +class TestJobInterceptor : public URLRequestJobFactory::ProtocolHandler { public: TestJobInterceptor(); - virtual URLRequestJob* MaybeIntercept( - URLRequest* request, - NetworkDelegate* network_delegate) const OVERRIDE; - virtual URLRequestJob* MaybeInterceptRedirect( - const GURL& location, - URLRequest* request, - NetworkDelegate* network_delegate) const OVERRIDE; - virtual URLRequestJob* MaybeInterceptResponse( + virtual URLRequestJob* MaybeCreateJob( URLRequest* request, NetworkDelegate* network_delegate) const OVERRIDE; void set_main_intercept_job(URLRequestJob* job); diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index 611f04d..977c616 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc @@ -466,18 +466,20 @@ class URLRequestTest : public PlatformTest { default_context_.set_network_delegate(&default_network_delegate_); default_context_.Init(); } + virtual ~URLRequestTest() {} // Adds the TestJobInterceptor to the default context. TestJobInterceptor* AddTestInterceptor() { - TestJobInterceptor* interceptor = new TestJobInterceptor(); - default_context_.set_job_factory(&job_factory_); - job_factory_.AddInterceptor(interceptor); - return interceptor; + TestJobInterceptor* protocol_handler_ = new TestJobInterceptor(); + job_factory_.reset(new URLRequestJobFactoryImpl); + job_factory_->SetProtocolHandler("http", protocol_handler_); + default_context_.set_job_factory(job_factory_.get()); + return protocol_handler_; } protected: TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest. - URLRequestJobFactoryImpl job_factory_; + scoped_ptr<URLRequestJobFactoryImpl> job_factory_; TestURLRequestContext default_context_; }; diff --git a/webkit/tools/test_shell/test_shell.cc b/webkit/tools/test_shell/test_shell.cc index 70954bf..91dd2e9 100644 --- a/webkit/tools/test_shell/test_shell.cc +++ b/webkit/tools/test_shell/test_shell.cc @@ -169,6 +169,9 @@ TestShell::~TestShell() { LoadURL(GURL("about:blank")); } + net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); + filter->RemoveHostnameHandler("test-shell-resource", "inspector"); + // Call GC twice to clean up garbage. CallJSGC(); CallJSGC(); |