diff --git a/browser/BUILD.gn b/browser/BUILD.gn index d50e2d85d14c..009e08298ac0 100644 --- a/browser/BUILD.gn +++ b/browser/BUILD.gn @@ -46,14 +46,12 @@ source_set("browser_process") { "component_updater/brave_component_installer.h", "component_updater/brave_component_updater_configurator.cc", "component_updater/brave_component_updater_configurator.h", + "component_updater/brave_component_updater_delegate.cc", + "component_updater/brave_component_updater_delegate.h", "component_updater/brave_crx_update_service.cc", "component_updater/brave_crx_update_service.h", "content_settings/brave_cookie_settings_factory.cc", "content_settings/brave_cookie_settings_factory.h", - # TODO(bridiver) - move this from extensions -> component_updater - # and rename to BraveComponent - "extensions/brave_component_extension.cc", - "extensions/brave_component_extension.h", "geolocation/brave_geolocation_permission_context.cc", "geolocation/brave_geolocation_permission_context.h", "mac/sparkle_glue.mm", @@ -91,6 +89,7 @@ source_set("browser_process") { "//brave/browser/tor", "//brave/common", "//brave/components/brave_ads/browser", + "//brave/components/brave_component_updater/browser", "//brave/components/brave_referrals/browser", "//brave/components/brave_rewards/browser", "//brave/components/brave_shields/browser:brave_shields", diff --git a/browser/autoplay/autoplay_permission_context_browsertest.cc b/browser/autoplay/autoplay_permission_context_browsertest.cc index 8a51352595de..25d1d485e276 100644 --- a/browser/autoplay/autoplay_permission_context_browsertest.cc +++ b/browser/autoplay/autoplay_permission_context_browsertest.cc @@ -1,4 +1,5 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -10,7 +11,7 @@ #include "brave/browser/brave_content_browser_client.h" #include "brave/common/brave_paths.h" #include "brave/common/pref_names.h" -#include "brave/components/brave_shields/browser/local_data_files_service.h" +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" #include "brave/components/brave_shields/browser/autoplay_whitelist_service.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/extensions/extension_browsertest.h" @@ -36,10 +37,10 @@ const char kVideoPlayingDetect[] = using extensions::ExtensionBrowserTest; -const std::string kLocalDataFilesComponentTestId( - "eclbkhjphkhalklhipiicaldjbnhdfkc"); +const char kLocalDataFilesComponentTestId[] = + "eclbkhjphkhalklhipiicaldjbnhdfkc"; -const std::string kLocalDataFilesComponentTestBase64PublicKey = +const char kLocalDataFilesComponentTestBase64PublicKey[] = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsleoSxQ3DN+6xym2P1uX" "mN6ArIWd9Oru5CSjS0SRE5upM2EnAl/C20TP8JdIlPi/3tk/SN6Y92K3xIhAby5F" "0rbPDSTXEWGy72tv2qb/WySGwDdvYQu9/J5sEDneVcMrSHcC0VWgcZR0eof4BfOy" @@ -49,123 +50,124 @@ const std::string kLocalDataFilesComponentTestBase64PublicKey = "qwIDAQAB"; class AutoplayPermissionContextBrowserTest : public InProcessBrowserTest { - public: - void SetUpOnMainThread() override { - InProcessBrowserTest::SetUpOnMainThread(); - - content_client_.reset(new ChromeContentClient); - content::SetContentClient(content_client_.get()); - browser_content_client_.reset(new BraveContentBrowserClient()); - content::SetBrowserClientForTesting(browser_content_client_.get()); - - host_resolver()->AddRule("*", "127.0.0.1"); - content::SetupCrossSiteRedirector(embedded_test_server()); - - brave::RegisterPathProvider(); - base::FilePath test_data_dir; - base::PathService::Get(brave::DIR_TEST_DATA, &test_data_dir); - test_data_dir = test_data_dir.AppendASCII("autoplay"); - embedded_test_server()->ServeFilesFromDirectory(test_data_dir); - - ASSERT_TRUE(embedded_test_server()->Start()); - - autoplay_method_url_ = - embedded_test_server()->GetURL("a.com", "/autoplay_by_method.html"); - autoplay_attr_url_ = - embedded_test_server()->GetURL("a.com", "/autoplay_by_attr.html"); - autoplay_method_muted_url_ = - embedded_test_server()->GetURL("a.com", "/autoplay_by_method_muted.html"); - autoplay_attr_muted_url_ = - embedded_test_server()->GetURL("a.com", "/autoplay_by_attr_muted.html"); - file_autoplay_method_url_ = - GURL("file://" + test_data_dir.AsUTF8Unsafe() + - "/autoplay_by_method.html"); - file_autoplay_attr_url_ = - GURL("file://" + test_data_dir.AsUTF8Unsafe() + - "/autoplay_by_attr.html"); - - GURL pattern_url = embedded_test_server()->GetURL("a.com", "/index.html"); - top_level_page_pattern_ = - ContentSettingsPattern::FromString(pattern_url.spec()); - } - - void TearDown() override { - browser_content_client_.reset(); - content_client_.reset(); - } - - const GURL& autoplay_method_url() { return autoplay_method_url_; } - const GURL& autoplay_attr_url() { return autoplay_attr_url_; } - const GURL& autoplay_method_muted_url() { return autoplay_method_muted_url_; } - const GURL& autoplay_attr_muted_url() { return autoplay_attr_muted_url_; } - const GURL& file_autoplay_method_url() { return file_autoplay_method_url_; } - const GURL& file_autoplay_attr_url() { return file_autoplay_attr_url_; } - - const ContentSettingsPattern& top_level_page_pattern() { - return top_level_page_pattern_; - } - - HostContentSettingsMap * content_settings() { - return HostContentSettingsMapFactory::GetForProfile(browser()->profile()); - } - - void AllowAutoplay() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern_, - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_AUTOPLAY, - std::string(), - CONTENT_SETTING_ALLOW); - } - - void AskAutoplay() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern_, - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_AUTOPLAY, - std::string(), - CONTENT_SETTING_ASK); - } - - void BlockAutoplay() { - content_settings()->SetContentSettingCustomScope( - top_level_page_pattern_, - ContentSettingsPattern::Wildcard(), - CONTENT_SETTINGS_TYPE_AUTOPLAY, - std::string(), - CONTENT_SETTING_BLOCK); - } - - content::WebContents* contents() { - return browser()->tab_strip_model()->GetActiveWebContents(); - } - - bool NavigateToURLUntilLoadStop(const GURL& url) { - ui_test_utils::NavigateToURL(browser(), url); - return WaitForLoadStop(contents()); - } - - void WaitForPlaying() { - std::string msg_from_renderer; - ASSERT_TRUE(ExecuteScriptAndExtractString(contents(), "notifyWhenPlaying();", - &msg_from_renderer)); - ASSERT_EQ("PLAYING", msg_from_renderer); - } - - private: - GURL autoplay_method_url_; - GURL autoplay_attr_url_; - GURL autoplay_method_muted_url_; - GURL autoplay_attr_muted_url_; - GURL file_autoplay_method_url_; - GURL file_autoplay_attr_url_; - ContentSettingsPattern top_level_page_pattern_; - std::unique_ptr content_client_; - std::unique_ptr browser_content_client_; + public: + void SetUpOnMainThread() override { + InProcessBrowserTest::SetUpOnMainThread(); + + content_client_.reset(new ChromeContentClient); + content::SetContentClient(content_client_.get()); + browser_content_client_.reset(new BraveContentBrowserClient()); + content::SetBrowserClientForTesting(browser_content_client_.get()); + + host_resolver()->AddRule("*", "127.0.0.1"); + content::SetupCrossSiteRedirector(embedded_test_server()); + + brave::RegisterPathProvider(); + base::FilePath test_data_dir; + base::PathService::Get(brave::DIR_TEST_DATA, &test_data_dir); + test_data_dir = test_data_dir.AppendASCII("autoplay"); + embedded_test_server()->ServeFilesFromDirectory(test_data_dir); + + ASSERT_TRUE(embedded_test_server()->Start()); + + autoplay_method_url_ = + embedded_test_server()->GetURL("a.com", "/autoplay_by_method.html"); + autoplay_attr_url_ = + embedded_test_server()->GetURL("a.com", "/autoplay_by_attr.html"); + autoplay_method_muted_url_ = + embedded_test_server()->GetURL("a.com", "/autoplay_by_method_muted.html"); + autoplay_attr_muted_url_ = + embedded_test_server()->GetURL("a.com", "/autoplay_by_attr_muted.html"); + file_autoplay_method_url_ = + GURL("file://" + test_data_dir.AsUTF8Unsafe() + + "/autoplay_by_method.html"); + file_autoplay_attr_url_ = + GURL("file://" + test_data_dir.AsUTF8Unsafe() + + "/autoplay_by_attr.html"); + + GURL pattern_url = embedded_test_server()->GetURL("a.com", "/index.html"); + top_level_page_pattern_ = + ContentSettingsPattern::FromString(pattern_url.spec()); + } + + void TearDown() override { + browser_content_client_.reset(); + content_client_.reset(); + } + + const GURL& autoplay_method_url() { return autoplay_method_url_; } + const GURL& autoplay_attr_url() { return autoplay_attr_url_; } + const GURL& autoplay_method_muted_url() { return autoplay_method_muted_url_; } + const GURL& autoplay_attr_muted_url() { return autoplay_attr_muted_url_; } + const GURL& file_autoplay_method_url() { return file_autoplay_method_url_; } + const GURL& file_autoplay_attr_url() { return file_autoplay_attr_url_; } + + const ContentSettingsPattern& top_level_page_pattern() { + return top_level_page_pattern_; + } + + HostContentSettingsMap * content_settings() { + return HostContentSettingsMapFactory::GetForProfile(browser()->profile()); + } + + void AllowAutoplay() { + content_settings()->SetContentSettingCustomScope( + top_level_page_pattern_, + ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_AUTOPLAY, + std::string(), + CONTENT_SETTING_ALLOW); + } + + void AskAutoplay() { + content_settings()->SetContentSettingCustomScope( + top_level_page_pattern_, + ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_AUTOPLAY, + std::string(), + CONTENT_SETTING_ASK); + } + + void BlockAutoplay() { + content_settings()->SetContentSettingCustomScope( + top_level_page_pattern_, + ContentSettingsPattern::Wildcard(), + CONTENT_SETTINGS_TYPE_AUTOPLAY, + std::string(), + CONTENT_SETTING_BLOCK); + } + + content::WebContents* contents() { + return browser()->tab_strip_model()->GetActiveWebContents(); + } + + bool NavigateToURLUntilLoadStop(const GURL& url) { + ui_test_utils::NavigateToURL(browser(), url); + return WaitForLoadStop(contents()); + } + + void WaitForPlaying() { + std::string msg_from_renderer; + ASSERT_TRUE(ExecuteScriptAndExtractString(contents(), + "notifyWhenPlaying();", + &msg_from_renderer)); + ASSERT_EQ("PLAYING", msg_from_renderer); + } + + private: + GURL autoplay_method_url_; + GURL autoplay_attr_url_; + GURL autoplay_method_muted_url_; + GURL autoplay_attr_muted_url_; + GURL file_autoplay_method_url_; + GURL file_autoplay_attr_url_; + ContentSettingsPattern top_level_page_pattern_; + std::unique_ptr content_client_; + std::unique_ptr browser_content_client_; }; class AutoplayWhitelistServiceTest : public ExtensionBrowserTest { -public: + public: AutoplayWhitelistServiceTest() {} void SetUp() override { @@ -185,7 +187,8 @@ class AutoplayWhitelistServiceTest : public ExtensionBrowserTest { void PreRunTestOnMainThread() override { ExtensionBrowserTest::PreRunTestOnMainThread(); WaitForAutoplayWhitelistServiceThread(); - ASSERT_TRUE(g_brave_browser_process->local_data_files_service()->IsInitialized()); + ASSERT_TRUE( + g_brave_browser_process->local_data_files_service()->IsInitialized()); } void InitEmbeddedTestServer() { @@ -198,7 +201,7 @@ class AutoplayWhitelistServiceTest : public ExtensionBrowserTest { } void InitService() { - brave_shields::LocalDataFilesService:: + brave_component_updater::LocalDataFilesService:: SetComponentIdAndBase64PublicKeyForTest( kLocalDataFilesComponentTestId, kLocalDataFilesComponentTestBase64PublicKey); @@ -212,8 +215,8 @@ class AutoplayWhitelistServiceTest : public ExtensionBrowserTest { bool InstallAutoplayWhitelistExtension() { base::FilePath test_data_dir; GetTestDataDir(&test_data_dir); - const extensions::Extension* mock_extension = - InstallExtension(test_data_dir.AppendASCII("autoplay-whitelist-data"), 1); + const extensions::Extension* mock_extension = InstallExtension( + test_data_dir.AppendASCII("autoplay-whitelist-data"), 1); if (!mock_extension) return false; @@ -225,9 +228,8 @@ class AutoplayWhitelistServiceTest : public ExtensionBrowserTest { } void WaitForAutoplayWhitelistServiceThread() { - scoped_refptr io_helper( - new base::ThreadTestHelper( - g_brave_browser_process->autoplay_whitelist_service()->GetTaskRunner())); + scoped_refptr io_helper(new base::ThreadTestHelper( + g_brave_browser_process->local_data_files_service()->GetTaskRunner())); ASSERT_TRUE(io_helper->Run()); } @@ -242,14 +244,15 @@ class AutoplayWhitelistServiceTest : public ExtensionBrowserTest { void WaitForPlaying() { std::string msg_from_renderer; - ASSERT_TRUE(ExecuteScriptAndExtractString(contents(), "notifyWhenPlaying();", + ASSERT_TRUE(ExecuteScriptAndExtractString(contents(), + "notifyWhenPlaying();", &msg_from_renderer)); ASSERT_EQ("PLAYING", msg_from_renderer); } const GURL& whitelist_autoplay_url() { return whitelist_autoplay_url_; } -private: + private: GURL whitelist_autoplay_url_; }; diff --git a/browser/brave_browser_process_impl.cc b/browser/brave_browser_process_impl.cc index c6267149bac2..8c428cef1719 100644 --- a/browser/brave_browser_process_impl.cc +++ b/browser/brave_browser_process_impl.cc @@ -13,15 +13,16 @@ #include "base/threading/sequenced_task_runner_handle.h" #include "brave/browser/brave_stats_updater.h" #include "brave/browser/component_updater/brave_component_updater_configurator.h" +#include "brave/browser/component_updater/brave_component_updater_delegate.h" #include "brave/browser/extensions/brave_tor_client_updater.h" #include "brave/browser/profiles/brave_profile_manager.h" +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" #include "brave/components/brave_shields/browser/ad_block_custom_filters_service.h" #include "brave/components/brave_shields/browser/ad_block_regional_service_manager.h" #include "brave/components/brave_shields/browser/ad_block_service.h" #include "brave/components/brave_shields/browser/autoplay_whitelist_service.h" #include "brave/components/brave_shields/browser/extension_whitelist_service.h" #include "brave/components/brave_shields/browser/https_everywhere_service.h" -#include "brave/components/brave_shields/browser/local_data_files_service.h" #include "brave/components/brave_shields/browser/referrer_whitelist_service.h" #include "brave/components/brave_shields/browser/tracking_protection_service.h" #include "chrome/browser/io_thread.h" @@ -47,8 +48,7 @@ BraveBrowserProcessImpl* g_brave_browser_process = nullptr; using content::BrowserThread; -BraveBrowserProcessImpl::~BraveBrowserProcessImpl() { -} +BraveBrowserProcessImpl::~BraveBrowserProcessImpl() {} BraveBrowserProcessImpl::BraveBrowserProcessImpl(StartupData* startup_data) : BrowserProcessImpl(startup_data) { @@ -76,6 +76,15 @@ BraveBrowserProcessImpl::BraveBrowserProcessImpl(StartupData* startup_data) base::Unretained(brave_stats_updater_.get()))); } +brave_component_updater::BraveComponent::Delegate* +BraveBrowserProcessImpl::brave_component_updater_delegate() { + if (!brave_component_updater_delegate_) + brave_component_updater_delegate_ = + std::make_unique(); + + return brave_component_updater_delegate_.get(); +} + component_updater::ComponentUpdateService* BraveBrowserProcessImpl::component_updater() { if (component_updater_) @@ -105,6 +114,23 @@ BraveBrowserProcessImpl::component_updater() { return component_updater_.get(); } +void BraveBrowserProcessImpl::ResourceDispatcherHostCreated() { + BrowserProcessImpl::ResourceDispatcherHostCreated(); + ad_block_service()->Start(); + ad_block_custom_filters_service()->Start(); + ad_block_regional_service_manager()->Start(); + https_everywhere_service()->Start(); + + autoplay_whitelist_service(); +#if BUILDFLAG(ENABLE_EXTENSIONS) + extension_whitelist_service(); +#endif + referrer_whitelist_service(); + tracking_protection_service(); + // Now start the local data files service, which calls all observers. + local_data_files_service()->Start(); +} + ProfileManager* BraveBrowserProcessImpl::profile_manager() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!created_profile_manager_) @@ -117,7 +143,8 @@ BraveBrowserProcessImpl::ad_block_service() { if (ad_block_service_) return ad_block_service_.get(); - ad_block_service_ = brave_shields::AdBlockServiceFactory(); + ad_block_service_ = + brave_shields::AdBlockServiceFactory(brave_component_updater_delegate()); return ad_block_service_.get(); } @@ -125,7 +152,8 @@ brave_shields::AdBlockCustomFiltersService* BraveBrowserProcessImpl::ad_block_custom_filters_service() { if (!ad_block_custom_filters_service_) ad_block_custom_filters_service_ = - brave_shields::AdBlockCustomFiltersServiceFactory(); + brave_shields::AdBlockCustomFiltersServiceFactory( + brave_component_updater_delegate()); return ad_block_custom_filters_service_.get(); } @@ -133,7 +161,8 @@ brave_shields::AdBlockRegionalServiceManager* BraveBrowserProcessImpl::ad_block_regional_service_manager() { if (!ad_block_regional_service_manager_) ad_block_regional_service_manager_ = - brave_shields::AdBlockRegionalServiceManagerFactory(); + brave_shields::AdBlockRegionalServiceManagerFactory( + brave_component_updater_delegate()); return ad_block_regional_service_manager_.get(); } @@ -141,7 +170,8 @@ brave_shields::AutoplayWhitelistService* BraveBrowserProcessImpl::autoplay_whitelist_service() { if (!autoplay_whitelist_service_) { autoplay_whitelist_service_ = - brave_shields::AutoplayWhitelistServiceFactory(); + brave_shields::AutoplayWhitelistServiceFactory( + local_data_files_service()); } return autoplay_whitelist_service_.get(); } @@ -151,7 +181,8 @@ brave_shields::ExtensionWhitelistService* BraveBrowserProcessImpl::extension_whitelist_service() { if (!extension_whitelist_service_) { extension_whitelist_service_ = - brave_shields::ExtensionWhitelistServiceFactory(); + brave_shields::ExtensionWhitelistServiceFactory( + local_data_files_service()); } return extension_whitelist_service_.get(); } @@ -161,7 +192,8 @@ brave_shields::ReferrerWhitelistService* BraveBrowserProcessImpl::referrer_whitelist_service() { if (!referrer_whitelist_service_) { referrer_whitelist_service_ = - brave_shields::ReferrerWhitelistServiceFactory(); + brave_shields::ReferrerWhitelistServiceFactory( + local_data_files_service()); } return referrer_whitelist_service_.get(); } @@ -170,7 +202,8 @@ brave_shields::TrackingProtectionService* BraveBrowserProcessImpl::tracking_protection_service() { if (!tracking_protection_service_) { tracking_protection_service_ = - brave_shields::TrackingProtectionServiceFactory(); + brave_shields::TrackingProtectionServiceFactory( + local_data_files_service()); } return tracking_protection_service_.get(); } @@ -179,15 +212,17 @@ brave_shields::HTTPSEverywhereService* BraveBrowserProcessImpl::https_everywhere_service() { if (!https_everywhere_service_) https_everywhere_service_ = - brave_shields::HTTPSEverywhereServiceFactory(); + brave_shields::HTTPSEverywhereServiceFactory( + brave_component_updater_delegate()); return https_everywhere_service_.get(); } -brave_shields::LocalDataFilesService* +brave_component_updater::LocalDataFilesService* BraveBrowserProcessImpl::local_data_files_service() { if (!local_data_files_service_) local_data_files_service_ = - brave_shields::LocalDataFilesServiceFactory(); + brave_component_updater::LocalDataFilesServiceFactory( + brave_component_updater_delegate()); return local_data_files_service_.get(); } @@ -197,7 +232,8 @@ BraveBrowserProcessImpl::tor_client_updater() { if (tor_client_updater_) return tor_client_updater_.get(); - tor_client_updater_ = extensions::BraveTorClientUpdaterFactory(); + tor_client_updater_ = extensions::BraveTorClientUpdaterFactory( + brave_component_updater_delegate()); return tor_client_updater_.get(); } #endif diff --git a/browser/brave_browser_process_impl.h b/browser/brave_browser_process_impl.h index 0acde8c42eae..08c97a2f62e2 100644 --- a/browser/brave_browser_process_impl.h +++ b/browser/brave_browser_process_impl.h @@ -9,6 +9,7 @@ #include #include "brave/browser/tor/buildflags.h" +#include "brave/components/brave_component_updater/browser/brave_component.h" #include "brave/components/brave_referrals/buildflags/buildflags.h" #include "chrome/browser/browser_process_impl.h" #include "extensions/buildflags/buildflags.h" @@ -23,6 +24,10 @@ class BraveStatsUpdater; class BraveWidevineBundleManager; #endif +namespace brave_component_updater { +class LocalDataFilesService; +} + namespace brave_shields { class AdBlockService; class AdBlockCustomFiltersService; @@ -30,7 +35,6 @@ class AdBlockRegionalServiceManager; class AutoplayWhitelistService; class ExtensionWhitelistService; class HTTPSEverywhereService; -class LocalDataFilesService; class ReferrerWhitelistService; class TrackingProtectionService; } // namespace brave_shields @@ -39,6 +43,8 @@ namespace extensions { class BraveTorClientUpdater; } +using brave_component_updater::BraveComponent; + class BraveBrowserProcessImpl : public BrowserProcessImpl { public: explicit BraveBrowserProcessImpl(StartupData* startup_data); @@ -46,6 +52,7 @@ class BraveBrowserProcessImpl : public BrowserProcessImpl { // BrowserProcess implementation. component_updater::ComponentUpdateService* component_updater() override; + void ResourceDispatcherHostCreated() override; ProfileManager* profile_manager() override; @@ -60,7 +67,7 @@ class BraveBrowserProcessImpl : public BrowserProcessImpl { brave_shields::ReferrerWhitelistService* referrer_whitelist_service(); brave_shields::TrackingProtectionService* tracking_protection_service(); brave_shields::HTTPSEverywhereService* https_everywhere_service(); - brave_shields::LocalDataFilesService* local_data_files_service(); + brave_component_updater::LocalDataFilesService* local_data_files_service(); #if BUILDFLAG(ENABLE_TOR) extensions::BraveTorClientUpdater* tor_client_updater(); #endif @@ -71,6 +78,9 @@ class BraveBrowserProcessImpl : public BrowserProcessImpl { private: void CreateProfileManager(); + BraveComponent::Delegate* brave_component_updater_delegate(); + + std::unique_ptr brave_component_updater_delegate_; std::unique_ptr ad_block_service_; std::unique_ptr ad_block_custom_filters_service_; @@ -86,7 +96,7 @@ class BraveBrowserProcessImpl : public BrowserProcessImpl { tracking_protection_service_; std::unique_ptr https_everywhere_service_; - std::unique_ptr + std::unique_ptr local_data_files_service_; std::unique_ptr brave_stats_updater_; #if BUILDFLAG(ENABLE_BRAVE_REFERRALS) diff --git a/browser/component_updater/brave_component_installer.cc b/browser/component_updater/brave_component_installer.cc index 7382813f0775..0adf37b960b1 100644 --- a/browser/component_updater/brave_component_installer.cc +++ b/browser/component_updater/brave_component_installer.cc @@ -1,4 +1,5 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -22,6 +23,8 @@ #include "components/update_client/utils.h" #include "crypto/sha2.h" +using brave_component_updater::BraveComponent; + namespace { using Result = update_client::CrxInstaller::Result; using InstallError = update_client::InstallError; @@ -77,10 +80,10 @@ namespace brave { BraveComponentInstallerPolicy::BraveComponentInstallerPolicy( const std::string& name, const std::string& base64_public_key, - const ReadyCallback& ready_callback) + BraveComponent::ReadyCallback ready_callback) : name_(name), base64_public_key_(base64_public_key), - ready_callback_(ready_callback) { + ready_callback_(std::move(ready_callback)) { base::Base64Decode(base64_public_key, &public_key_); } @@ -99,7 +102,8 @@ bool BraveComponentInstallerPolicy::VerifyInstallation( install_dir.Append(FILE_PATH_LITERAL("manifest.json"))); } -bool BraveComponentInstallerPolicy::SupportsGroupPolicyEnabledComponentUpdates() const { +bool BraveComponentInstallerPolicy:: +SupportsGroupPolicyEnabledComponentUpdates() const { return false; } @@ -107,7 +111,8 @@ bool BraveComponentInstallerPolicy::RequiresNetworkEncryption() const { return false; } -update_client::CrxInstaller::Result BraveComponentInstallerPolicy::OnCustomInstall( +update_client::CrxInstaller::Result +BraveComponentInstallerPolicy::OnCustomInstall( const base::DictionaryValue& manifest, const base::FilePath& install_dir) { return Result(InstallError::NONE); @@ -117,10 +122,12 @@ void BraveComponentInstallerPolicy::OnCustomUninstall() { } void BraveComponentInstallerPolicy::ComponentReady( - const base::Version& version, - const base::FilePath& install_dir, - std::unique_ptr manifest) { - ready_callback_.Run(install_dir, GetManifestString(*manifest, base64_public_key_)); + const base::Version& version, + const base::FilePath& install_dir, + std::unique_ptr manifest) { + std::move(ready_callback_).Run( + install_dir, + GetManifestString(*manifest, base64_public_key_)); } base::FilePath BraveComponentInstallerPolicy::GetRelativeInstallDir() const { @@ -144,7 +151,8 @@ std::vector BraveComponentInstallerPolicy::GetMimeTypes() const { return std::vector(); } -update_client::InstallerAttributes BraveComponentInstallerPolicy::GetInstallerAttributes() const { +update_client::InstallerAttributes +BraveComponentInstallerPolicy::GetInstallerAttributes() const { return update_client::InstallerAttributes(); } @@ -152,11 +160,12 @@ void RegisterComponent( component_updater::ComponentUpdateService* cus, const std::string& name, const std::string& base64_public_key, - const base::Closure& registered_callback, - const ReadyCallback& ready_callback) { + base::OnceClosure registered_callback, + BraveComponent::ReadyCallback ready_callback) { auto installer = base::MakeRefCounted( - std::make_unique(name, base64_public_key, ready_callback)); - installer->Register(cus, registered_callback); + std::make_unique( + name, base64_public_key, std::move(ready_callback))); + installer->Register(cus, std::move(registered_callback)); } } // namespace brave diff --git a/browser/component_updater/brave_component_installer.h b/browser/component_updater/brave_component_installer.h index 520b885e16c7..fa277d11f5d5 100644 --- a/browser/component_updater/brave_component_installer.h +++ b/browser/component_updater/brave_component_installer.h @@ -1,9 +1,10 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_BRAVE_COMPONENT_INSTALLER_H_ -#define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_BRAVE_COMPONENT_INSTALLER_H_ +#ifndef BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_COMPONENT_INSTALLER_H_ +#define BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_COMPONENT_INSTALLER_H_ #include @@ -15,15 +16,11 @@ #include "base/callback.h" #include "base/files/file_path.h" #include "base/macros.h" +#include "brave/components/brave_component_updater/browser/brave_component.h" #include "components/component_updater/component_installer.h" #include "components/update_client/update_client.h" -namespace base { -class FilePath; -} // namespace base - -using ReadyCallback = base::Callback; +using brave_component_updater::BraveComponent; namespace brave { @@ -32,7 +29,7 @@ class BraveComponentInstallerPolicy : public: explicit BraveComponentInstallerPolicy(const std::string& name, const std::string& base64_public_key, - const ReadyCallback& ready_callback); + BraveComponent::ReadyCallback ready_callback); ~BraveComponentInstallerPolicy() override; @@ -59,7 +56,7 @@ class BraveComponentInstallerPolicy : std::string name_; std::string base64_public_key_; std::string public_key_; - ReadyCallback ready_callback_; + BraveComponent::ReadyCallback ready_callback_; DISALLOW_COPY_AND_ASSIGN(BraveComponentInstallerPolicy); }; @@ -67,9 +64,9 @@ class BraveComponentInstallerPolicy : void RegisterComponent(component_updater::ComponentUpdateService* cus, const std::string& name, const std::string& base64_public_key, - const base::Closure& registered_callback, - const ReadyCallback& ready_callback); + base::OnceClosure registered_callback, + BraveComponent::ReadyCallback ready_callback); } // namespace brave -#endif // BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_BRAVE_COMPONENT_INSTALLER_H_ +#endif // BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_COMPONENT_INSTALLER_H_ diff --git a/browser/component_updater/brave_component_updater_delegate.cc b/browser/component_updater/brave_component_updater_delegate.cc new file mode 100644 index 000000000000..80bb130b63f7 --- /dev/null +++ b/browser/component_updater/brave_component_updater_delegate.cc @@ -0,0 +1,58 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/browser/component_updater/brave_component_updater_delegate.h" + +#include + +#include "base/sequenced_task_runner.h" +#include "base/task/post_task.h" +#include "brave/browser/component_updater/brave_component_installer.h" +#include "chrome/browser/ui/webui/components_ui.h" +#include "chrome/browser/browser_process.h" +#include "components/component_updater/component_updater_service.h" + +using brave_component_updater::BraveComponent; + +namespace brave { + +BraveComponentUpdaterDelegate::BraveComponentUpdaterDelegate() + : task_runner_( + base::CreateSequencedTaskRunnerWithTraits({base::MayBlock(), + base::TaskPriority::USER_VISIBLE, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) { +} + +BraveComponentUpdaterDelegate::~BraveComponentUpdaterDelegate() {} + +void BraveComponentUpdaterDelegate::Register( + const std::string& component_name, + const std::string& component_base64_public_key, + base::OnceClosure registered_callback, + BraveComponent::ReadyCallback ready_callback) { + brave::RegisterComponent(g_browser_process->component_updater(), + component_name, + component_base64_public_key, + std::move(registered_callback), + std::move(ready_callback)); +} + +bool BraveComponentUpdaterDelegate::Unregister( + const std::string& component_id) { + return g_browser_process->component_updater()->UnregisterComponent( + component_id); +} + +void BraveComponentUpdaterDelegate::OnDemandUpdate( + const std::string& component_id) { + ComponentsUI::OnDemandUpdate(component_id); +} + +scoped_refptr +BraveComponentUpdaterDelegate::GetTaskRunner() { + return task_runner_; +} + +} // namespace brave diff --git a/browser/component_updater/brave_component_updater_delegate.h b/browser/component_updater/brave_component_updater_delegate.h new file mode 100644 index 000000000000..275b2db476ef --- /dev/null +++ b/browser/component_updater/brave_component_updater_delegate.h @@ -0,0 +1,44 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_COMPONENT_UPDATER_DELEGATE_H_ +#define BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_COMPONENT_UPDATER_DELEGATE_H_ + +#include + +#include "base/macros.h" +#include "brave/components/brave_component_updater/browser/brave_component.h" + +using brave_component_updater::BraveComponent; + +namespace base { +class SequencedTaskRunner; +} + +namespace brave { + +class BraveComponentUpdaterDelegate : public BraveComponent::Delegate { + public: + BraveComponentUpdaterDelegate(); + ~BraveComponentUpdaterDelegate() override; + + // brave_component_updater::BraveComponent::Delegate implementation + void Register(const std::string& component_name, + const std::string& component_base64_public_key, + base::OnceClosure registered_callback, + BraveComponent::ReadyCallback ready_callback) override; + bool Unregister(const std::string& component_id) override; + void OnDemandUpdate(const std::string& component_id) override; + scoped_refptr GetTaskRunner() override; + + private: + scoped_refptr task_runner_; + + DISALLOW_COPY_AND_ASSIGN(BraveComponentUpdaterDelegate); +}; + +} // namespace brave + +#endif // BRAVE_BROWSER_COMPONENT_UPDATER_BRAVE_COMPONENT_UPDATER_DELEGATE_H_ diff --git a/browser/component_updater/brave_crx_update_service.cc b/browser/component_updater/brave_crx_update_service.cc index 8f9e98e17b1c..6988fe6e96fe 100644 --- a/browser/component_updater/brave_crx_update_service.cc +++ b/browser/component_updater/brave_crx_update_service.cc @@ -42,44 +42,6 @@ void BraveCrxUpdateService::Start() { base::DoNothing()); } -bool BraveCrxUpdateService::RegisterComponent(const CrxComponent& component) { - DCHECK(thread_checker_.CalledOnValidThread()); - if (component.pk_hash.empty() || !component.version.IsValid() || - !component.installer) { - return false; - } - - // Update the registration data if the component has been registered before. - const std::string id(GetCrxComponentID(component)); - auto it = components_.find(id); - if (it != components_.end()) { - it->second = component; - return true; - } - - components_.insert(std::make_pair(id, component)); - components_order_.push_back(id); - for (const auto& mime_type : component.handled_mime_types) - component_ids_by_mime_type_[mime_type] = id; - - // Create an initial state for this component. The state is mutated in - // response to events from the UpdateClient instance. - CrxUpdateItem item; - item.id = id; - item.component = component; - const auto inserted = component_states_.insert(std::make_pair(id, item)); - DCHECK(inserted.second); - - // Start the timer if this is the first component registered. The first timer - // event occurs after an interval defined by the component update - // configurator. The subsequent timer events are repeated with a period - // defined by the same configurator. - if (components_.size() == 1) - Start(); - - return true; -} - bool BraveCrxUpdateService::CheckForUpdates( UpdateScheduler::OnFinishedCallback on_finished) { DCHECK(thread_checker_.CalledOnValidThread()); diff --git a/browser/component_updater/brave_crx_update_service.h b/browser/component_updater/brave_crx_update_service.h index edfe6b63e972..41619c24dbed 100644 --- a/browser/component_updater/brave_crx_update_service.h +++ b/browser/component_updater/brave_crx_update_service.h @@ -23,7 +23,6 @@ class BraveCrxUpdateService : public CrxUpdateService { std::unique_ptr scheduler, scoped_refptr update_client); - bool RegisterComponent(const CrxComponent& component) override; ~BraveCrxUpdateService() override {} private: diff --git a/browser/extensions/BUILD.gn b/browser/extensions/BUILD.gn index e9b1c55fe5c6..458fb23096f1 100644 --- a/browser/extensions/BUILD.gn +++ b/browser/extensions/BUILD.gn @@ -45,6 +45,7 @@ source_set("extensions") { "//brave/app:brave_generated_resources_grit", "//brave/common:pref_names", "//brave/common/extensions/api", + "//brave/components/brave_component_updater/browser", "//brave/components/brave_extension:static_resources", "//brave/components/brave_extension:generated_resources", "//brave/components/brave_sync", diff --git a/browser/extensions/brave_component_extension.cc b/browser/extensions/brave_component_extension.cc deleted file mode 100644 index ffb34dcefdc8..000000000000 --- a/browser/extensions/brave_component_extension.cc +++ /dev/null @@ -1,63 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/browser/extensions/brave_component_extension.h" - -#include - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "brave/browser/component_updater/brave_component_installer.h" -#include "chrome/browser/browser_process.h" - -void ComponentsUI::OnDemandUpdate( - component_updater::ComponentUpdateService* cus, - const std::string& component_id) { - cus->GetOnDemandUpdater().OnDemandUpdate( - component_id, component_updater::OnDemandUpdater::Priority::FOREGROUND, - component_updater::Callback()); -} - -BraveComponentExtension::BraveComponentExtension() { -} - -BraveComponentExtension::~BraveComponentExtension() { -} - -void BraveComponentExtension::Register( - const std::string& component_name, - const std::string& component_id, - const std::string& component_base64_public_key) { - component_name_ = component_name; - component_id_ = component_id; - component_base64_public_key_ = component_base64_public_key; - - base::Closure registered_callback = - base::Bind(&BraveComponentExtension::OnComponentRegistered, - base::Unretained(this), component_id_); - ReadyCallback ready_callback = - base::Bind(&BraveComponentExtension::OnComponentReady, - base::Unretained(this), component_id_); - brave::RegisterComponent(g_browser_process->component_updater(), - component_name_, component_base64_public_key_, - registered_callback, ready_callback); -} - -// static -bool BraveComponentExtension::Unregister(const std::string& component_id) { - return g_browser_process->component_updater()->UnregisterComponent( - component_id); -} - -void BraveComponentExtension::OnComponentRegistered(const std::string& component_id) { - OnDemandUpdate(g_browser_process->component_updater(), component_id); -} - -void BraveComponentExtension::OnComponentReady( - const std::string& component_id, - const base::FilePath& install_dir, - const std::string& manifest) { -} diff --git a/browser/extensions/brave_component_extension.h b/browser/extensions/brave_component_extension.h deleted file mode 100644 index f9a5f783dfb7..000000000000 --- a/browser/extensions/brave_component_extension.h +++ /dev/null @@ -1,44 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_EXTENSIONS_BRAVE_COMPONENT_EXTENSION_H_ -#define BRAVE_BROWSER_EXTENSIONS_BRAVE_COMPONENT_EXTENSION_H_ - -#include - -#include "base/files/file_path.h" -#include "components/component_updater/component_updater_service.h" - -// Just used to give access to OnDemandUpdater since it's private. -// Chromium has ComponentsUI which is a friend class, so we just -// do this hack here to gain access. -class ComponentsUI { - public: - void OnDemandUpdate(component_updater::ComponentUpdateService* cus, - const std::string& component_id); -}; - -class BraveComponentExtension : public ComponentsUI { - public: - BraveComponentExtension(); - virtual ~BraveComponentExtension(); - void Register(const std::string& component_name, - const std::string& component_id, - const std::string& component_base64_public_key); - static bool Unregister(const std::string& component_id); - - protected: - virtual void OnComponentRegistered(const std::string& component_id); - virtual void OnComponentReady(const std::string& component_id, - const base::FilePath& install_dir, - const std::string& manifest); - - private: - std::string component_name_; - std::string component_id_; - std::string component_base64_public_key_; -}; - -#endif // BRAVE_BROWSER_EXTENSIONS_BRAVE_COMPONENT_EXTENSION_H_ diff --git a/browser/extensions/brave_component_loader.cc b/browser/extensions/brave_component_loader.cc index 11f0ab83a4db..27ce4c616f51 100644 --- a/browser/extensions/brave_component_loader.cc +++ b/browser/extensions/brave_component_loader.cc @@ -10,7 +10,6 @@ #include "base/command_line.h" #include "brave/browser/brave_browser_process_impl.h" #include "brave/browser/component_updater/brave_component_installer.h" -#include "brave/browser/extensions/brave_component_extension.h" #include "brave/common/brave_switches.h" #include "brave/common/extensions/extension_constants.h" #include "brave/common/pref_names.h" @@ -19,6 +18,7 @@ #include "brave/components/brave_rewards/resources/extension/grit/brave_rewards_extension_resources.h" #include "brave/components/brave_webtorrent/grit/brave_webtorrent_resources.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/components_ui.h" #include "chrome/common/pref_names.h" #include "components/grit/brave_components_resources.h" #include "extensions/browser/extension_prefs.h" @@ -27,9 +27,13 @@ namespace extensions { // static bool BraveComponentLoader::IsPdfjsDisabled() { +#if defined(OS_ANDROID) + return true; +#else const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); return command_line.HasSwitch(switches::kDisablePDFJSExtension); +#endif } BraveComponentLoader::BraveComponentLoader( @@ -41,18 +45,18 @@ BraveComponentLoader::BraveComponentLoader( profile_(profile), profile_prefs_(profile_prefs), testing_callbacks_(nullptr) { +// TODO(bridiver) - this doesn't belong here +#if !defined(OS_ANDROID) ObserveOpenPdfExternallySetting(); +#endif } BraveComponentLoader::~BraveComponentLoader() { } void BraveComponentLoader::OnComponentRegistered(std::string extension_id) { - ComponentsUI demand_updater; - // This weird looking call is ok, it is just like this to not need - // to patch for friend access. - demand_updater.OnDemandUpdate(g_browser_process->component_updater(), - extension_id); + // TODO(bridiver) - I don't think this is correct + ComponentsUI::OnDemandUpdate(extension_id); } void BraveComponentLoader::OnComponentReady(std::string extension_id, @@ -126,6 +130,7 @@ void BraveComponentLoader::AddDefaultComponentExtensions( } } +#if !defined(OS_ANDROID) void BraveComponentLoader::ObserveOpenPdfExternallySetting() { // Observe the setting change only in regular profiles since the PDF settings // page is not available in Guest/Tor profiles. @@ -137,6 +142,7 @@ void BraveComponentLoader::ObserveOpenPdfExternallySetting() { base::Unretained(this))); } } +#endif void BraveComponentLoader::UpdatePdfExtension(const std::string& pref_name) { DCHECK(pref_name == prefs::kPluginsAlwaysOpenPdfExternally); diff --git a/browser/extensions/brave_component_loader.h b/browser/extensions/brave_component_loader.h index 96aac12a09e0..8bd95731a4f4 100644 --- a/browser/extensions/brave_component_loader.h +++ b/browser/extensions/brave_component_loader.h @@ -48,7 +48,9 @@ class BraveComponentLoader : public ComponentLoader { void AddHangoutServicesExtension() override; #endif // BUILDFLAG(ENABLE_HANGOUT_SERVICES_EXTENSION) friend class ::BraveComponentLoaderTest; +#if !defined(OS_ANDROID) void ObserveOpenPdfExternallySetting(); +#endif // Callback for changes to the AlwaysOpenPdfExternally setting. void UpdatePdfExtension(const std::string& pref_name); diff --git a/browser/extensions/brave_extension_provider.cc b/browser/extensions/brave_extension_provider.cc index f702f74217ea..2db1f5ca1031 100644 --- a/browser/extensions/brave_extension_provider.cc +++ b/browser/extensions/brave_extension_provider.cc @@ -12,8 +12,8 @@ #include "base/strings/utf_string_conversions.h" #include "brave/browser/brave_browser_process_impl.h" #include "brave/common/extensions/extension_constants.h" +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" #include "brave/components/brave_shields/browser/extension_whitelist_service.h" -#include "brave/components/brave_shields/browser/local_data_files_service.h" #include "brave/grit/brave_generated_resources.h" #include "ui/base/l10n/l10n_util.h" @@ -61,7 +61,7 @@ bool BraveExtensionProvider::IsVetted(const std::string id) { pdfjs_extension_id, hangouts_extension_id, widevine_extension_id, - brave_shields::kLocalDataFilesComponentId, + brave_component_updater::kLocalDataFilesComponentId, // Web Store "ahfgeienlihckogmohjhadlkjgocpleb", // Brave Automation Extension diff --git a/browser/extensions/brave_tor_client_updater.cc b/browser/extensions/brave_tor_client_updater.cc index 8550b7f47516..43892218e6aa 100644 --- a/browser/extensions/brave_tor_client_updater.cc +++ b/browser/extensions/brave_tor_client_updater.cc @@ -1,24 +1,66 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "brave/browser/extensions/brave_tor_client_updater.h" +#include +#include + #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/task/post_task.h" #include "third_party/re2/src/re2/re2.h" +using brave_component_updater::BraveComponent; + namespace extensions { +#if defined(OS_WIN) +const char kTorClientComponentName[] = "Brave Tor Client Updater (Windows)"; +const char kTorClientComponentId[] = "cpoalefficncklhjfpglfiplenlpccdb"; +const char kTorClientComponentBase64PublicKey[] = + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1AYAsmR/VoRwkZCsjRpD" + "58xjrgngW5y17H6BqQ7/CeNSpmXlcMXy6bJs2D/yeS96rhZSrQSHTzS9h/ieo/NZ" + "F5PIwcv07YsG5sRd6zF5a6m92aWCQa1OkbL6jpcpL2Tbc4mCqNxhKMErT7EtIIWL" + "9cW+mtFUjUjvV3rJLQ3Vy9u6fEi77Y8b25kGnTJoVt3uETAIHBnyNpL7ac2f8Iq+" + "4Qa6VFmuoBhup54tTZvMv+ikoKKaQkHzkkjTa4hV5AzdnFDKO8C9qJb3T/Ef0+MO" + "IuZjyySVzGNcOfASeHkhxhlwMQSQuhCN5mdFW5YBnVZ/5QWx8WzbhqBny/ZynS4e" + "rQIDAQAB"; +#elif defined(OS_MACOSX) +const char kTorClientComponentName[] = "Brave Tor Client Updater (Mac)"; +const char kTorClientComponentId[] = "cldoidikboihgcjfkhdeidbpclkineef"; +const char kTorClientComponentBase64PublicKey[] = + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw2QUXSbVuRxYpItYApZ8" + "Ly/fGeUD3A+vb3J7Ot62CF32wTfWweANWyyB+EBGfbtNDAuRlAbNk0QYeCQEttuf" + "jLh3Kd5KR5fSyyNNd2cAzAckQ8p7JdiFYjvqZLGC5vlnHgqq4O8xACX5EPwHLNFD" + "iSpsthNmz3GCUrHrzPHjHVfy+IuucQXygnRv2fwIaAIxJmTbYm4fqsGKpfolWdMe" + "jKVAy1hc9mApZSyt4oGvUu4SJZnxlYMrY4Ze+OWbDesi2JGy+6dA1ddL9IdnwCb3" + "9CBOMNjaHeCVz0MKxdCWGPieQM0R7S1KvDCVqAkss6NAbLB6AVM0JulqxC9b+hr/" + "xwIDAQAB"; +#elif defined(OS_LINUX) +const char kTorClientComponentName[] = "Brave Tor Client Updater (Linux)"; +const char kTorClientComponentId[] = "biahpgbdmdkfgndcmfiipgcebobojjkp"; +const char kTorClientComponentBase64PublicKey[] = + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseuq8dXKawkZC7RSE7xb" + "lRwh6DD+oPEGEjZWKh596/42IrWNQw60gRIR6s7x0YHh5geFnBRkx9bisEXOrFkq" + "oArVY7eD0gMkjpor9CneD5CnCxc9/2uIPajtXfAmmLAHtN6Wk7yW30SkRf/WvLWX" + "/H+PqskQBN7I5MO7sveYxSrRMSj7prrFHEiFmXTgG/DwjpzrA7KV6vmzz/ReD51o" + "+UuLHE7cxPhnsNd/52uY3Lod3GhxvDoXKYx9kWlzBjxB53A2eLBCDIwwCpqS4/Ib" + "RSJhvF33KQT8YM+7V1MitwB49klP4aEWPXwOlFHmn9Dkmlx2RbO7S0tRcH9UH4LK" + "2QIDAQAB"; +#endif + std::string BraveTorClientUpdater::g_tor_client_component_id_( kTorClientComponentId); std::string BraveTorClientUpdater::g_tor_client_component_base64_public_key_( kTorClientComponentBase64PublicKey); -BraveTorClientUpdater::BraveTorClientUpdater() - : task_runner_( +BraveTorClientUpdater::BraveTorClientUpdater(BraveComponent::Delegate* delegate) + : BraveComponent(delegate), + task_runner_( base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})), registered_(false) { } @@ -30,9 +72,9 @@ void BraveTorClientUpdater::Register() { if (registered_) return; - BraveComponentExtension::Register(kTorClientComponentName, - g_tor_client_component_id_, - g_tor_client_component_base64_public_key_); + BraveComponent::Register(kTorClientComponentName, + g_tor_client_component_id_, + g_tor_client_component_base64_public_key_); registered_ = true; } @@ -71,7 +113,7 @@ void BraveTorClientUpdater::InitExecutablePath( << executable_path.value().c_str(); return; } -#endif // defined(OS_POSIX) +#endif // defined(OS_POSIX) executable_path_ = executable_path; } @@ -96,8 +138,9 @@ void BraveTorClientUpdater::SetComponentIdAndBase64PublicKeyForTest( /////////////////////////////////////////////////////////////////////////////// // The Brave Tor client extension factory. -std::unique_ptr BraveTorClientUpdaterFactory() { - return std::make_unique(); +std::unique_ptr +BraveTorClientUpdaterFactory(BraveComponent::Delegate* delegate) { + return std::make_unique(delegate); } } // namespace extensions diff --git a/browser/extensions/brave_tor_client_updater.h b/browser/extensions/brave_tor_client_updater.h index 0ddfabc3757f..63b853aa88b1 100644 --- a/browser/extensions/brave_tor_client_updater.h +++ b/browser/extensions/brave_tor_client_updater.h @@ -1,57 +1,42 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef BRAVE_BROWSER_EXTENSIONS_BRAVE_TOR_CLIENT_UPDATER_H_ #define BRAVE_BROWSER_EXTENSIONS_BRAVE_TOR_CLIENT_UPDATER_H_ +#include +#include + #include "base/files/file_path.h" #include "base/sequenced_task_runner.h" -#include "brave/browser/extensions/brave_component_extension.h" +#include "brave/components/brave_component_updater/browser/brave_component.h" class BraveTorClientUpdaterTest; +using brave_component_updater::BraveComponent; + +// TODO(bridiver) - this doesn't belong under extensions namespace extensions { #if defined(OS_WIN) -const std::string kTorClientComponentName("Brave Tor Client Updater (Windows)"); -const std::string kTorClientComponentId("cpoalefficncklhjfpglfiplenlpccdb"); -const std::string kTorClientComponentBase64PublicKey = - "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1AYAsmR/VoRwkZCsjRpD" - "58xjrgngW5y17H6BqQ7/CeNSpmXlcMXy6bJs2D/yeS96rhZSrQSHTzS9h/ieo/NZ" - "F5PIwcv07YsG5sRd6zF5a6m92aWCQa1OkbL6jpcpL2Tbc4mCqNxhKMErT7EtIIWL" - "9cW+mtFUjUjvV3rJLQ3Vy9u6fEi77Y8b25kGnTJoVt3uETAIHBnyNpL7ac2f8Iq+" - "4Qa6VFmuoBhup54tTZvMv+ikoKKaQkHzkkjTa4hV5AzdnFDKO8C9qJb3T/Ef0+MO" - "IuZjyySVzGNcOfASeHkhxhlwMQSQuhCN5mdFW5YBnVZ/5QWx8WzbhqBny/ZynS4e" - "rQIDAQAB"; +extern const char kTorClientComponentName[]; +extern const char kTorClientComponentId[]; #elif defined(OS_MACOSX) -const std::string kTorClientComponentName("Brave Tor Client Updater (Mac)"); -const std::string kTorClientComponentId("cldoidikboihgcjfkhdeidbpclkineef"); -const std::string kTorClientComponentBase64PublicKey = - "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw2QUXSbVuRxYpItYApZ8" - "Ly/fGeUD3A+vb3J7Ot62CF32wTfWweANWyyB+EBGfbtNDAuRlAbNk0QYeCQEttuf" - "jLh3Kd5KR5fSyyNNd2cAzAckQ8p7JdiFYjvqZLGC5vlnHgqq4O8xACX5EPwHLNFD" - "iSpsthNmz3GCUrHrzPHjHVfy+IuucQXygnRv2fwIaAIxJmTbYm4fqsGKpfolWdMe" - "jKVAy1hc9mApZSyt4oGvUu4SJZnxlYMrY4Ze+OWbDesi2JGy+6dA1ddL9IdnwCb3" - "9CBOMNjaHeCVz0MKxdCWGPieQM0R7S1KvDCVqAkss6NAbLB6AVM0JulqxC9b+hr/" - "xwIDAQAB"; +extern const char kTorClientComponentName[]; +extern const char kTorClientComponentId[]; +extern const char kTorClientComponentBase64PublicKey[]; #elif defined(OS_LINUX) -const std::string kTorClientComponentName("Brave Tor Client Updater (Linux)"); -const std::string kTorClientComponentId("biahpgbdmdkfgndcmfiipgcebobojjkp"); -const std::string kTorClientComponentBase64PublicKey = - "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAseuq8dXKawkZC7RSE7xb" - "lRwh6DD+oPEGEjZWKh596/42IrWNQw60gRIR6s7x0YHh5geFnBRkx9bisEXOrFkq" - "oArVY7eD0gMkjpor9CneD5CnCxc9/2uIPajtXfAmmLAHtN6Wk7yW30SkRf/WvLWX" - "/H+PqskQBN7I5MO7sveYxSrRMSj7prrFHEiFmXTgG/DwjpzrA7KV6vmzz/ReD51o" - "+UuLHE7cxPhnsNd/52uY3Lod3GhxvDoXKYx9kWlzBjxB53A2eLBCDIwwCpqS4/Ib" - "RSJhvF33KQT8YM+7V1MitwB49klP4aEWPXwOlFHmn9Dkmlx2RbO7S0tRcH9UH4LK" - "2QIDAQAB"; +extern const char kTorClientComponentName[]; +extern const char kTorClientComponentId[]; +extern const char kTorClientComponentBase64PublicKey[]; #endif -class BraveTorClientUpdater : public BraveComponentExtension { +class BraveTorClientUpdater : public BraveComponent { public: - BraveTorClientUpdater(); - ~BraveTorClientUpdater() override; + explicit BraveTorClientUpdater(BraveComponent::Delegate* delegate); + ~BraveTorClientUpdater() override; void Register(); base::FilePath GetExecutablePath() const; @@ -81,7 +66,8 @@ class BraveTorClientUpdater : public BraveComponentExtension { }; // Creates the BraveTorClientUpdater -std::unique_ptr BraveTorClientUpdaterFactory(); +std::unique_ptr +BraveTorClientUpdaterFactory(BraveComponent::Delegate* delegate); } // namespace extensions diff --git a/browser/net/brave_ad_block_tp_network_delegate_helper.cc b/browser/net/brave_ad_block_tp_network_delegate_helper.cc index d126cbece4f5..05345558c0f3 100644 --- a/browser/net/brave_ad_block_tp_network_delegate_helper.cc +++ b/browser/net/brave_ad_block_tp_network_delegate_helper.cc @@ -85,8 +85,9 @@ bool GetPolyfillForAdBlock(bool allow_brave_shields, bool allow_ads, return false; } -void OnBeforeURLRequestAdBlockTPOnTaskRunner( +void OnBeforeURLRequestAdBlockTP( std::shared_ptr ctx) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // If the following info isn't available, then proper content settings can't // be looked up, so do nothing. if (ctx->tab_origin.is_empty() || !ctx->tab_origin.has_host() || @@ -120,12 +121,7 @@ void OnBeforeURLRequestAdBlockTPOnTaskRunner( &ctx->cancel_request_explicitly)) { ctx->blocked_by = kTrackerBlocked; } -} -void OnBeforeURLRequestDispatchOnIOThread( - const ResponseCallback& next_callback, - std::shared_ptr ctx) { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (ctx->blocked_by == kAdBlocked) { brave_shields::DispatchBlockedEventFromIO(ctx->request_url, ctx->render_frame_id, ctx->render_process_id, ctx->frame_tree_node_id, @@ -135,8 +131,6 @@ void OnBeforeURLRequestDispatchOnIOThread( ctx->render_frame_id, ctx->render_process_id, ctx->frame_tree_node_id, brave_shields::kTrackers); } - - next_callback.Run(); } int OnBeforeURLRequest_AdBlockTPPreWork( @@ -169,13 +163,9 @@ int OnBeforeURLRequest_AdBlockTPPreWork( return net::OK; } - g_brave_browser_process->ad_block_service()-> - GetTaskRunner()->PostTaskAndReply(FROM_HERE, - base::Bind(&OnBeforeURLRequestAdBlockTPOnTaskRunner, ctx), - base::Bind(base::IgnoreResult( - &OnBeforeURLRequestDispatchOnIOThread), next_callback, ctx)); + OnBeforeURLRequestAdBlockTP(ctx); - return net::ERR_IO_PENDING; + return net::OK; } } // namespace brave diff --git a/browser/net/brave_httpse_network_delegate_helper.cc b/browser/net/brave_httpse_network_delegate_helper.cc index 0babeaf48233..7d27b090207b 100644 --- a/browser/net/brave_httpse_network_delegate_helper.cc +++ b/browser/net/brave_httpse_network_delegate_helper.cc @@ -27,7 +27,7 @@ void OnBeforeURLRequest_HttpseFileWork( base::BlockingType::WILL_BLOCK); DCHECK_NE(ctx->request_identifier, 0U); g_brave_browser_process->https_everywhere_service()-> - GetHTTPSURL(&ctx->request_url, ctx->request_identifier, ctx->new_url_spec); + GetHTTPSURL(&ctx->request_url, ctx->request_identifier, &ctx->new_url_spec); } void OnBeforeURLRequest_HttpsePostFileWork( @@ -72,8 +72,9 @@ int OnBeforeURLRequest_HttpsePreFileWork( if (is_valid_url) { if (!g_brave_browser_process->https_everywhere_service()-> - GetHTTPSURLFromCacheOnly(&ctx->request_url, ctx->request_identifier, - ctx->new_url_spec)) { + GetHTTPSURLFromCacheOnly(&ctx->request_url, + ctx->request_identifier, + &ctx->new_url_spec)) { g_brave_browser_process->https_everywhere_service()-> GetTaskRunner()->PostTaskAndReply(FROM_HERE, base::Bind(OnBeforeURLRequest_HttpseFileWork, ctx), diff --git a/chromium_src/chrome/browser/browser_process_impl.cc b/chromium_src/chrome/browser/browser_process_impl.cc deleted file mode 100644 index bae639d802fd..000000000000 --- a/chromium_src/chrome/browser/browser_process_impl.cc +++ /dev/null @@ -1,9 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_shields/browser/brave_resource_dispatcher_host_delegate.h" - -#define ChromeResourceDispatcherHostDelegate BraveResourceDispatcherHostDelegate -#include "../../../../chrome/browser/browser_process_impl.cc" -#undef ChromeResourceDispatcherHostDelegate diff --git a/chromium_src/chrome/browser/component_updater/crl_set_component_installer.cc b/chromium_src/chrome/browser/component_updater/crl_set_component_installer.cc index 33f235d8683e..868e66846c2f 100644 --- a/chromium_src/chrome/browser/component_updater/crl_set_component_installer.cc +++ b/chromium_src/chrome/browser/component_updater/crl_set_component_installer.cc @@ -10,8 +10,8 @@ #include "chrome/browser/browser_process.h" #if !defined(OS_ANDROID) -#include "brave/browser/extensions/brave_component_extension.h" #include "brave/common/extensions/extension_constants.h" +#include "chrome/browser/ui/webui/components_ui.h" #endif namespace component_updater { @@ -19,9 +19,7 @@ namespace component_updater { void OnCRLSetRegistered() { // https://github.com/brave/browser-android-tabs/issues/857 #if !defined(OS_ANDROID) - ComponentsUI demand_updater; - demand_updater.OnDemandUpdate(g_browser_process->component_updater(), - crl_set_extension_id); + ComponentsUI::OnDemandUpdate(crl_set_extension_id); #endif } diff --git a/chromium_src/chrome/browser/component_updater/widevine_cdm_component_installer.cc b/chromium_src/chrome/browser/component_updater/widevine_cdm_component_installer.cc index ebecea6f4610..aa66fd39d5b9 100644 --- a/chromium_src/chrome/browser/component_updater/widevine_cdm_component_installer.cc +++ b/chromium_src/chrome/browser/component_updater/widevine_cdm_component_installer.cc @@ -1,15 +1,16 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #define RegisterWidevineCdmComponent RegisterWidevineCdmComponent_ChromiumImpl -#include "../../../../../chrome/browser/component_updater/widevine_cdm_component_installer.cc" +#include "../../../../../chrome/browser/component_updater/widevine_cdm_component_installer.cc" // NOLINT #undef RegisterWidevineCdmComponent #include "brave/browser/brave_browser_process_impl.h" -#include "brave/browser/extensions/brave_component_extension.h" #include "brave/common/pref_names.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/webui/components_ui.h" #include "brave/common/extensions/extension_constants.h" #include "components/component_updater/component_updater_service.h" #include "components/prefs/pref_service.h" @@ -21,11 +22,7 @@ namespace component_updater { void OnWidevineRegistered() { - ComponentsUI demand_updater; - // This weird looking call is ok, it is just like this to not need - // to patch for friend access. - demand_updater.OnDemandUpdate(g_browser_process->component_updater(), - widevine_extension_id); + ComponentsUI::OnDemandUpdate(widevine_extension_id); } void RegisterAndInstallWidevine() { diff --git a/components/brave_component_updater/browser/BUILD.gn b/components/brave_component_updater/browser/BUILD.gn new file mode 100644 index 000000000000..74bc19821188 --- /dev/null +++ b/components/brave_component_updater/browser/BUILD.gn @@ -0,0 +1,16 @@ +source_set("browser") { + sources = [ + "brave_component.cc", + "brave_component.h", + "dat_file_util.cc", + "dat_file_util.h", + "local_data_files_service.cc", + "local_data_files_service.h", + "local_data_files_observer.cc", + "local_data_files_observer.h", + ] + + deps = [ + "//base", + ] +} diff --git a/components/brave_component_updater/browser/brave_component.cc b/components/brave_component_updater/browser/brave_component.cc new file mode 100644 index 000000000000..558fcc4ee82f --- /dev/null +++ b/components/brave_component_updater/browser/brave_component.cc @@ -0,0 +1,64 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/components/brave_component_updater/browser/brave_component.h" + +#include + +#include "base/bind.h" +#include "base/sequenced_task_runner.h" + +namespace brave_component_updater { + +BraveComponent::BraveComponent(Delegate* delegate) + : delegate_(delegate), + weak_factory_(this) {} + +BraveComponent::~BraveComponent() { +} + +void BraveComponent::Register(const std::string& component_name, + const std::string& component_id, + const std::string& component_base64_public_key) { + component_name_ = component_name; + component_id_ = component_id; + component_base64_public_key_ = component_base64_public_key; + + auto registered_callback = + base::BindOnce(&BraveComponent::OnComponentRegistered, + delegate_, + component_id); + auto ready_callback = + base::BindOnce(&BraveComponent::OnComponentReady, + weak_factory_.GetWeakPtr(), + component_id); + + delegate_->Register(component_name_, + component_base64_public_key_, + std::move(registered_callback), + std::move(ready_callback)); +} + +bool BraveComponent::Unregister() { + return delegate_->Unregister(component_id_); +} + +scoped_refptr BraveComponent::GetTaskRunner() { + return delegate_->GetTaskRunner(); +} + +void BraveComponent::OnComponentReady( + const std::string& component_id, + const base::FilePath& install_dir, + const std::string& manifest) {} + +// static +void BraveComponent::OnComponentRegistered( + Delegate* delegate, + const std::string& component_id) { + delegate->OnDemandUpdate(component_id); +} + +} // namespace brave_component_updater diff --git a/components/brave_component_updater/browser/brave_component.h b/components/brave_component_updater/browser/brave_component.h new file mode 100644 index 000000000000..99b593ac58f8 --- /dev/null +++ b/components/brave_component_updater/browser/brave_component.h @@ -0,0 +1,63 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_BRAVE_COMPONENT_H_ +#define BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_BRAVE_COMPONENT_H_ + +#include + +#include "base/callback.h" +#include "base/files/file_path.h" +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "base/sequenced_task_runner.h" + +namespace brave_component_updater { + +class BraveComponent { + public: + using ReadyCallback = base::OnceCallback; + class Delegate { + public: + virtual ~Delegate() = default; + virtual void Register(const std::string& component_name, + const std::string& component_base64_public_key, + base::OnceClosure registered_callback, + ReadyCallback ready_callback) = 0; + virtual bool Unregister(const std::string& component_id) = 0; + virtual void OnDemandUpdate(const std::string& component_id) = 0; + virtual scoped_refptr GetTaskRunner() = 0; + }; + + explicit BraveComponent(Delegate* delegate); + virtual ~BraveComponent(); + void Register(const std::string& component_name, + const std::string& component_id, + const std::string& component_base64_public_key); + bool Unregister(); + scoped_refptr GetTaskRunner(); + + protected: + virtual void OnComponentReady(const std::string& component_id, + const base::FilePath& install_dir, + const std::string& manifest); + + private: + static void OnComponentRegistered(Delegate* delegate, + const std::string& component_id); + + std::string component_name_; + std::string component_id_; + std::string component_base64_public_key_; + Delegate* delegate_; // NOT OWNED + base::WeakPtrFactory weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(BraveComponent); +}; + +} // namespace brave_component_updater + +#endif // BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_BRAVE_COMPONENT_H_ diff --git a/components/brave_shields/browser/dat_file_util.cc b/components/brave_component_updater/browser/dat_file_util.cc similarity index 73% rename from components/brave_shields/browser/dat_file_util.cc rename to components/brave_component_updater/browser/dat_file_util.cc index 40d1fa009fa7..ea142ea3212b 100644 --- a/components/brave_shields/browser/dat_file_util.cc +++ b/components/brave_component_updater/browser/dat_file_util.cc @@ -3,14 +3,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "brave/components/brave_shields/browser/dat_file_util.h" +#include "brave/components/brave_component_updater/browser/dat_file_util.h" #include +#include "base/logging.h" #include "base/files/file_path.h" #include "base/files/file_util.h" -namespace brave_shields { +namespace brave_component_updater { void GetDATFileData(const base::FilePath& file_path, DATFileDataBuffer* buffer) { @@ -33,13 +34,14 @@ void GetDATFileData(const base::FilePath& file_path, } } -void GetDATFileAsString(const base::FilePath& file_path, - std::string* contents) { - bool success = base::ReadFileToString(file_path, contents); - if (!success || contents->empty()) { +std::string GetDATFileAsString(const base::FilePath& file_path) { + std::string contents; + bool success = base::ReadFileToString(file_path, &contents); + if (!success || contents.empty()) { LOG(ERROR) << "GetDATFileAsString: cannot " << "read dat file " << file_path; } + return contents; } -} // namespace brave_shields +} // namespace brave_component_updater diff --git a/components/brave_component_updater/browser/dat_file_util.h b/components/brave_component_updater/browser/dat_file_util.h new file mode 100644 index 000000000000..2163516d4422 --- /dev/null +++ b/components/brave_component_updater/browser/dat_file_util.h @@ -0,0 +1,46 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_DAT_FILE_UTIL_H_ +#define BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_DAT_FILE_UTIL_H_ + +#include +#include +#include +#include + +#include "base/files/file_path.h" + +namespace brave_component_updater { + +using DATFileDataBuffer = std::vector; + +void GetDATFileData(const base::FilePath& file_path, + DATFileDataBuffer* buffer); +std::string GetDATFileAsString(const base::FilePath& file_path); + +template +using LoadDATFileDataResult = + std::pair, brave_component_updater::DATFileDataBuffer>; + +template +LoadDATFileDataResult LoadDATFileData( + const base::FilePath& dat_file_path) { + DATFileDataBuffer buffer; + GetDATFileData(dat_file_path, &buffer); + std::unique_ptr client; + client = std::make_unique(); + if (buffer.empty() || + !client->deserialize(reinterpret_cast(&buffer.front()))) + client.reset(); + + return LoadDATFileDataResult( + std::move(client), std::move(buffer)); +} + + +} // namespace brave_component_updater + +#endif // BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_DAT_FILE_UTIL_H_ diff --git a/components/brave_component_updater/browser/local_data_files_observer.cc b/components/brave_component_updater/browser/local_data_files_observer.cc new file mode 100644 index 000000000000..1aaeeaaa3f49 --- /dev/null +++ b/components/brave_component_updater/browser/local_data_files_observer.cc @@ -0,0 +1,31 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/components/brave_component_updater/browser/local_data_files_observer.h" + +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" + +namespace brave_component_updater { + +LocalDataFilesObserver::LocalDataFilesObserver( + LocalDataFilesService* local_data_files_service) + : local_data_files_service_(local_data_files_service), + local_data_files_observer_(this) { + local_data_files_observer_.Add(local_data_files_service); +} + +LocalDataFilesObserver::~LocalDataFilesObserver() {} + +void LocalDataFilesObserver::OnLocalDataFilesServiceDestroyed() { + local_data_files_observer_.RemoveAll(); + local_data_files_service_ = nullptr; +} + +LocalDataFilesService* LocalDataFilesObserver::local_data_files_service() { + return local_data_files_service_; +} + +} // namespace brave_component_updater + diff --git a/components/brave_component_updater/browser/local_data_files_observer.h b/components/brave_component_updater/browser/local_data_files_observer.h new file mode 100644 index 000000000000..d574f0f318a7 --- /dev/null +++ b/components/brave_component_updater/browser/local_data_files_observer.h @@ -0,0 +1,40 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_LOCAL_DATA_FILES_OBSERVER_H_ +#define BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_LOCAL_DATA_FILES_OBSERVER_H_ + +#include + +#include "base/files/file_path.h" +#include "base/scoped_observer.h" + +namespace brave_component_updater { + +class LocalDataFilesService; + +// The abstract base class for observers of the local data files service, +// which is the component that arbitrates access to various DAT files +// like tracking protection, video autoplay whitelist, etc. +class LocalDataFilesObserver { + public: + explicit LocalDataFilesObserver( + LocalDataFilesService* local_data_files_service); + virtual ~LocalDataFilesObserver(); + virtual void OnComponentReady(const std::string& component_id, + const base::FilePath& install_dir, + const std::string& manifest) = 0; + virtual void OnLocalDataFilesServiceDestroyed(); + LocalDataFilesService* local_data_files_service(); + + protected: + LocalDataFilesService* local_data_files_service_; // NOT OWNED + ScopedObserver + local_data_files_observer_; +}; + +} // namespace brave_component_updater + +#endif // BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_LOCAL_DATA_FILES_OBSERVER_H_ diff --git a/components/brave_component_updater/browser/local_data_files_service.cc b/components/brave_component_updater/browser/local_data_files_service.cc new file mode 100644 index 000000000000..d1485828541f --- /dev/null +++ b/components/brave_component_updater/browser/local_data_files_service.cc @@ -0,0 +1,70 @@ +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" + +#include "brave/components/brave_component_updater/browser/local_data_files_observer.h" + +using brave_component_updater::BraveComponent; + +namespace brave_component_updater { + +std::string LocalDataFilesService::g_local_data_files_component_id_( + kLocalDataFilesComponentId); +std::string LocalDataFilesService:: +g_local_data_files_component_base64_public_key_( + kLocalDataFilesComponentBase64PublicKey); + +LocalDataFilesService::LocalDataFilesService(BraveComponent::Delegate* delegate) + : BraveComponent(delegate), + initialized_(false) {} + +LocalDataFilesService::~LocalDataFilesService() { + for (auto& observer : observers_) + observer.OnLocalDataFilesServiceDestroyed(); +} + +bool LocalDataFilesService::Start() { + if (initialized_) + return true; + Register(kLocalDataFilesComponentName, + g_local_data_files_component_id_, + g_local_data_files_component_base64_public_key_); + initialized_ = true; + return true; +} + +void LocalDataFilesService::OnComponentReady( + const std::string& component_id, + const base::FilePath& install_dir, + const std::string& manifest) { + for (auto& observer : observers_) + observer.OnComponentReady(component_id, install_dir, manifest); +} + +void LocalDataFilesService::AddObserver(LocalDataFilesObserver* observer) { + observers_.AddObserver(observer); +} + +void LocalDataFilesService::RemoveObserver(LocalDataFilesObserver* observer) { + observers_.RemoveObserver(observer); +} + +// static +void LocalDataFilesService::SetComponentIdAndBase64PublicKeyForTest( + const std::string& component_id, + const std::string& component_base64_public_key) { + g_local_data_files_component_id_ = component_id; + g_local_data_files_component_base64_public_key_ = component_base64_public_key; +} + +/////////////////////////////////////////////////////////////////////////////// + +std::unique_ptr +LocalDataFilesServiceFactory(BraveComponent::Delegate* delegate) { + return std::make_unique(delegate); +} + +} // namespace brave_component_updater diff --git a/components/brave_shields/browser/local_data_files_service.h b/components/brave_component_updater/browser/local_data_files_service.h similarity index 58% rename from components/brave_shields/browser/local_data_files_service.h rename to components/brave_component_updater/browser/local_data_files_service.h index 08982f6bc666..45595ce10a6a 100644 --- a/components/brave_shields/browser/local_data_files_service.h +++ b/components/brave_component_updater/browser/local_data_files_service.h @@ -3,30 +3,19 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_LOCAL_DATA_FILES_SERVICE_H_ -#define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_LOCAL_DATA_FILES_SERVICE_H_ +#ifndef BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_LOCAL_DATA_FILES_SERVICE_H_ +#define BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_LOCAL_DATA_FILES_SERVICE_H_ -#include - -#include #include #include -#include #include "base/files/file_path.h" -#include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" -#include "brave/browser/extensions/brave_component_extension.h" -#include "content/public/common/resource_type.h" - -class AdBlockServiceTest; -class AutoplayWhitelistServiceTest; -class ReferrerWhitelistServiceTest; -class TrackingProtectionServiceTest; +#include "base/observer_list.h" +#include "brave/components/brave_component_updater/browser/brave_component.h" -namespace brave_shields { +namespace brave_component_updater { -class BaseLocalDataFilesObserver; +class LocalDataFilesObserver; const char kLocalDataFilesComponentName[] = "Brave Local Data Updater"; const char kLocalDataFilesComponentId[] = "afalakplffnnnlkncjhbmahjfjhmlkal"; @@ -41,13 +30,18 @@ const char kLocalDataFilesComponentBase64PublicKey[] = // The component in charge of delegating access to different DAT files // such as tracking protection and video autoplay whitelist -class LocalDataFilesService : public BraveComponentExtension { +class LocalDataFilesService : public BraveComponent { public: - LocalDataFilesService(); + explicit LocalDataFilesService(BraveComponent::Delegate* delegate); ~LocalDataFilesService() override; bool Start(); bool IsInitialized() const { return initialized_; } - void AddObserver(BaseLocalDataFilesObserver* observer); + void AddObserver(LocalDataFilesObserver* observer); + void RemoveObserver(LocalDataFilesObserver* observer); + + static void SetComponentIdAndBase64PublicKeyForTest( + const std::string& component_id, + const std::string& component_base64_public_key); protected: void OnComponentReady(const std::string& component_id, @@ -55,28 +49,19 @@ class LocalDataFilesService : public BraveComponentExtension { const std::string& manifest) override; private: - friend class ::AdBlockServiceTest; - friend class ::AutoplayWhitelistServiceTest; - friend class ::ReferrerWhitelistServiceTest; - friend class ::TrackingProtectionServiceTest; static std::string g_local_data_files_component_id_; static std::string g_local_data_files_component_base64_public_key_; - static void SetComponentIdAndBase64PublicKeyForTest( - const std::string& component_id, - const std::string& component_base64_public_key); - std::vector observers_; - - SEQUENCE_CHECKER(sequence_checker_); bool initialized_; - bool observers_already_called_; - base::WeakPtrFactory weak_factory_; + base::ObserverList::Unchecked observers_; + DISALLOW_COPY_AND_ASSIGN(LocalDataFilesService); }; // Creates the LocalDataFilesService -std::unique_ptr LocalDataFilesServiceFactory(); +std::unique_ptr +LocalDataFilesServiceFactory(BraveComponent::Delegate* delegate); -} // namespace brave_shields +} // namespace brave_component_updater -#endif // BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_LOCAL_DATA_FILES_SERVICE_H_ +#endif // BRAVE_COMPONENTS_BRAVE_COMPONENT_UPDATER_BROWSER_LOCAL_DATA_FILES_SERVICE_H_ diff --git a/components/brave_shields/browser/BUILD.gn b/components/brave_shields/browser/BUILD.gn index 9167db9b0588..6bea35fda1bc 100644 --- a/components/brave_shields/browser/BUILD.gn +++ b/components/brave_shields/browser/BUILD.gn @@ -25,21 +25,13 @@ source_set("brave_shields") { "autoplay_whitelist_service.h", "base_brave_shields_service.cc", "base_brave_shields_service.h", - "base_local_data_files_observer.cc", - "base_local_data_files_observer.h", "brave_shields_util.cc", "brave_shields_util.h", "brave_shields_web_contents_observer.cc", "brave_shields_web_contents_observer.h", - "brave_resource_dispatcher_host_delegate.cc", - "brave_resource_dispatcher_host_delegate.h", - "dat_file_util.cc", - "dat_file_util.h", "https_everywhere_recently_used_cache.h", "https_everywhere_service.cc", "https_everywhere_service.h", - "local_data_files_service.cc", - "local_data_files_service.h", "referrer_whitelist_service.cc", "referrer_whitelist_service.h", "tracking_protection_service.cc", @@ -54,11 +46,15 @@ source_set("brave_shields") { } deps = [ + "//brave/components/brave_component_updater/browser", "//brave/content:common", "//brave/vendor/ad-block/brave:ad-block", "//brave/vendor/tracking-protection/brave:tracking-protection", "//brave/vendor/autoplay-whitelist/brave:autoplay-whitelist", "//chrome/common", + "//components/prefs", + "//content/public/browser", + "//net", "//third_party/leveldatabase", ] diff --git a/components/brave_shields/browser/ad_block_base_service.cc b/components/brave_shields/browser/ad_block_base_service.cc index 5a6c82bdeeb7..a331a6345cb3 100644 --- a/components/brave_shields/browser/ad_block_base_service.cc +++ b/components/brave_shields/browser/ad_block_base_service.cc @@ -12,22 +12,23 @@ #include "base/bind.h" #include "base/files/file_path.h" -#include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" -#include "base/threading/thread_restrictions.h" -#include "brave/browser/brave_browser_process_impl.h" +#include "base/task/post_task.h" #include "brave/browser/net/url_context.h" #include "brave/common/pref_names.h" -#include "brave/components/brave_shields/browser/dat_file_util.h" +#include "brave/components/brave_component_updater/browser/dat_file_util.h" #include "brave/components/brave_shields/common/brave_shield_constants.h" #include "brave/vendor/ad-block/ad_block_client.h" -#include "chrome/browser/profiles/profile_manager.h" #include "components/prefs/pref_service.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "url/origin.h" +using brave_component_updater::BraveComponent; +using content::BrowserThread; using namespace net::registry_controlled_domains; // NOLINT namespace { @@ -106,10 +107,11 @@ FilterOption ResourceTypeToFilterOption(content::ResourceType resource_type) { namespace brave_shields { -AdBlockBaseService::AdBlockBaseService() - : BaseBraveShieldsService(), +AdBlockBaseService::AdBlockBaseService(BraveComponent::Delegate* delegate) + : BaseBraveShieldsService(delegate), ad_block_client_(new AdBlockClient()), - weak_factory_(this) { + weak_factory_(this), + weak_factory_io_thread_(this) { DETACH_FROM_SEQUENCE(sequence_checker_); } @@ -118,13 +120,14 @@ AdBlockBaseService::~AdBlockBaseService() { } void AdBlockBaseService::Cleanup() { - ad_block_client_.reset(); + BrowserThread::DeleteSoon( + BrowserThread::IO, FROM_HERE, ad_block_client_.release()); } bool AdBlockBaseService::ShouldStartRequest(const GURL& url, content::ResourceType resource_type, const std::string& tab_host, bool* did_match_exception, bool* cancel_request_explicitly) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK_CURRENTLY_ON(BrowserThread::IO); FilterOption current_option = ResourceTypeToFilterOption(resource_type); // Determine third-party here so the library doesn't need to figure it out. @@ -164,15 +167,17 @@ bool AdBlockBaseService::ShouldStartRequest(const GURL& url, } void AdBlockBaseService::EnableTag(const std::string& tag, bool enabled) { - GetTaskRunner()->PostTask( - FROM_HERE, - base::BindOnce(&AdBlockBaseService::EnableTagOnFileTaskRunner, - base::Unretained(this), tag, enabled)); + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&AdBlockBaseService::EnableTagOnIOThread, + weak_factory_io_thread_.GetWeakPtr(), + tag, + enabled)); } -void AdBlockBaseService::EnableTagOnFileTaskRunner( - std::string tag, bool enabled) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); +void AdBlockBaseService::EnableTagOnIOThread( + const std::string& tag, bool enabled) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (enabled) { ad_block_client_->addTag(tag); } else { @@ -181,26 +186,43 @@ void AdBlockBaseService::EnableTagOnFileTaskRunner( } void AdBlockBaseService::GetDATFileData(const base::FilePath& dat_file_path) { - GetTaskRunner()->PostTaskAndReply( + base::PostTaskAndReplyWithResult( + GetTaskRunner().get(), FROM_HERE, - base::Bind(&brave_shields::GetDATFileData, dat_file_path, &buffer_), - base::Bind(&AdBlockBaseService::OnDATFileDataReady, - weak_factory_.GetWeakPtr())); + base::BindOnce( + &brave_component_updater::LoadDATFileData, + dat_file_path), + base::BindOnce(&AdBlockBaseService::OnGetDATFileData, + weak_factory_.GetWeakPtr())); } -void AdBlockBaseService::OnDATFileDataReady() { - if (buffer_.empty()) { +void AdBlockBaseService::OnGetDATFileData(GetDATFileDataResult result) { + if (result.second.empty()) { LOG(ERROR) << "Could not obtain ad block data"; return; } - if (!ad_block_client_->deserialize( - reinterpret_cast(&buffer_.front()))) { - ad_block_client_.reset(new AdBlockClient()); + if (!result.first.get()) { LOG(ERROR) << "Failed to deserialize ad block data"; return; } + + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&AdBlockBaseService::UpdateAdBlockClient, + weak_factory_io_thread_.GetWeakPtr(), + std::move(result.first), + std::move(result.second))); } +void AdBlockBaseService::UpdateAdBlockClient( + std::unique_ptr ad_block_client, + brave_component_updater::DATFileDataBuffer buffer) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + ad_block_client_ = std::move(ad_block_client); + buffer_ = std::move(buffer); +} + + bool AdBlockBaseService::Init() { return true; } diff --git a/components/brave_shields/browser/ad_block_base_service.h b/components/brave_shields/browser/ad_block_base_service.h index 0e8980075220..f12b71ff8f8d 100644 --- a/components/brave_shields/browser/ad_block_base_service.h +++ b/components/brave_shields/browser/ad_block_base_service.h @@ -10,25 +10,31 @@ #include #include +#include #include #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" #include "brave/components/brave_shields/browser/base_brave_shields_service.h" -#include "brave/components/brave_shields/browser/dat_file_util.h" +#include "brave/components/brave_component_updater/browser/dat_file_util.h" #include "content/public/common/resource_type.h" class AdBlockClient; class AdBlockServiceTest; +using brave_component_updater::BraveComponent; + namespace brave_shields { // The base class of the brave shields service in charge of ad-block // checking and init. class AdBlockBaseService : public BaseBraveShieldsService { public: - AdBlockBaseService(); + using GetDATFileDataResult = + brave_component_updater::LoadDATFileDataResult; + + explicit AdBlockBaseService(BraveComponent::Delegate* delegate); ~AdBlockBaseService() override; bool ShouldStartRequest(const GURL &url, content::ResourceType resource_type, @@ -41,19 +47,24 @@ class AdBlockBaseService : public BaseBraveShieldsService { bool Init() override; void Cleanup() override; - void EnableTagOnFileTaskRunner(std::string tag, bool enabled); void GetDATFileData(const base::FilePath& dat_file_path); + AdBlockClient* GetAdBlockClientForTest(); SEQUENCE_CHECKER(sequence_checker_); std::unique_ptr ad_block_client_; - DATFileDataBuffer buffer_; private: - void OnDATFileDataReady(); + void UpdateAdBlockClient( + std::unique_ptr ad_block_client, + brave_component_updater::DATFileDataBuffer buffer); + void OnGetDATFileData(GetDATFileDataResult result); + void EnableTagOnIOThread(const std::string& tag, bool enabled); void OnPreferenceChanges(const std::string& pref_name); + brave_component_updater::DATFileDataBuffer buffer_; base::WeakPtrFactory weak_factory_; + base::WeakPtrFactory weak_factory_io_thread_; DISALLOW_COPY_AND_ASSIGN(AdBlockBaseService); }; diff --git a/components/brave_shields/browser/ad_block_custom_filters_service.cc b/components/brave_shields/browser/ad_block_custom_filters_service.cc index 9540ae207f77..f75c65e849ab 100644 --- a/components/brave_shields/browser/ad_block_custom_filters_service.cc +++ b/components/brave_shields/browser/ad_block_custom_filters_service.cc @@ -13,9 +13,12 @@ #include "components/prefs/pref_service.h" #include "content/public/browser/browser_thread.h" +using brave_component_updater::BraveComponent; + namespace brave_shields { -AdBlockCustomFiltersService::AdBlockCustomFiltersService() { +AdBlockCustomFiltersService::AdBlockCustomFiltersService( + BraveComponent::Delegate* delegate) : AdBlockBaseService(delegate) { } AdBlockCustomFiltersService::~AdBlockCustomFiltersService() { @@ -58,17 +61,11 @@ void AdBlockCustomFiltersService::UpdateCustomFiltersOnFileTaskRunner( ad_block_client_->parse(custom_filters.c_str()); } -scoped_refptr -AdBlockCustomFiltersService::GetTaskRunner() { - // We share the same task runner for all ad-block and TP code - return g_brave_browser_process->ad_block_service()->GetTaskRunner(); -} - /////////////////////////////////////////////////////////////////////////////// std::unique_ptr -AdBlockCustomFiltersServiceFactory() { - return std::make_unique(); +AdBlockCustomFiltersServiceFactory(BraveComponent::Delegate* delegate) { + return std::make_unique(delegate); } } // namespace brave_shields diff --git a/components/brave_shields/browser/ad_block_custom_filters_service.h b/components/brave_shields/browser/ad_block_custom_filters_service.h index 8e580f3e4e9a..721ddbc04cf9 100644 --- a/components/brave_shields/browser/ad_block_custom_filters_service.h +++ b/components/brave_shields/browser/ad_block_custom_filters_service.h @@ -13,18 +13,19 @@ class AdBlockServiceTest; +using brave_component_updater::BraveComponent; + namespace brave_shields { // The brave shields service in charge of custom filter ad-block // checking and init. class AdBlockCustomFiltersService : public AdBlockBaseService { public: - AdBlockCustomFiltersService(); + explicit AdBlockCustomFiltersService(BraveComponent::Delegate* delegate); ~AdBlockCustomFiltersService() override; std::string GetCustomFilters(); bool UpdateCustomFilters(const std::string& custom_filters); - scoped_refptr GetTaskRunner() override; protected: bool Init() override; @@ -38,7 +39,7 @@ class AdBlockCustomFiltersService : public AdBlockBaseService { // Creates the AdBlockCustomFiltersService std::unique_ptr -AdBlockCustomFiltersServiceFactory(); +AdBlockCustomFiltersServiceFactory(BraveComponent::Delegate* delegate); } // namespace brave_shields diff --git a/components/brave_shields/browser/ad_block_regional_service.cc b/components/brave_shields/browser/ad_block_regional_service.cc index f50f93447e8b..2efb696d7719 100644 --- a/components/brave_shields/browser/ad_block_regional_service.cc +++ b/components/brave_shields/browser/ad_block_regional_service.cc @@ -18,14 +18,12 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" -#include "brave/browser/brave_browser_process_impl.h" #include "brave/common/pref_names.h" #include "brave/components/brave_shields/browser/ad_block_service.h" #include "brave/components/brave_shields/browser/ad_block_service_helper.h" #include "brave/vendor/ad-block/ad_block_client.h" #include "brave/vendor/ad-block/data_file_version.h" #include "brave/vendor/ad-block/lists/regions.h" -#include "chrome/browser/profiles/profile_manager.h" #include "components/prefs/pref_service.h" namespace brave_shields { @@ -36,8 +34,11 @@ std::string std::string AdBlockRegionalService::g_ad_block_regional_dat_file_version_( base::NumberToString(DATA_FILE_VERSION)); -AdBlockRegionalService::AdBlockRegionalService(const std::string& uuid) - : uuid_(uuid) { +AdBlockRegionalService::AdBlockRegionalService( + const std::string& uuid, + brave_component_updater::BraveComponent::Delegate* delegate) + : AdBlockBaseService(delegate), + uuid_(uuid) { } AdBlockRegionalService::~AdBlockRegionalService() { @@ -70,7 +71,7 @@ void AdBlockRegionalService::OnComponentReady( install_dir.AppendASCII(g_ad_block_regional_dat_file_version_) .AppendASCII(uuid_) .AddExtension(FILE_PATH_LITERAL(".dat")); - AdBlockBaseService::GetDATFileData(dat_file_path); + GetDATFileData(dat_file_path); } // static @@ -88,17 +89,12 @@ void AdBlockRegionalService::SetDATFileVersionForTest( g_ad_block_regional_dat_file_version_ = dat_file_version; } -scoped_refptr -AdBlockRegionalService::GetTaskRunner() { - // We share the same task runner for all ad-block and TP code - return g_brave_browser_process->ad_block_service()->GetTaskRunner(); -} - /////////////////////////////////////////////////////////////////////////////// std::unique_ptr AdBlockRegionalServiceFactory( - const std::string& uuid) { - return std::make_unique(uuid); + const std::string& uuid, + brave_component_updater::BraveComponent::Delegate* delegate) { + return std::make_unique(uuid, delegate); } } // namespace brave_shields diff --git a/components/brave_shields/browser/ad_block_regional_service.h b/components/brave_shields/browser/ad_block_regional_service.h index 005fe7664339..a0e488ebe122 100644 --- a/components/brave_shields/browser/ad_block_regional_service.h +++ b/components/brave_shields/browser/ad_block_regional_service.h @@ -24,12 +24,13 @@ namespace brave_shields { // for a specific region. class AdBlockRegionalService : public AdBlockBaseService { public: - explicit AdBlockRegionalService(const std::string& uuid); + explicit AdBlockRegionalService( + const std::string& uuid, + brave_component_updater::BraveComponent::Delegate* delegate); ~AdBlockRegionalService() override; std::string GetUUID() const { return uuid_; } std::string GetTitle() const { return title_; } - scoped_refptr GetTaskRunner() override; protected: bool Init() override; @@ -55,7 +56,8 @@ class AdBlockRegionalService : public AdBlockBaseService { // Creates the AdBlockRegionalService std::unique_ptr AdBlockRegionalServiceFactory( - const std::string& uuid); + const std::string& uuid, + brave_component_updater::BraveComponent::Delegate* delegate); } // namespace brave_shields diff --git a/components/brave_shields/browser/ad_block_regional_service_manager.cc b/components/brave_shields/browser/ad_block_regional_service_manager.cc index dd0e80f5462e..2afe25b6a3a9 100644 --- a/components/brave_shields/browser/ad_block_regional_service_manager.cc +++ b/components/brave_shields/browser/ad_block_regional_service_manager.cc @@ -25,8 +25,10 @@ namespace brave_shields { -AdBlockRegionalServiceManager::AdBlockRegionalServiceManager() - : initialized_(false) { +AdBlockRegionalServiceManager::AdBlockRegionalServiceManager( + brave_component_updater::BraveComponent::Delegate* delegate) + : delegate_(delegate), + initialized_(false) { if (Init()) { initialized_ = true; } @@ -76,7 +78,7 @@ void AdBlockRegionalServiceManager::StartRegionalServices() { if (regional_filter_dict) regional_filter_dict->GetBoolean("enabled", &enabled); if (enabled) { - auto regional_service = AdBlockRegionalServiceFactory(uuid); + auto regional_service = AdBlockRegionalServiceFactory(uuid, delegate_); regional_service->Start(); regional_services_.insert( std::make_pair(uuid, std::move(regional_service))); @@ -157,14 +159,14 @@ void AdBlockRegionalServiceManager::EnableFilterList(const std::string& uuid, auto it = regional_services_.find(uuid); if (enabled) { DCHECK(it == regional_services_.end()); - auto regional_service = AdBlockRegionalServiceFactory(uuid); + auto regional_service = AdBlockRegionalServiceFactory(uuid, delegate_); regional_service->Start(); regional_services_.insert( std::make_pair(uuid, std::move(regional_service))); } else { DCHECK(it != regional_services_.end()); it->second->Stop(); - BraveComponentExtension::Unregister(uuid); + it->second->Unregister(); regional_services_.erase(it); } } @@ -177,12 +179,6 @@ void AdBlockRegionalServiceManager::EnableFilterList(const std::string& uuid, base::Unretained(this), uuid, enabled)); } -scoped_refptr -AdBlockRegionalServiceManager::GetTaskRunner() { - // We share the same task runner for all ad-block and TP code - return g_brave_browser_process->ad_block_service()->GetTaskRunner(); -} - // static bool AdBlockRegionalServiceManager::IsSupportedLocale( const std::string& locale) { @@ -230,8 +226,8 @@ AdBlockRegionalServiceManager::GetRegionalLists() { /////////////////////////////////////////////////////////////////////////////// std::unique_ptr -AdBlockRegionalServiceManagerFactory() { - return std::make_unique(); +AdBlockRegionalServiceManagerFactory(BraveComponent::Delegate* delegate) { + return std::make_unique(delegate); } } // namespace brave_shields diff --git a/components/brave_shields/browser/ad_block_regional_service_manager.h b/components/brave_shields/browser/ad_block_regional_service_manager.h index 4564612f28cb..7fe3107dc2df 100644 --- a/components/brave_shields/browser/ad_block_regional_service_manager.h +++ b/components/brave_shields/browser/ad_block_regional_service_manager.h @@ -13,6 +13,7 @@ #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "base/synchronization/lock.h" +#include "brave/components/brave_component_updater/browser/brave_component.h" #include "content/public/common/resource_type.h" #include "url/gurl.h" @@ -22,6 +23,8 @@ class ListValue; class AdBlockServiceTest; +using brave_component_updater::BraveComponent; + namespace brave_shields { class AdBlockRegionalService; @@ -30,7 +33,7 @@ class AdBlockRegionalService; // managing regional AdBlock clients. class AdBlockRegionalServiceManager { public: - AdBlockRegionalServiceManager(); + explicit AdBlockRegionalServiceManager(BraveComponent::Delegate* delegate); ~AdBlockRegionalServiceManager(); static bool IsSupportedLocale(const std::string& locale); @@ -46,7 +49,6 @@ class AdBlockRegionalServiceManager { bool* cancel_request_explicitly); void EnableTag(const std::string& tag, bool enabled); void EnableFilterList(const std::string& uuid, bool enabled); - scoped_refptr GetTaskRunner(); private: friend class ::AdBlockServiceTest; @@ -54,6 +56,7 @@ class AdBlockRegionalServiceManager { void StartRegionalServices(); void UpdateFilterListPrefs(const std::string& uuid, bool enabled); + brave_component_updater::BraveComponent::Delegate* delegate_; // NOT OWNED bool initialized_; base::Lock regional_services_lock_; std::map> @@ -64,7 +67,7 @@ class AdBlockRegionalServiceManager { // Creates the AdBlockRegionalServiceManager std::unique_ptr -AdBlockRegionalServiceManagerFactory(); +AdBlockRegionalServiceManagerFactory(BraveComponent::Delegate* delegate); } // namespace brave_shields diff --git a/components/brave_shields/browser/ad_block_service.cc b/components/brave_shields/browser/ad_block_service.cc index 179ec852e9d2..6ab950061e34 100644 --- a/components/brave_shields/browser/ad_block_service.cc +++ b/components/brave_shields/browser/ad_block_service.cc @@ -33,15 +33,20 @@ std::string AdBlockService::g_ad_block_component_base64_public_key_( std::string AdBlockService::g_ad_block_dat_file_version_( base::NumberToString(DATA_FILE_VERSION)); -AdBlockService::AdBlockService() { +AdBlockService::AdBlockService( + brave_component_updater::BraveComponent::Delegate* delegate) + : AdBlockBaseService(delegate) { } AdBlockService::~AdBlockService() { } bool AdBlockService::Init() { - AdBlockBaseService::Init(); - Register(kAdBlockComponentName, g_ad_block_component_id_, + if (!AdBlockBaseService::Init()) + return false; + + Register(kAdBlockComponentName, + g_ad_block_component_id_, g_ad_block_component_base64_public_key_); return true; } @@ -52,7 +57,7 @@ void AdBlockService::OnComponentReady(const std::string& component_id, base::FilePath dat_file_path = install_dir.AppendASCII(g_ad_block_dat_file_version_) .AppendASCII(DAT_FILE); - AdBlockBaseService::GetDATFileData(dat_file_path); + GetDATFileData(dat_file_path); } // static @@ -72,8 +77,9 @@ void AdBlockService::SetDATFileVersionForTest( /////////////////////////////////////////////////////////////////////////////// // The Adblock service factory. -std::unique_ptr AdBlockServiceFactory() { - return std::make_unique(); +std::unique_ptr AdBlockServiceFactory( + brave_component_updater::BraveComponent::Delegate* delegate) { + return std::make_unique(delegate); } void RegisterPrefsForAdBlockService(PrefRegistrySimple* registry) { diff --git a/components/brave_shields/browser/ad_block_service.h b/components/brave_shields/browser/ad_block_service.h index 193f315a20f9..9c8cfaac037b 100644 --- a/components/brave_shields/browser/ad_block_service.h +++ b/components/brave_shields/browser/ad_block_service.h @@ -13,10 +13,12 @@ #include #include "brave/components/brave_shields/browser/ad_block_base_service.h" -#include "content/public/common/resource_type.h" +#include "components/prefs/pref_registry_simple.h" class AdBlockServiceTest; +using brave_component_updater::BraveComponent; + namespace brave_shields { const char kAdBlockComponentName[] = "Brave Ad Block Updater"; @@ -33,7 +35,7 @@ const char kAdBlockComponentBase64PublicKey[] = // The brave shields service in charge of ad-block checking and init. class AdBlockService : public AdBlockBaseService { public: - AdBlockService(); + explicit AdBlockService(BraveComponent::Delegate* delegate); ~AdBlockService() override; protected: @@ -56,7 +58,8 @@ class AdBlockService : public AdBlockBaseService { }; // Creates the AdBlockService -std::unique_ptr AdBlockServiceFactory(); +std::unique_ptr AdBlockServiceFactory( + BraveComponent::Delegate* delegate); // Registers the local_state preferences used by Adblock void RegisterPrefsForAdBlockService(PrefRegistrySimple* registry); diff --git a/components/brave_shields/browser/ad_block_service_browsertest.cc b/components/brave_shields/browser/ad_block_service_browsertest.cc index 8f985925d791..a6ee092da570 100644 --- a/components/brave_shields/browser/ad_block_service_browsertest.cc +++ b/components/brave_shields/browser/ad_block_service_browsertest.cc @@ -4,6 +4,7 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "base/path_service.h" +#include "base/task/post_task.h" #include "base/test/thread_test_helper.h" #include "brave/browser/brave_browser_process_impl.h" #include "brave/common/brave_paths.h" @@ -12,7 +13,7 @@ #include "brave/components/brave_shields/browser/ad_block_regional_service.h" #include "brave/components/brave_shields/browser/ad_block_regional_service_manager.h" #include "brave/components/brave_shields/browser/ad_block_service.h" -#include "brave/components/brave_shields/browser/local_data_files_service.h" +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" #include "brave/components/brave_shields/browser/tracking_protection_service.h" #include "brave/components/brave_shields/common/brave_shield_constants.h" #include "brave/vendor/ad-block/ad_block_client.h" @@ -20,9 +21,12 @@ #include "chrome/browser/ui/browser.h" #include "chrome/test/base/ui_test_utils.h" #include "components/prefs/pref_service.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" #include "content/public/test/browser_test_utils.h" #include "net/dns/mock_host_resolver.h" +using content::BrowserThread; using extensions::ExtensionBrowserTest; const char kAdBlockTestPage[] = "/blocking.html"; @@ -78,7 +82,7 @@ class AdBlockServiceTest : public ExtensionBrowserTest { void PreRunTestOnMainThread() override { ExtensionBrowserTest::PreRunTestOnMainThread(); - WaitForDefaultAdBlockServiceThread(); + WaitForAdBlockServiceThreads(); ASSERT_TRUE(g_brave_browser_process->ad_block_service()->IsInitialized()); } @@ -125,7 +129,7 @@ class AdBlockServiceTest : public ExtensionBrowserTest { } void InitTrackingProtectionService() { - brave_shields::LocalDataFilesService:: + brave_component_updater::LocalDataFilesService:: SetComponentIdAndBase64PublicKeyForTest( kTrackingProtectionComponentTestId, kTrackingProtectionComponentTestBase64PublicKey); @@ -156,7 +160,7 @@ class AdBlockServiceTest : public ExtensionBrowserTest { g_brave_browser_process->ad_block_service()->OnComponentReady( ad_block_extension->id(), ad_block_extension->path(), ""); - WaitForDefaultAdBlockServiceThread(); + WaitForAdBlockServiceThreads(); return true; } @@ -183,7 +187,7 @@ class AdBlockServiceTest : public ExtensionBrowserTest { ->regional_services_.find(uuid); regional_service->second->OnComponentReady(ad_block_extension->id(), ad_block_extension->path(), ""); - WaitForRegionalAdBlockServiceThread(); + WaitForAdBlockServiceThreads(); return true; } @@ -200,7 +204,7 @@ class AdBlockServiceTest : public ExtensionBrowserTest { g_brave_browser_process->tracking_protection_service()->OnComponentReady( tracking_protection_extension->id(), tracking_protection_extension->path(), ""); - WaitForTrackingProtectionServiceThread(); + WaitForAdBlockServiceThreads(); return true; } @@ -213,29 +217,13 @@ class AdBlockServiceTest : public ExtensionBrowserTest { return true; } - void WaitForAllAdBlockServiceThreads() { - WaitForDefaultAdBlockServiceThread(); - WaitForRegionalAdBlockServiceThread(); - } - - void WaitForDefaultAdBlockServiceThread() { - scoped_refptr io_helper(new base::ThreadTestHelper( - g_brave_browser_process->ad_block_service()->GetTaskRunner())); - ASSERT_TRUE(io_helper->Run()); - } - - void WaitForRegionalAdBlockServiceThread() { + void WaitForAdBlockServiceThreads() { + scoped_refptr tr_helper(new base::ThreadTestHelper( + g_brave_browser_process->local_data_files_service()->GetTaskRunner())); + ASSERT_TRUE(tr_helper->Run()); scoped_refptr io_helper(new base::ThreadTestHelper( - g_brave_browser_process->ad_block_regional_service_manager() - ->GetTaskRunner())); - ASSERT_TRUE(io_helper->Run()); - } - - void WaitForTrackingProtectionServiceThread() { - scoped_refptr io_helper( - new base::ThreadTestHelper( - g_brave_browser_process->tracking_protection_service() - ->GetTaskRunner())); + base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}) + .get())); ASSERT_TRUE(io_helper->Run()); } }; @@ -698,7 +686,7 @@ IN_PROC_BROWSER_TEST_F(AdBlockServiceTest, SocialButttonAdBLockTagTest) { kAdBlockTestPage); g_brave_browser_process->ad_block_service()->EnableTag( brave_shields::kFacebookEmbeds, true); - WaitForDefaultAdBlockServiceThread(); + WaitForAdBlockServiceThreads(); GURL resource_url = embedded_test_server()->GetURL("example.com", "/logo.png"); ui_test_utils::NavigateToURL(browser(), tab_url); @@ -723,7 +711,7 @@ IN_PROC_BROWSER_TEST_F(AdBlockServiceTest, SocialButttonAdBlockDiffTagTest) { kAdBlockTestPage); g_brave_browser_process->ad_block_service()->EnableTag( brave_shields::kFacebookEmbeds, true); - WaitForDefaultAdBlockServiceThread(); + WaitForAdBlockServiceThreads(); GURL resource_url = embedded_test_server()->GetURL("example.com", "/logo.png"); ui_test_utils::NavigateToURL(browser(), tab_url); @@ -751,38 +739,38 @@ IN_PROC_BROWSER_TEST_F(AdBlockServiceTest, TagPrefsControlTags) { // Toggling prefs once is reflected in the adblock client. prefs->SetBoolean(kLinkedInEmbedControlType, true); - WaitForAllAdBlockServiceThreads(); + WaitForAdBlockServiceThreads(); AssertTagExists(brave_shields::kFacebookEmbeds, true); AssertTagExists(brave_shields::kTwitterEmbeds, true); AssertTagExists(brave_shields::kLinkedInEmbeds, true); prefs->SetBoolean(kFBEmbedControlType, false); - WaitForAllAdBlockServiceThreads(); + WaitForAdBlockServiceThreads(); AssertTagExists(brave_shields::kFacebookEmbeds, false); AssertTagExists(brave_shields::kTwitterEmbeds, true); AssertTagExists(brave_shields::kLinkedInEmbeds, true); prefs->SetBoolean(kTwitterEmbedControlType, false); - WaitForAllAdBlockServiceThreads(); + WaitForAdBlockServiceThreads(); AssertTagExists(brave_shields::kFacebookEmbeds, false); AssertTagExists(brave_shields::kTwitterEmbeds, false); AssertTagExists(brave_shields::kLinkedInEmbeds, true); // Toggling prefs back is reflected in the adblock client. prefs->SetBoolean(kLinkedInEmbedControlType, false); - WaitForAllAdBlockServiceThreads(); + WaitForAdBlockServiceThreads(); AssertTagExists(brave_shields::kFacebookEmbeds, false); AssertTagExists(brave_shields::kTwitterEmbeds, false); AssertTagExists(brave_shields::kLinkedInEmbeds, false); prefs->SetBoolean(kFBEmbedControlType, true); - WaitForAllAdBlockServiceThreads(); + WaitForAdBlockServiceThreads(); AssertTagExists(brave_shields::kFacebookEmbeds, true); AssertTagExists(brave_shields::kTwitterEmbeds, false); AssertTagExists(brave_shields::kLinkedInEmbeds, false); prefs->SetBoolean(kTwitterEmbedControlType, true); - WaitForAllAdBlockServiceThreads(); + WaitForAdBlockServiceThreads(); AssertTagExists(brave_shields::kFacebookEmbeds, true); AssertTagExists(brave_shields::kTwitterEmbeds, true); AssertTagExists(brave_shields::kLinkedInEmbeds, false); diff --git a/components/brave_shields/browser/autoplay_whitelist_service.cc b/components/brave_shields/browser/autoplay_whitelist_service.cc index 96cec9c760a7..2a875fdae53a 100644 --- a/components/brave_shields/browser/autoplay_whitelist_service.cc +++ b/components/brave_shields/browser/autoplay_whitelist_service.cc @@ -5,32 +5,29 @@ #include "brave/components/brave_shields/browser/autoplay_whitelist_service.h" -#include #include -#include "base/base_paths.h" #include "base/bind.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/threading/thread_restrictions.h" -#include "brave/browser/brave_browser_process_impl.h" -#include "brave/components/brave_shields/browser/ad_block_service.h" -#include "brave/components/brave_shields/browser/local_data_files_service.h" -#include "brave/components/brave_shields/browser/dat_file_util.h" +#include "base/task/post_task.h" +#include "base/task_runner_util.h" +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" #include "brave/vendor/autoplay-whitelist/autoplay_whitelist_parser.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" +using brave_component_updater::LocalDataFilesObserver; +using brave_component_updater::LocalDataFilesService; + namespace brave_shields { -AutoplayWhitelistService::AutoplayWhitelistService() - : autoplay_whitelist_client_(new AutoplayWhitelistParser()), +AutoplayWhitelistService::AutoplayWhitelistService( + LocalDataFilesService* local_data_files_service) + : LocalDataFilesObserver(local_data_files_service), + autoplay_whitelist_client_(new AutoplayWhitelistParser()), weak_factory_(this) { - DETACH_FROM_SEQUENCE(sequence_checker_); } AutoplayWhitelistService::~AutoplayWhitelistService() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); autoplay_whitelist_client_.reset(); } @@ -43,51 +40,45 @@ bool AutoplayWhitelistService::ShouldAllowAutoplay(const GURL& url) { return autoplay_whitelist_client_->matchesHost(etld_plus_one.c_str()); } -void AutoplayWhitelistService::OnDATFileDataReady() { - if (buffer_.empty()) { - LOG(ERROR) << "Could not obtain autoplay whitelist data"; - return; - } - autoplay_whitelist_client_.reset(new AutoplayWhitelistParser()); - if (!autoplay_whitelist_client_->deserialize( - reinterpret_cast(&buffer_.front()))) { - autoplay_whitelist_client_.reset(); - LOG(ERROR) << "Failed to deserialize autoplay whitelist data"; - return; - } -} - void AutoplayWhitelistService::OnComponentReady( const std::string& component_id, const base::FilePath& install_dir, const std::string& manifest) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + base::FilePath dat_file_path = install_dir + .AppendASCII(AUTOPLAY_DAT_FILE_VERSION) + .AppendASCII(AUTOPLAY_DAT_FILE); - base::FilePath dat_file_path = install_dir.AppendASCII( - AUTOPLAY_DAT_FILE_VERSION).AppendASCII(AUTOPLAY_DAT_FILE); - - GetTaskRunner()->PostTaskAndReply( + base::PostTaskAndReplyWithResult( + local_data_files_service()->GetTaskRunner().get(), FROM_HERE, - base::Bind(&GetDATFileData, dat_file_path, &buffer_), - base::Bind(&AutoplayWhitelistService::OnDATFileDataReady, - weak_factory_.GetWeakPtr())); + base::BindOnce( + &brave_component_updater::LoadDATFileData, + dat_file_path), + base::BindOnce(&AutoplayWhitelistService::OnGetDATFileData, + weak_factory_.GetWeakPtr())); } -scoped_refptr - AutoplayWhitelistService::GetTaskRunner() { - // We share the same task runner as ad-block code - return g_brave_browser_process->ad_block_service()->GetTaskRunner(); +void AutoplayWhitelistService::OnGetDATFileData(GetDATFileDataResult result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (result.second.empty()) { + LOG(ERROR) << "Could not obtain autoplay whitelist data"; + return; + } + if (!result.first.get()) { + LOG(ERROR) << "Failed to deserialize autoplay whitelist data"; + return; + } + + autoplay_whitelist_client_ = std::move(result.first); + buffer_ = std::move(result.second); } /////////////////////////////////////////////////////////////////////////////// - -// The autoplay whitelist factory. Using the Brave Shields as a singleton -// is the job of the browser process. -std::unique_ptr AutoplayWhitelistServiceFactory() { - std::unique_ptr service = - std::make_unique(); - g_brave_browser_process->local_data_files_service()->AddObserver( - service.get()); - return service; +// The autoplay whitelist factory +std::unique_ptr AutoplayWhitelistServiceFactory( + LocalDataFilesService* local_data_files_service) { + return std::make_unique(local_data_files_service); } } // namespace brave_shields diff --git a/components/brave_shields/browser/autoplay_whitelist_service.h b/components/brave_shields/browser/autoplay_whitelist_service.h index 9734c04d650c..13019ff7a34f 100644 --- a/components/brave_shields/browser/autoplay_whitelist_service.h +++ b/components/brave_shields/browser/autoplay_whitelist_service.h @@ -6,37 +6,38 @@ #ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_AUTOPLAY_WHITELIST_SERVICE_H_ #define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_AUTOPLAY_WHITELIST_SERVICE_H_ -#include - -#include #include #include -#include +#include #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" -#include "base/sequenced_task_runner.h" -#include "brave/components/brave_shields/browser/base_local_data_files_observer.h" -#include "brave/components/brave_shields/browser/dat_file_util.h" -#include "content/public/common/resource_type.h" +#include "brave/components/brave_component_updater/browser/dat_file_util.h" +#include "brave/components/brave_component_updater/browser/local_data_files_observer.h" #include "url/gurl.h" class AutoplayWhitelistParser; class BraveContentSettingsObserverAutoplayTest; +using brave_component_updater::LocalDataFilesObserver; +using brave_component_updater::LocalDataFilesService; + namespace brave_shields { // The brave shields service in charge of autoplay whitelist -class AutoplayWhitelistService : public BaseLocalDataFilesObserver { +class AutoplayWhitelistService : public LocalDataFilesObserver { public: - AutoplayWhitelistService(); + using GetDATFileDataResult = + brave_component_updater::LoadDATFileDataResult; + + explicit AutoplayWhitelistService( + LocalDataFilesService* local_data_files_service); ~AutoplayWhitelistService() override; bool ShouldAllowAutoplay(const GURL& url); - scoped_refptr GetTaskRunner(); - // implementation of BaseLocalDataFilesObserver + // implementation of LocalDataFilesObserver void OnComponentReady(const std::string& component_id, const base::FilePath& install_dir, const std::string& manifest) override; @@ -44,19 +45,19 @@ class AutoplayWhitelistService : public BaseLocalDataFilesObserver { private: friend class ::BraveContentSettingsObserverAutoplayTest; - void OnDATFileDataReady(); - - brave_shields::DATFileDataBuffer buffer_; + void OnGetDATFileData(GetDATFileDataResult result); std::unique_ptr autoplay_whitelist_client_; - + brave_component_updater::DATFileDataBuffer buffer_; SEQUENCE_CHECKER(sequence_checker_); + base::WeakPtrFactory weak_factory_; DISALLOW_COPY_AND_ASSIGN(AutoplayWhitelistService); }; // Creates the AutoplayWhitelistService -std::unique_ptr AutoplayWhitelistServiceFactory(); +std::unique_ptr AutoplayWhitelistServiceFactory( + LocalDataFilesService* local_data_files_service); } // namespace brave_shields diff --git a/components/brave_shields/browser/base_brave_shields_service.cc b/components/brave_shields/browser/base_brave_shields_service.cc index 11c6a5f673b5..813a6b8f6263 100644 --- a/components/brave_shields/browser/base_brave_shields_service.cc +++ b/components/brave_shields/browser/base_brave_shields_service.cc @@ -15,18 +15,15 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" -#include "base/task_runner_util.h" -#include "base/task/post_task.h" -#include "base/threading/thread_restrictions.h" + +using brave_component_updater::BraveComponent; namespace brave_shields { -BaseBraveShieldsService::BaseBraveShieldsService() - : initialized_(false), - task_runner_( - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock(), - base::TaskPriority::USER_VISIBLE, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) { +BaseBraveShieldsService::BaseBraveShieldsService( + BraveComponent::Delegate* delegate) + : BraveComponent(delegate), + initialized_(false) { } BaseBraveShieldsService::~BaseBraveShieldsService() { @@ -70,9 +67,4 @@ bool BaseBraveShieldsService::ShouldStartRequest(const GURL& url, return true; } -scoped_refptr -BaseBraveShieldsService::GetTaskRunner() { - return task_runner_; -} - } // namespace brave_shields diff --git a/components/brave_shields/browser/base_brave_shields_service.h b/components/brave_shields/browser/base_brave_shields_service.h index 9c9ff6063741..ad10e0e87a93 100644 --- a/components/brave_shields/browser/base_brave_shields_service.h +++ b/components/brave_shields/browser/base_brave_shields_service.h @@ -10,23 +10,24 @@ #include #include -#include // TODO(brave): is an unapproved C++11 header #include // NOLINT #include "base/files/file_path.h" #include "base/sequenced_task_runner.h" -#include "brave/browser/extensions/brave_component_extension.h" +#include "brave/components/brave_component_updater/browser/brave_component.h" #include "content/public/common/resource_type.h" #include "url/gurl.h" +using brave_component_updater::BraveComponent; + namespace brave_shields { // The brave shields service in charge of checking brave shields like ad-block, // tracking protection, etc. -class BaseBraveShieldsService : public BraveComponentExtension { +class BaseBraveShieldsService : public BraveComponent { public: - BaseBraveShieldsService(); + explicit BaseBraveShieldsService(BraveComponent::Delegate* delegate); ~BaseBraveShieldsService() override; bool Start(); void Stop(); @@ -36,7 +37,6 @@ class BaseBraveShieldsService : public BraveComponentExtension { const std::string& tab_host, bool* did_match_exception, bool* cancel_request_explicitly); - virtual scoped_refptr GetTaskRunner(); protected: virtual bool Init() = 0; diff --git a/components/brave_shields/browser/base_local_data_files_observer.cc b/components/brave_shields/browser/base_local_data_files_observer.cc deleted file mode 100644 index b9a105d4a587..000000000000 --- a/components/brave_shields/browser/base_local_data_files_observer.cc +++ /dev/null @@ -1,13 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_shields/browser/base_local_data_files_observer.h" - -namespace brave_shields { - -BaseLocalDataFilesObserver::BaseLocalDataFilesObserver() { } - -BaseLocalDataFilesObserver::~BaseLocalDataFilesObserver() { } - -} // namespace brave_shields diff --git a/components/brave_shields/browser/base_local_data_files_observer.h b/components/brave_shields/browser/base_local_data_files_observer.h deleted file mode 100644 index 9a60b0f95fa2..000000000000 --- a/components/brave_shields/browser/base_local_data_files_observer.h +++ /dev/null @@ -1,29 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_BASE_LOCAL_DATA_FILES_OBSERVER_H_ -#define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_BASE_LOCAL_DATA_FILES_OBSERVER_H_ - -#include - -#include "base/files/file_path.h" - -namespace brave_shields { - -// The abstract base class for observers of the local data files service, -// which is the component that arbitrates access to various DAT files -// like tracking protection, video autoplay whitelist, etc. -class BaseLocalDataFilesObserver { - public: - BaseLocalDataFilesObserver(); - virtual ~BaseLocalDataFilesObserver(); - - virtual void OnComponentReady(const std::string& component_id, - const base::FilePath& install_dir, - const std::string& manifest) = 0; -}; - -} // namespace brave_shields - -#endif // BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_BASE_LOCAL_DATA_FILES_OBSERVER_H_ diff --git a/components/brave_shields/browser/brave_resource_dispatcher_host_delegate.cc b/components/brave_shields/browser/brave_resource_dispatcher_host_delegate.cc deleted file mode 100644 index c7e0e5ef0ce1..000000000000 --- a/components/brave_shields/browser/brave_resource_dispatcher_host_delegate.cc +++ /dev/null @@ -1,45 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_shields/browser/brave_resource_dispatcher_host_delegate.h" - -#include "brave/browser/brave_browser_process_impl.h" -#include "brave/components/brave_shields/browser/ad_block_custom_filters_service.h" -#include "brave/components/brave_shields/browser/ad_block_regional_service_manager.h" -#include "brave/components/brave_shields/browser/ad_block_service.h" -#include "brave/components/brave_shields/browser/https_everywhere_service.h" -#include "brave/components/brave_shields/browser/local_data_files_service.h" -#include "extensions/buildflags/buildflags.h" - -using content::ResourceType; - -BraveResourceDispatcherHostDelegate::BraveResourceDispatcherHostDelegate() { - g_brave_browser_process->ad_block_service()->Start(); - g_brave_browser_process->ad_block_custom_filters_service()->Start(); - g_brave_browser_process->ad_block_regional_service_manager()->Start(); - g_brave_browser_process->https_everywhere_service()->Start(); - // Ensure that all services that observe the local data files service - // are created before calling Start(). - g_brave_browser_process->autoplay_whitelist_service(); -#if BUILDFLAG(ENABLE_EXTENSIONS) - g_brave_browser_process->extension_whitelist_service(); -#endif - g_brave_browser_process->referrer_whitelist_service(); - g_brave_browser_process->tracking_protection_service(); - // Now start the local data files service, which calls all observers. - g_brave_browser_process->local_data_files_service()->Start(); -} - -BraveResourceDispatcherHostDelegate::~BraveResourceDispatcherHostDelegate() { -} - -void BraveResourceDispatcherHostDelegate::AppendStandardResourceThrottles( - net::URLRequest* request, - content::ResourceContext* resource_context, - ResourceType resource_type, - std::vector>* throttles) { - ChromeResourceDispatcherHostDelegate::AppendStandardResourceThrottles( - request, resource_context, resource_type, throttles); -} diff --git a/components/brave_shields/browser/brave_resource_dispatcher_host_delegate.h b/components/brave_shields/browser/brave_resource_dispatcher_host_delegate.h deleted file mode 100644 index 4c83e95af4b2..000000000000 --- a/components/brave_shields/browser/brave_resource_dispatcher_host_delegate.h +++ /dev/null @@ -1,31 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_BROWSER_LOADER_BRAVE_RESOURCE_DISPATCHER_HOST_DELEGATE_H_ -#define BRAVE_BROWSER_LOADER_BRAVE_RESOURCE_DISPATCHER_HOST_DELEGATE_H_ - -#include -#include - -#include "chrome/browser/loader/chrome_resource_dispatcher_host_delegate.h" - - -class BraveResourceDispatcherHostDelegate - : public ChromeResourceDispatcherHostDelegate { - public: - BraveResourceDispatcherHostDelegate(); - ~BraveResourceDispatcherHostDelegate() override; - - protected: - void AppendStandardResourceThrottles( - net::URLRequest* request, - content::ResourceContext* resource_context, - content::ResourceType resource_type, - std::vector>* throttles) - override; - - DISALLOW_COPY_AND_ASSIGN(BraveResourceDispatcherHostDelegate); -}; - -#endif // BRAVE_BROWSER_LOADER_BRAVE_RESOURCE_DISPATCHER_HOST_DELEGATE_H_ diff --git a/components/brave_shields/browser/dat_file_util.h b/components/brave_shields/browser/dat_file_util.h deleted file mode 100644 index adc4e7a76a36..000000000000 --- a/components/brave_shields/browser/dat_file_util.h +++ /dev/null @@ -1,29 +0,0 @@ -/* Copyright (c) 2019 The Brave Authors. All rights reserved. - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_DAT_FILE_UTIL_H_ -#define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_DAT_FILE_UTIL_H_ - -#include -#include - -#include "base/callback_forward.h" - -namespace base { -class FilePath; -} - -namespace brave_shields { - -using DATFileDataBuffer = std::vector; - -void GetDATFileData(const base::FilePath& file_path, - DATFileDataBuffer* buffer); -void GetDATFileAsString(const base::FilePath& file_path, - std::string* contents); - -} // namespace brave_shields - -#endif // BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_DAT_FILE_UTIL_H_ diff --git a/components/brave_shields/browser/extension_whitelist_service.cc b/components/brave_shields/browser/extension_whitelist_service.cc index 7379cf9aa491..ca1196c2e563 100644 --- a/components/brave_shields/browser/extension_whitelist_service.cc +++ b/components/brave_shields/browser/extension_whitelist_service.cc @@ -5,90 +5,78 @@ #include "brave/components/brave_shields/browser/extension_whitelist_service.h" -#include #include -#include "base/base_paths.h" #include "base/bind.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/threading/thread_restrictions.h" -#include "brave/browser/brave_browser_process_impl.h" -#include "brave/components/brave_shields/browser/ad_block_service.h" -#include "brave/components/brave_shields/browser/local_data_files_service.h" -#include "brave/components/brave_shields/browser/dat_file_util.h" +#include "base/task_runner_util.h" +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" #include "brave/vendor/extension-whitelist/extension_whitelist_parser.h" -#include "net/base/registry_controlled_domains/registry_controlled_domain.h" namespace brave_shields { -ExtensionWhitelistService::ExtensionWhitelistService() - : extension_whitelist_client_(new ExtensionWhitelistParser()), +ExtensionWhitelistService::ExtensionWhitelistService( + LocalDataFilesService* local_data_files_service) + : LocalDataFilesObserver(local_data_files_service), + extension_whitelist_client_(new ExtensionWhitelistParser()), weak_factory_(this) { - DETACH_FROM_SEQUENCE(sequence_checker_); } ExtensionWhitelistService::~ExtensionWhitelistService() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); extension_whitelist_client_.reset(); } -bool ExtensionWhitelistService::IsWhitelisted(const std::string& extension_id) const { +bool ExtensionWhitelistService::IsWhitelisted( + const std::string& extension_id) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return extension_whitelist_client_->isWhitelisted(extension_id.c_str()); } -bool ExtensionWhitelistService::IsBlacklisted(const std::string& extension_id) const { +bool ExtensionWhitelistService::IsBlacklisted( + const std::string& extension_id) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return extension_whitelist_client_->isBlacklisted(extension_id.c_str()); } -void ExtensionWhitelistService::OnDATFileDataReady() { - if (buffer_.empty()) { - LOG(ERROR) << "Could not obtain extension whitelist data"; - return; - } - extension_whitelist_client_.reset(new ExtensionWhitelistParser()); - if (!extension_whitelist_client_->deserialize( - reinterpret_cast(&buffer_.front()))) { - extension_whitelist_client_.reset(); - LOG(ERROR) << "Failed to deserialize extension whitelist data"; - return; - } -} - void ExtensionWhitelistService::OnComponentReady( const std::string& component_id, const base::FilePath& install_dir, const std::string& manifest) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + base::FilePath dat_file_path = install_dir + .AppendASCII(EXTENSION_DAT_FILE_VERSION) + .AppendASCII(EXTENSION_DAT_FILE); - base::FilePath dat_file_path = install_dir.AppendASCII( - EXTENSION_DAT_FILE_VERSION).AppendASCII(EXTENSION_DAT_FILE); - - GetTaskRunner()->PostTaskAndReply( + base::PostTaskAndReplyWithResult( + local_data_files_service()->GetTaskRunner().get(), FROM_HERE, - base::Bind(&GetDATFileData, dat_file_path, &buffer_), - base::Bind(&ExtensionWhitelistService::OnDATFileDataReady, - weak_factory_.GetWeakPtr())); + base::BindOnce( + &brave_component_updater::LoadDATFileData, + dat_file_path), + base::BindOnce(&ExtensionWhitelistService::OnGetDATFileData, + weak_factory_.GetWeakPtr())); } -scoped_refptr - ExtensionWhitelistService::GetTaskRunner() { - // We share the same task runner as ad-block code - return g_brave_browser_process->ad_block_service()->GetTaskRunner(); +void ExtensionWhitelistService::OnGetDATFileData(GetDATFileDataResult result) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (result.second.empty()) { + LOG(ERROR) << "Could not obtain extension whitelist data"; + return; + } + if (!result.first.get()) { + LOG(ERROR) << "Failed to deserialize extension whitelist data"; + return; + } + + extension_whitelist_client_ = std::move(result.first); + buffer_ = std::move(result.second); } /////////////////////////////////////////////////////////////////////////////// -// The extension whitelist factory. Using the Brave Shields as a singleton -// is the job of the browser process. -std::unique_ptr ExtensionWhitelistServiceFactory() { - std::unique_ptr service = - std::make_unique(); - g_brave_browser_process->local_data_files_service()->AddObserver( - service.get()); - return service; +std::unique_ptr ExtensionWhitelistServiceFactory( + LocalDataFilesService* local_data_files_service) { + return std::make_unique(local_data_files_service); } } // namespace brave_shields diff --git a/components/brave_shields/browser/extension_whitelist_service.h b/components/brave_shields/browser/extension_whitelist_service.h index 56ab51dd55d0..79fd9dafe443 100644 --- a/components/brave_shields/browser/extension_whitelist_service.h +++ b/components/brave_shields/browser/extension_whitelist_service.h @@ -6,39 +6,42 @@ #ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_EXTENSION_WHITELIST_SERVICE_H_ #define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_EXTENSION_WHITELIST_SERVICE_H_ -#include - #include #include #include +#include #include #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" -#include "base/sequenced_task_runner.h" -#include "brave/components/brave_shields/browser/base_local_data_files_observer.h" -#include "brave/components/brave_shields/browser/dat_file_util.h" -#include "content/public/common/resource_type.h" -#include "url/gurl.h" +#include "brave/components/brave_component_updater/browser/dat_file_util.h" +#include "brave/components/brave_component_updater/browser/local_data_files_observer.h" class ExtensionWhitelistParser; class BraveExtensionProviderTest; class BravePDFDownloadTest; +using brave_component_updater::LocalDataFilesObserver; +using brave_component_updater::LocalDataFilesService; + +// TODO(bridiver) - move out of brave shields namespace brave_shields { // The brave shields service in charge of extension whitelist -class ExtensionWhitelistService : public BaseLocalDataFilesObserver { +class ExtensionWhitelistService : public LocalDataFilesObserver { public: - ExtensionWhitelistService(); + using GetDATFileDataResult = + brave_component_updater::LoadDATFileDataResult; + + explicit ExtensionWhitelistService( + LocalDataFilesService* local_data_files_service); ~ExtensionWhitelistService() override; bool IsWhitelisted(const std::string& extension_id) const; bool IsBlacklisted(const std::string& extension_id) const; - scoped_refptr GetTaskRunner(); - // implementation of BaseLocalDataFilesObserver + // implementation of LocalDataFilesObserver void OnComponentReady(const std::string& component_id, const base::FilePath& install_dir, const std::string& manifest) override; @@ -47,19 +50,19 @@ class ExtensionWhitelistService : public BaseLocalDataFilesObserver { friend class ::BraveExtensionProviderTest; friend class ::BravePDFDownloadTest; - void OnDATFileDataReady(); - - brave_shields::DATFileDataBuffer buffer_; + void OnGetDATFileData(GetDATFileDataResult result); std::unique_ptr extension_whitelist_client_; - + brave_component_updater::DATFileDataBuffer buffer_; SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory weak_factory_; + DISALLOW_COPY_AND_ASSIGN(ExtensionWhitelistService); }; // Creates the ExtensionWhitelistService -std::unique_ptr ExtensionWhitelistServiceFactory(); +std::unique_ptr ExtensionWhitelistServiceFactory( + LocalDataFilesService* local_data_files_service); } // namespace brave_shields diff --git a/components/brave_shields/browser/https_everywhere_service.cc b/components/brave_shields/browser/https_everywhere_service.cc index ba1ece7162a2..975a42b5b723 100644 --- a/components/brave_shields/browser/https_everywhere_service.cc +++ b/components/brave_shields/browser/https_everywhere_service.cc @@ -11,6 +11,7 @@ #include #include "base/base_paths.h" +#include "base/bind.h" #include "base/json/json_reader.h" #include "base/logging.h" #include "base/macros.h" @@ -18,8 +19,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/threading/scoped_blocking_call.h" #include "base/values.h" -#include "brave/components/brave_shields/browser/dat_file_util.h" -#include "chrome/browser/browser_process.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/re2/src/re2/re2.h" #include "third_party/zlib/google/zip.h" @@ -80,6 +79,17 @@ std::string leveldbGet(leveldb::DB* db, const std::string &key) { namespace brave_shields { +const char kHTTPSEverywhereComponentName[] = "Brave HTTPS Everywhere Updater"; +const char kHTTPSEverywhereComponentId[] = "oofiananboodjbbmdelgdommihjbkfag"; +const char kHTTPSEverywhereComponentBase64PublicKey[] = + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvn9zSMjTmhkQyrZu5UdN" + "350nPqLoSeCYngcC7yDFwaUHjoBQXCZqGeDC69ciCQ2mlRhcV2nxXqlUDkiC6+7m" + "651nI+gi4oVqHagc7EFUyGA0yuIk7qIMvCBdH7wbET27de0rzbRzRht9EKzEjIhC" + "BtoPnmyrO/8qPrH4XR4cPfnFPuJssBBxC1B35H7rh0Br9qePhPDDe9OjyqYxPuio" + "+YcC9obL4g5krVrfrlKLfFNpIewUcJyBpSlCgfxEyEhgDkK9cILTMUi5vC7GxS3P" + "OtZqgfRg8Da4i+NwmjQqrz0JFtPMMSyUnmeMj+mSOL4xZVWr8fU2/GOCXs9gczDp" + "JwIDAQAB"; + bool HTTPSEverywhereService::g_ignore_port_for_test_(false); std::string HTTPSEverywhereService::g_https_everywhere_component_id_( kHTTPSEverywhereComponentId); @@ -87,7 +97,10 @@ std::string HTTPSEverywhereService::g_https_everywhere_component_base64_public_key_( kHTTPSEverywhereComponentBase64PublicKey); -HTTPSEverywhereService::HTTPSEverywhereService() : level_db_(nullptr) { +HTTPSEverywhereService::HTTPSEverywhereService( + BraveComponent::Delegate* delegate) + : BaseBraveShieldsService(delegate), + level_db_(nullptr) { DETACH_FROM_SEQUENCE(sequence_checker_); } @@ -99,11 +112,12 @@ void HTTPSEverywhereService::Cleanup() { GetTaskRunner()->PostTask( FROM_HERE, base::Bind(&HTTPSEverywhereService::CloseDatabase, - base::Unretained(this))); + AsWeakPtr())); } bool HTTPSEverywhereService::Init() { - Register(kHTTPSEverywhereComponentName, g_https_everywhere_component_id_, + Register(kHTTPSEverywhereComponentName, + g_https_everywhere_component_id_, g_https_everywhere_component_base64_public_key_); return true; } @@ -144,13 +158,14 @@ void HTTPSEverywhereService::OnComponentReady( GetTaskRunner()->PostTask( FROM_HERE, base::Bind(&HTTPSEverywhereService::InitDB, - base::Unretained(this), + AsWeakPtr(), install_dir)); } bool HTTPSEverywhereService::GetHTTPSURL( - const GURL* url, const uint64_t& request_identifier, - std::string& new_url) { + const GURL* url, + const uint64_t& request_identifier, + std::string* new_url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!url->is_valid()) @@ -163,7 +178,7 @@ bool HTTPSEverywhereService::GetHTTPSURL( return false; } - if (recently_used_cache_.get(url->spec(), &new_url)) { + if (recently_used_cache_.get(url->spec(), new_url)) { AddHTTPSEUrlToRedirectList(request_identifier); return true; } @@ -180,9 +195,9 @@ bool HTTPSEverywhereService::GetHTTPSURL( for (auto domain : domains) { std::string value = leveldbGet(level_db_, domain); if (!value.empty()) { - new_url = ApplyHTTPSRule(candidate_url.spec(), value); - if (0 != new_url.length()) { - recently_used_cache_.add(candidate_url.spec(), new_url); + *new_url = ApplyHTTPSRule(candidate_url.spec(), value); + if (0 != new_url->length()) { + recently_used_cache_.add(candidate_url.spec(), *new_url); AddHTTPSEUrlToRedirectList(request_identifier); return true; } @@ -195,7 +210,7 @@ bool HTTPSEverywhereService::GetHTTPSURL( bool HTTPSEverywhereService::GetHTTPSURLFromCacheOnly( const GURL* url, const uint64_t& request_identifier, - std::string& cached_url) { + std::string* cached_url) { if (!url->is_valid()) return false; @@ -206,7 +221,7 @@ bool HTTPSEverywhereService::GetHTTPSURLFromCacheOnly( return false; } - if (recently_used_cache_.get(url->spec(), &cached_url)) { + if (recently_used_cache_.get(url->spec(), cached_url)) { AddHTTPSEUrlToRedirectList(request_identifier); return true; } @@ -215,7 +230,7 @@ bool HTTPSEverywhereService::GetHTTPSURLFromCacheOnly( bool HTTPSEverywhereService::ShouldHTTPSERedirect( const uint64_t& request_identifier) { - std::lock_guard guard(httpse_get_urls_redirects_count_mutex_); + base::AutoLock auto_lock(httpse_get_urls_redirects_count_mutex_); for (size_t i = 0; i < httpse_urls_redirects_count_.size(); i++) { if (request_identifier == httpse_urls_redirects_count_[i].request_identifier_ && @@ -231,7 +246,7 @@ bool HTTPSEverywhereService::ShouldHTTPSERedirect( void HTTPSEverywhereService::AddHTTPSEUrlToRedirectList( const uint64_t& request_identifier) { // Adding redirects count for the current request - std::lock_guard guard(httpse_get_urls_redirects_count_mutex_); + base::AutoLock auto_lock(httpse_get_urls_redirects_count_mutex_); bool hostFound = false; for (size_t i = 0; i < httpse_urls_redirects_count_.size(); i++) { if (request_identifier == @@ -392,8 +407,9 @@ void HTTPSEverywhereService::SetIgnorePortForTest(bool ignore) { // The brave shields factory. Using the Brave Shields as a singleton // is the job of the browser process. -std::unique_ptr HTTPSEverywhereServiceFactory() { - return std::make_unique(); +std::unique_ptr HTTPSEverywhereServiceFactory( + BraveComponent::Delegate* delegate) { + return std::make_unique(delegate); } } // namespace brave_shields diff --git a/components/brave_shields/browser/https_everywhere_service.h b/components/brave_shields/browser/https_everywhere_service.h index 9b90f10aa9f5..aa7024f56989 100644 --- a/components/brave_shields/browser/https_everywhere_service.h +++ b/components/brave_shields/browser/https_everywhere_service.h @@ -1,22 +1,21 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public +/* Copyright (c) 2019 The Brave Authors. All rights reserved. + * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_HTTPS_EVERYHWERE_SERVICE_H_ -#define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_HTTPS_EVERYHWERE_SERVICE_H_ - -#include +#ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_HTTPS_EVERYWHERE_SERVICE_H_ +#define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_HTTPS_EVERYWHERE_SERVICE_H_ #include #include #include -#include #include "base/files/file_path.h" +#include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" +#include "base/synchronization/lock.h" #include "brave/components/brave_shields/browser/base_brave_shields_service.h" #include "brave/components/brave_shields/browser/https_everywhere_recently_used_cache.h" -#include "content/public/common/resource_type.h" namespace leveldb { class DB; @@ -24,40 +23,37 @@ class DB; class HTTPSEverywhereServiceTest; -namespace brave_shields { +using brave_component_updater::BraveComponent; -const std::string kHTTPSEverywhereComponentName("Brave HTTPS Everywhere Updater"); -const std::string kHTTPSEverywhereComponentId("oofiananboodjbbmdelgdommihjbkfag"); +namespace brave_shields { -const std::string kHTTPSEverywhereComponentBase64PublicKey = - "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvn9zSMjTmhkQyrZu5UdN" - "350nPqLoSeCYngcC7yDFwaUHjoBQXCZqGeDC69ciCQ2mlRhcV2nxXqlUDkiC6+7m" - "651nI+gi4oVqHagc7EFUyGA0yuIk7qIMvCBdH7wbET27de0rzbRzRht9EKzEjIhC" - "BtoPnmyrO/8qPrH4XR4cPfnFPuJssBBxC1B35H7rh0Br9qePhPDDe9OjyqYxPuio" - "+YcC9obL4g5krVrfrlKLfFNpIewUcJyBpSlCgfxEyEhgDkK9cILTMUi5vC7GxS3P" - "OtZqgfRg8Da4i+NwmjQqrz0JFtPMMSyUnmeMj+mSOL4xZVWr8fU2/GOCXs9gczDp" - "JwIDAQAB"; +extern const char kHTTPSEverywhereComponentName[]; +extern const char kHTTPSEverywhereComponentId[]; +extern const char kHTTPSEverywhereComponentBase64PublicKey[]; struct HTTPSE_REDIRECTS_COUNT_ST { -public: - HTTPSE_REDIRECTS_COUNT_ST(uint64_t request_identifier, - unsigned int redirects): - request_identifier_(request_identifier), - redirects_(redirects) { - } - - uint64_t request_identifier_; - unsigned int redirects_; + public: + HTTPSE_REDIRECTS_COUNT_ST(uint64_t request_identifier, + unsigned int redirects): + request_identifier_(request_identifier), + redirects_(redirects) { + } + + uint64_t request_identifier_; + unsigned int redirects_; }; -class HTTPSEverywhereService : public BaseBraveShieldsService { +class HTTPSEverywhereService : public BaseBraveShieldsService, + public base::SupportsWeakPtr { public: - HTTPSEverywhereService(); - ~HTTPSEverywhereService() override; - bool GetHTTPSURL(const GURL* url, const uint64_t& request_id, - std::string& new_url); + explicit HTTPSEverywhereService(BraveComponent::Delegate* delegate); + ~HTTPSEverywhereService() override; + bool GetHTTPSURL(const GURL* url, + const uint64_t& request_id, + std::string* new_url); bool GetHTTPSURLFromCacheOnly(const GURL* url, - const uint64_t& request_id, std::string& cached_url); + const uint64_t& request_id, + std::string* cached_url); protected: bool Init() override; @@ -86,7 +82,7 @@ class HTTPSEverywhereService : public BaseBraveShieldsService { void InitDB(const base::FilePath& install_dir); - std::mutex httpse_get_urls_redirects_count_mutex_; + base::Lock httpse_get_urls_redirects_count_mutex_; std::vector httpse_urls_redirects_count_; HTTPSERecentlyUsedCache recently_used_cache_; leveldb::DB* level_db_; @@ -96,8 +92,9 @@ class HTTPSEverywhereService : public BaseBraveShieldsService { }; // Creates the HTTPSEverywhereService -std::unique_ptr HTTPSEverywhereServiceFactory(); +std::unique_ptr HTTPSEverywhereServiceFactory( + BraveComponent::Delegate* delegate); } // namespace brave_shields -#endif // BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_HTTPS_EVERYHWERE_SERVICE_H_ +#endif // BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_HTTPS_EVERYWHERE_SERVICE_H_ diff --git a/components/brave_shields/browser/local_data_files_service.cc b/components/brave_shields/browser/local_data_files_service.cc deleted file mode 100644 index b31fa50ee9ae..000000000000 --- a/components/brave_shields/browser/local_data_files_service.cc +++ /dev/null @@ -1,76 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "brave/components/brave_shields/browser/local_data_files_service.h" - -#include -#include - -#include "base/base_paths.h" -#include "base/bind.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/threading/thread_restrictions.h" -#include "brave/browser/brave_browser_process_impl.h" -#include "brave/components/brave_shields/browser/base_local_data_files_observer.h" - -namespace brave_shields { - -std::string LocalDataFilesService::g_local_data_files_component_id_( - kLocalDataFilesComponentId); -std::string LocalDataFilesService::g_local_data_files_component_base64_public_key_( - kLocalDataFilesComponentBase64PublicKey); - -LocalDataFilesService::LocalDataFilesService() - : initialized_(false), - observers_already_called_(false), - weak_factory_(this) { - DETACH_FROM_SEQUENCE(sequence_checker_); -} - -LocalDataFilesService::~LocalDataFilesService() { } - -bool LocalDataFilesService::Start() { - if (initialized_) - return true; - Register(kLocalDataFilesComponentName, - g_local_data_files_component_id_, - g_local_data_files_component_base64_public_key_); - initialized_ = true; - return true; -} - -void LocalDataFilesService::AddObserver(BaseLocalDataFilesObserver* observer) { - DCHECK(!observers_already_called_); - observers_.push_back(observer); -} - -void LocalDataFilesService::OnComponentReady( - const std::string& component_id, - const base::FilePath& install_dir, - const std::string& manifest) { - observers_already_called_ = true; - for (BaseLocalDataFilesObserver* observer : observers_) - observer->OnComponentReady(component_id, install_dir, manifest); -} - -// static -void LocalDataFilesService::SetComponentIdAndBase64PublicKeyForTest( - const std::string& component_id, - const std::string& component_base64_public_key) { - g_local_data_files_component_id_ = component_id; - g_local_data_files_component_base64_public_key_ = component_base64_public_key; -} - -/////////////////////////////////////////////////////////////////////////////// - -// The brave shields factory. Using the Brave Shields as a singleton -// is the job of the browser process. -std::unique_ptr LocalDataFilesServiceFactory() { - return std::make_unique(); -} - -} // namespace brave_shields diff --git a/components/brave_shields/browser/referrer_whitelist_service.cc b/components/brave_shields/browser/referrer_whitelist_service.cc index ee7ffe85ef89..78b52a8ac8c7 100644 --- a/components/brave_shields/browser/referrer_whitelist_service.cc +++ b/components/brave_shields/browser/referrer_whitelist_service.cc @@ -5,27 +5,29 @@ #include "brave/components/brave_shields/browser/referrer_whitelist_service.h" -#include #include -#include "base/base_paths.h" #include "base/bind.h" #include "base/json/json_reader.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/threading/thread_restrictions.h" -#include "brave/browser/brave_browser_process_impl.h" -#include "brave/components/brave_shields/browser/ad_block_service.h" -#include "brave/components/brave_shields/browser/local_data_files_service.h" -#include "brave/components/brave_shields/browser/dat_file_util.h" +#include "base/task/post_task.h" +#include "base/task_runner_util.h" +#include "base/values.h" +#include "brave/components/brave_component_updater/browser/dat_file_util.h" +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" + +using brave_component_updater::LocalDataFilesObserver; +using brave_component_updater::LocalDataFilesService; +using content::BrowserThread; namespace brave_shields { -ReferrerWhitelistService::ReferrerWhitelistService() - : weak_factory_(this) { - DETACH_FROM_SEQUENCE(sequence_checker_); +ReferrerWhitelistService::ReferrerWhitelistService( + LocalDataFilesService* local_data_files_service) + : LocalDataFilesObserver(local_data_files_service), + weak_factory_(this), + weak_factory_io_thread_(this) { } ReferrerWhitelistService::~ReferrerWhitelistService() { @@ -37,11 +39,24 @@ ReferrerWhitelistService::ReferrerWhitelist::ReferrerWhitelist( ReferrerWhitelistService::ReferrerWhitelist::~ReferrerWhitelist() = default; bool ReferrerWhitelistService::IsWhitelisted( - const GURL& firstPartyOrigin, const GURL& subresourceUrl) const { - for (auto rw : referrer_whitelist_) { - if (rw.first_party_pattern.MatchesURL(firstPartyOrigin)) { + const GURL& first_party_origin, const GURL& subresource_url) const { + if (BrowserThread::CurrentlyOn(BrowserThread::IO)) { + return IsWhitelisted( + referrer_whitelist_io_thread_, first_party_origin, subresource_url); + } else { + return IsWhitelisted( + referrer_whitelist_, first_party_origin, subresource_url); + } +} + +bool ReferrerWhitelistService::IsWhitelisted( + const std::vector& whitelist, + const GURL& first_party_origin, + const GURL& subresource_url) const { + for (auto rw : whitelist) { + if (rw.first_party_pattern.MatchesURL(first_party_origin)) { for (auto subresource_pattern : rw.subresource_pattern_list) { - if (subresource_pattern.MatchesURL(subresourceUrl)) { + if (subresource_pattern.MatchesURL(subresource_url)) { return true; } } @@ -50,15 +65,15 @@ bool ReferrerWhitelistService::IsWhitelisted( return false; } -void ReferrerWhitelistService::OnDATFileDataReady() { +void ReferrerWhitelistService::OnDATFileDataReady(std::string contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); referrer_whitelist_.clear(); - if (file_contents_.empty()) { + if (contents.empty()) { LOG(ERROR) << "Could not obtain referrer whitelist data"; return; } - base::Optional root = base::JSONReader::Read(file_contents_); - file_contents_.clear(); + base::Optional root = base::JSONReader::Read(contents); + contents.clear(); if (!root) { LOG(ERROR) << "Failed to parse referrer whitelist data"; return; @@ -83,37 +98,42 @@ void ReferrerWhitelistService::OnDATFileDataReady() { referrer_whitelist_.push_back(rw); } } + + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&ReferrerWhitelistService::OnDATFileDataReadyOnIOThread, + weak_factory_io_thread_.GetWeakPtr(), + referrer_whitelist_)); +} + +void ReferrerWhitelistService::OnDATFileDataReadyOnIOThread( + std::vector whitelist) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + referrer_whitelist_io_thread_ = std::move(whitelist); } void ReferrerWhitelistService::OnComponentReady( const std::string& component_id, const base::FilePath& install_dir, const std::string& manifest) { - base::FilePath dat_file_path = install_dir.AppendASCII( - REFERRER_DAT_FILE_VERSION).AppendASCII(REFERRER_DAT_FILE); - GetTaskRunner()->PostTaskAndReply( - FROM_HERE, - base::Bind(&GetDATFileAsString, dat_file_path, &file_contents_), - base::Bind(&ReferrerWhitelistService::OnDATFileDataReady, - weak_factory_.GetWeakPtr())); -} + base::FilePath dat_file_path = install_dir + .AppendASCII(REFERRER_DAT_FILE_VERSION) + .AppendASCII(REFERRER_DAT_FILE); -scoped_refptr - ReferrerWhitelistService::GetTaskRunner() { - // We share the same task runner as ad-block code - return g_brave_browser_process->ad_block_service()->GetTaskRunner(); + base::PostTaskAndReplyWithResult( + local_data_files_service()->GetTaskRunner().get(), + FROM_HERE, + base::BindOnce(&brave_component_updater::GetDATFileAsString, + dat_file_path), + base::BindOnce(&ReferrerWhitelistService::OnDATFileDataReady, + weak_factory_.GetWeakPtr())); } /////////////////////////////////////////////////////////////////////////////// -// The referrer whitelist factory. Using the Brave Shields as a singleton -// is the job of the browser process. -std::unique_ptr ReferrerWhitelistServiceFactory() { - std::unique_ptr service = - std::make_unique(); - g_brave_browser_process->local_data_files_service()->AddObserver( - service.get()); - return service; +std::unique_ptr ReferrerWhitelistServiceFactory( + LocalDataFilesService* local_data_files_service) { + return std::make_unique(local_data_files_service); } } // namespace brave_shields diff --git a/components/brave_shields/browser/referrer_whitelist_service.h b/components/brave_shields/browser/referrer_whitelist_service.h index 941d14197356..add9fab7e922 100644 --- a/components/brave_shields/browser/referrer_whitelist_service.h +++ b/components/brave_shields/browser/referrer_whitelist_service.h @@ -6,9 +6,6 @@ #ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_REFERRER_WHITELIST_SERVICE_H_ #define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_REFERRER_WHITELIST_SERVICE_H_ -#include - -#include #include #include #include @@ -16,11 +13,7 @@ #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" -#include "base/sequenced_task_runner.h" -#include "base/values.h" -#include "brave/components/brave_shields/browser/base_local_data_files_observer.h" -#include "brave/components/brave_shields/browser/dat_file_util.h" -#include "content/public/common/resource_type.h" +#include "brave/components/brave_component_updater/browser/local_data_files_observer.h" #include "extensions/common/url_pattern.h" #include "url/gurl.h" @@ -29,19 +22,22 @@ class ReferrerWhitelistServiceTest; +using brave_component_updater::LocalDataFilesObserver; +using brave_component_updater::LocalDataFilesService; + namespace brave_shields { // The brave shields service in charge of referrer whitelist -class ReferrerWhitelistService : public BaseLocalDataFilesObserver { +class ReferrerWhitelistService : public LocalDataFilesObserver { public: - ReferrerWhitelistService(); + explicit ReferrerWhitelistService( + LocalDataFilesService* local_data_files_service); ~ReferrerWhitelistService() override; bool IsWhitelisted(const GURL& firstPartyOrigin, const GURL& subresourceUrl) const; - scoped_refptr GetTaskRunner(); - // implementation of BaseLocalDataFilesObserver + // implementation of LocalDataFilesObserver void OnComponentReady(const std::string& component_id, const base::FilePath& install_dir, const std::string& manifest) override; @@ -49,10 +45,6 @@ class ReferrerWhitelistService : public BaseLocalDataFilesObserver { private: friend class ::ReferrerWhitelistServiceTest; - void OnDATFileDataReady(); - - typedef std::vector URLPatternList; - struct ReferrerWhitelist { URLPattern first_party_pattern; URLPatternList subresource_pattern_list; @@ -61,16 +53,26 @@ class ReferrerWhitelistService : public BaseLocalDataFilesObserver { ~ReferrerWhitelist(); }; - std::string file_contents_; + bool IsWhitelisted(const std::vector& whitelist, + const GURL& first_party_origin, + const GURL& subresource_url) const; + void OnDATFileDataReady(std::string contents); + void OnDATFileDataReadyOnIOThread(std::vector whitelist); + + typedef std::vector URLPatternList; + std::vector referrer_whitelist_; + std::vector referrer_whitelist_io_thread_; SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory weak_factory_; + base::WeakPtrFactory weak_factory_io_thread_; DISALLOW_COPY_AND_ASSIGN(ReferrerWhitelistService); }; // Creates the ReferrerWhitelistService -std::unique_ptr ReferrerWhitelistServiceFactory(); +std::unique_ptr ReferrerWhitelistServiceFactory( + LocalDataFilesService* local_data_files_service); } // namespace brave_shields diff --git a/components/brave_shields/browser/referrer_whitelist_service_browsertest.cc b/components/brave_shields/browser/referrer_whitelist_service_browsertest.cc index d122899d7ed6..3b63ef9ac57b 100644 --- a/components/brave_shields/browser/referrer_whitelist_service_browsertest.cc +++ b/components/brave_shields/browser/referrer_whitelist_service_browsertest.cc @@ -9,10 +9,13 @@ #include "base/test/thread_test_helper.h" #include "brave/browser/brave_browser_process_impl.h" #include "brave/common/brave_paths.h" -#include "brave/components/brave_shields/browser/local_data_files_service.h" +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" #include "brave/components/brave_shields/browser/referrer_whitelist_service.h" #include "chrome/browser/extensions/extension_browsertest.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" +using content::BrowserThread; using extensions::ExtensionBrowserTest; const char kLocalDataFilesComponentTestId[] = @@ -45,7 +48,7 @@ class ReferrerWhitelistServiceTest : public ExtensionBrowserTest { } void InitService() { - brave_shields::LocalDataFilesService:: + brave_component_updater::LocalDataFilesService:: SetComponentIdAndBase64PublicKeyForTest( kLocalDataFilesComponentTestId, kLocalDataFilesComponentTestBase64PublicKey); @@ -73,10 +76,12 @@ class ReferrerWhitelistServiceTest : public ExtensionBrowserTest { } void WaitForReferrerWhitelistServiceThread() { - scoped_refptr io_helper( - new base::ThreadTestHelper( - g_brave_browser_process->referrer_whitelist_service()-> - GetTaskRunner())); + scoped_refptr tr_helper(new base::ThreadTestHelper( + g_brave_browser_process->local_data_files_service()->GetTaskRunner())); + ASSERT_TRUE(tr_helper->Run()); + scoped_refptr io_helper(new base::ThreadTestHelper( + base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}) + .get())); ASSERT_TRUE(io_helper->Run()); base::RunLoop().RunUntilIdle(); } diff --git a/components/brave_shields/browser/tracking_protection_service.cc b/components/brave_shields/browser/tracking_protection_service.cc index 03bb6fcce287..d3f52669f0cc 100644 --- a/components/brave_shields/browser/tracking_protection_service.cc +++ b/components/brave_shields/browser/tracking_protection_service.cc @@ -5,23 +5,16 @@ #include "brave/components/brave_shields/browser/tracking_protection_service.h" -#include #include -#include "base/base_paths.h" #include "base/bind.h" -#include "base/command_line.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/threading/thread_restrictions.h" -#include "brave/browser/brave_browser_process_impl.h" -#include "brave/components/brave_shields/browser/ad_block_service.h" -#include "brave/components/brave_shields/browser/dat_file_util.h" -#include "brave/components/brave_shields/browser/local_data_files_service.h" +#include "base/task/post_task.h" +#include "base/task_runner_util.h" +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" #include "brave/components/content_settings/core/browser/brave_cookie_settings.h" #include "brave/vendor/tracking-protection/TPParser.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" #if BUILDFLAG(BRAVE_STP_ENABLED) #include "base/strings/string_split.h" @@ -29,12 +22,9 @@ #include "brave/components/brave_shields/browser/tracking_protection_helper.h" #include "brave/components/brave_shields/common/brave_shield_constants.h" #include "components/content_settings/core/browser/host_content_settings_map.h" -#include "content/browser/web_contents/web_contents_impl.h" -#include "content/public/browser/browser_thread.h" - -using content::BrowserThread; #endif +using content::BrowserThread; using content_settings::BraveCookieSettings; namespace brave_shields { @@ -48,13 +38,17 @@ const char kStorageTrackersFile[] = "StorageTrackingProtection.dat"; const int kThirdPartyHostsCacheSize = 20; -TrackingProtectionService::TrackingProtectionService() - : tracking_protection_client_(new CTPParser()), weak_factory_(this) { - DETACH_FROM_SEQUENCE(sequence_checker_); +TrackingProtectionService::TrackingProtectionService( + LocalDataFilesService* local_data_files_service) + : LocalDataFilesObserver(local_data_files_service), + tracking_protection_client_(new CTPParser()), + weak_factory_(this), + weak_factory_io_thread_(this) { } TrackingProtectionService::~TrackingProtectionService() { - tracking_protection_client_.reset(); + BrowserThread::DeleteSoon( + BrowserThread::IO, FROM_HERE, tracking_protection_client_.release()); } #if BUILDFLAG(BRAVE_STP_ENABLED) @@ -175,25 +169,35 @@ bool TrackingProtectionService::ShouldStoreState(HostContentSettingsMap* map, first_party_storage_trackers_.end(); } -void TrackingProtectionService::ParseStorageTrackersData() { - if (storage_trackers_buffer_.empty()) { - LOG(ERROR) << "Could not obtain tracking protection data"; +void TrackingProtectionService::OnGetSTPDATFileData(std::string contents) { + if (contents.empty()) { + LOG(ERROR) << "Could not obtain first party trackers data"; return; } - std::string trackers(storage_trackers_buffer_.begin(), - storage_trackers_buffer_.end()); std::vector storage_trackers = - base::SplitString(base::StringPiece(trackers.data(), trackers.size()), + base::SplitString(base::StringPiece(contents.data(), contents.size()), ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); if (storage_trackers.empty()) { LOG(ERROR) << "No first party trackers found"; return; } + + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::IO}, + base::BindOnce( + &TrackingProtectionService::UpdateFirstPartyStorageTrackers, + weak_factory_io_thread_.GetWeakPtr(), + std::move(storage_trackers))); +} + +void TrackingProtectionService::UpdateFirstPartyStorageTrackers( + std::vector storage_trackers) { first_party_storage_trackers_ = base::flat_set(std::move(storage_trackers)); } + #endif bool TrackingProtectionService::ShouldStoreState(BraveCookieSettings* settings, @@ -220,13 +224,13 @@ bool TrackingProtectionService::ShouldStartRequest( const std::string& tab_host, bool* matching_exception_filter, bool* cancel_request_explicitly) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); // There are no exceptions in the TP service, but exceptions are // combined with brave/ad-block. if (matching_exception_filter) { *matching_exception_filter = false; } // Intentionally don't set cancel_request_explicitly - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::string host = url.host(); if (!tracking_protection_client_->matchesTracker(tab_host.c_str(), host.c_str())) { @@ -251,55 +255,70 @@ bool TrackingProtectionService::ShouldStartRequest( return false; } -void TrackingProtectionService::OnDATFileDataReady() { - if (buffer_.empty()) { +void TrackingProtectionService::OnGetDATFileData(GetDATFileDataResult result) { + if (result.second.empty()) { LOG(ERROR) << "Could not obtain tracking protection data"; return; } - tracking_protection_client_.reset(new CTPParser()); - if (!tracking_protection_client_->deserialize( - reinterpret_cast(&buffer_.front()))) { - tracking_protection_client_.reset(); + if (!result.first.get()) { LOG(ERROR) << "Failed to deserialize tracking protection data"; return; } + + base::PostTaskWithTraits( + FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&TrackingProtectionService::UpdateTrackingProtectionClient, + weak_factory_io_thread_.GetWeakPtr(), + std::move(result.first), + std::move(result.second))); +} + +void TrackingProtectionService::UpdateTrackingProtectionClient( + std::unique_ptr tracking_protection_client, + brave_component_updater::DATFileDataBuffer buffer) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + tracking_protection_client_ = std::move(tracking_protection_client); + buffer_ = std::move(buffer); } void TrackingProtectionService::OnComponentReady( const std::string& component_id, const base::FilePath& install_dir, const std::string& manifest) { - base::FilePath navigation_tracking_protection_path = - install_dir.AppendASCII(kDatFileVersion) - .AppendASCII(kNavigationTrackersFile); + base::FilePath navigation_tracking_protection_path = install_dir + .AppendASCII(kDatFileVersion) + .AppendASCII(kNavigationTrackersFile); - GetTaskRunner()->PostTaskAndReply( + base::PostTaskAndReplyWithResult( + local_data_files_service()->GetTaskRunner().get(), FROM_HERE, - base::Bind(&GetDATFileData, navigation_tracking_protection_path, - &buffer_), - base::Bind(&TrackingProtectionService::OnDATFileDataReady, - weak_factory_.GetWeakPtr())); + base::BindOnce(&brave_component_updater::LoadDATFileData, + navigation_tracking_protection_path), + base::BindOnce(&TrackingProtectionService::OnGetDATFileData, + weak_factory_.GetWeakPtr())); #if BUILDFLAG(BRAVE_STP_ENABLED) if (!TrackingProtectionHelper::IsSmartTrackingProtectionEnabled()) { return; } - base::FilePath storage_tracking_protection_path = - install_dir.AppendASCII(kDatFileVersion) - .AppendASCII(kStorageTrackersFile); + base::FilePath storage_tracking_protection_path = install_dir + .AppendASCII(kDatFileVersion) + .AppendASCII(kStorageTrackersFile); - GetTaskRunner()->PostTaskAndReply( + base::PostTaskAndReplyWithResult( + local_data_files_service()->GetTaskRunner().get(), FROM_HERE, - base::Bind(&GetDATFileData, storage_tracking_protection_path, - &storage_trackers_buffer_), - base::Bind(&TrackingProtectionService::ParseStorageTrackersData, - weak_factory_.GetWeakPtr())); + base::BindOnce(&brave_component_updater::GetDATFileAsString, + storage_tracking_protection_path), + base::BindOnce(&TrackingProtectionService::OnGetSTPDATFileData, + weak_factory_.GetWeakPtr())); #endif } // Ported from Android: net/blockers/blockers_worker.cc std::vector TrackingProtectionService::GetThirdPartyHosts( const std::string& base_host) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); { base::AutoLock guard(third_party_hosts_lock_); std::map>::const_iterator iter = @@ -353,21 +372,12 @@ std::vector TrackingProtectionService::GetThirdPartyHosts( return hosts; } -scoped_refptr -TrackingProtectionService::GetTaskRunner() { - // We share the same task runner for all ad-block and TP code - return g_brave_browser_process->ad_block_service()->GetTaskRunner(); -} - /////////////////////////////////////////////////////////////////////////////// -// The tracking protection factory. Using the Brave Shields as a singleton -// is the job of the browser process. -std::unique_ptr TrackingProtectionServiceFactory() { +std::unique_ptr TrackingProtectionServiceFactory( + LocalDataFilesService* local_data_files_service) { std::unique_ptr service = - std::make_unique(); - g_brave_browser_process->local_data_files_service()->AddObserver( - service.get()); + std::make_unique(local_data_files_service); return service; } diff --git a/components/brave_shields/browser/tracking_protection_service.h b/components/brave_shields/browser/tracking_protection_service.h index fde162479211..7a3038bb0213 100644 --- a/components/brave_shields/browser/tracking_protection_service.h +++ b/components/brave_shields/browser/tracking_protection_service.h @@ -6,24 +6,20 @@ #ifndef BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_TRACKING_PROTECTION_SERVICE_H_ #define BRAVE_COMPONENTS_BRAVE_SHIELDS_BROWSER_TRACKING_PROTECTION_SERVICE_H_ -#include - #include #include -// TODO(brave): is an unapproved C++11 header -#include // NOLINT #include +#include #include #include "base/containers/flat_set.h" #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" -#include "base/sequence_checker.h" #include "base/sequenced_task_runner.h" #include "base/synchronization/lock.h" -#include "brave/components/brave_shields/browser/base_local_data_files_observer.h" +#include "brave/components/brave_component_updater/browser/dat_file_util.h" +#include "brave/components/brave_component_updater/browser/local_data_files_observer.h" #include "brave/components/brave_shields/browser/buildflags/buildflags.h" // For STP -#include "brave/components/brave_shields/browser/dat_file_util.h" #include "content/public/common/resource_type.h" #include "url/gurl.h" @@ -35,12 +31,19 @@ namespace content_settings { class BraveCookieSettings; } +using brave_component_updater::LocalDataFilesObserver; +using brave_component_updater::LocalDataFilesService; + namespace brave_shields { // The brave shields service in charge of tracking protection and init. -class TrackingProtectionService : public BaseLocalDataFilesObserver { +class TrackingProtectionService : public LocalDataFilesObserver { public: - TrackingProtectionService(); + using GetDATFileDataResult = + brave_component_updater::LoadDATFileDataResult; + + explicit TrackingProtectionService( + LocalDataFilesService* local_data_files_service); ~TrackingProtectionService() override; bool ShouldStartRequest(const GURL& spec, @@ -57,9 +60,7 @@ class TrackingProtectionService : public BaseLocalDataFilesObserver { const GURL& first_party_url, const GURL& tab_url) const; - scoped_refptr GetTaskRunner(); - - // implementation of BaseLocalDataFilesObserver + // implementation of LocalDataFilesObserver void OnComponentReady(const std::string& component_id, const base::FilePath& install_dir, const std::string& manifest) override; @@ -91,7 +92,8 @@ class TrackingProtectionService : public BaseLocalDataFilesObserver { #if BUILDFLAG(BRAVE_STP_ENABLED) // ParseStorageTrackersData parses the storage trackers list provided by // the offline-crawler - void ParseStorageTrackersData(); + void OnGetSTPDATFileData(std::string contents); + void UpdateFirstPartyStorageTrackers(std::vector); // For Smart Tracking Protection, we need to keep track of the starting site // that initiated the redirects. We use RenderFrameIdKey to determine the @@ -109,29 +111,31 @@ class TrackingProtectionService : public BaseLocalDataFilesObserver { #endif private: - void OnDATFileDataReady(); + void OnGetDATFileData(GetDATFileDataResult result); + void UpdateTrackingProtectionClient( + std::unique_ptr tracking_protection_client, + brave_component_updater::DATFileDataBuffer); std::vector GetThirdPartyHosts(const std::string& base_host); #if BUILDFLAG(BRAVE_STP_ENABLED) base::flat_set first_party_storage_trackers_; std::map render_frame_key_to_starting_site_url; - - brave_shields::DATFileDataBuffer storage_trackers_buffer_; #endif - brave_shields::DATFileDataBuffer buffer_; std::unique_ptr tracking_protection_client_; std::vector third_party_base_hosts_; std::map> third_party_hosts_cache_; base::Lock third_party_hosts_lock_; + brave_component_updater::DATFileDataBuffer buffer_; - SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory weak_factory_; + base::WeakPtrFactory weak_factory_io_thread_; DISALLOW_COPY_AND_ASSIGN(TrackingProtectionService); }; // Creates the TrackingProtectionService -std::unique_ptr TrackingProtectionServiceFactory(); +std::unique_ptr TrackingProtectionServiceFactory( + LocalDataFilesService* local_data_files_service); } // namespace brave_shields diff --git a/components/brave_shields/browser/tracking_protection_service_browsertest.cc b/components/brave_shields/browser/tracking_protection_service_browsertest.cc index d9bee6abff3e..0d347b5b3c0a 100644 --- a/components/brave_shields/browser/tracking_protection_service_browsertest.cc +++ b/components/brave_shields/browser/tracking_protection_service_browsertest.cc @@ -11,7 +11,7 @@ #include "brave/common/brave_paths.h" #include "brave/common/pref_names.h" #include "brave/components/brave_shields/browser/buildflags/buildflags.h" // For STP -#include "brave/components/brave_shields/browser/local_data_files_service.h" +#include "brave/components/brave_component_updater/browser/local_data_files_service.h" #include "brave/components/brave_shields/browser/tracking_protection_service.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/net/url_request_mock_util.h" @@ -19,6 +19,7 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" #include "content/public/test/browser_test_utils.h" #include "net/dns/mock_host_resolver.h" @@ -33,6 +34,7 @@ const char kRedirectPage[] = "/client-redirect?"; const char kStoragePage[] = "/storage.html"; #endif +using content::BrowserThread; using extensions::ExtensionBrowserTest; const char kTrackingPage[] = "/tracking.html"; @@ -77,7 +79,7 @@ class TrackingProtectionServiceTest : public ExtensionBrowserTest { void SetUpOnMainThread() override { ExtensionBrowserTest::SetUpOnMainThread(); base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, + FROM_HERE, {BrowserThread::IO}, base::BindOnce(&chrome_browser_net::SetUrlRequestMocksEnabled, true)); host_resolver()->AddRule("*", "127.0.0.1"); } @@ -99,7 +101,7 @@ class TrackingProtectionServiceTest : public ExtensionBrowserTest { } void InitService() { - brave_shields::LocalDataFilesService:: + brave_component_updater::LocalDataFilesService:: SetComponentIdAndBase64PublicKeyForTest( kTrackingProtectionComponentTestId, kTrackingProtectionComponentTestBase64PublicKey); @@ -128,9 +130,12 @@ class TrackingProtectionServiceTest : public ExtensionBrowserTest { } void WaitForTrackingProtectionServiceThread() { + scoped_refptr tr_helper(new base::ThreadTestHelper( + g_brave_browser_process->local_data_files_service()->GetTaskRunner())); + ASSERT_TRUE(tr_helper->Run()); scoped_refptr io_helper(new base::ThreadTestHelper( - g_brave_browser_process->tracking_protection_service() - ->GetTaskRunner())); + base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}) + .get())); ASSERT_TRUE(io_helper->Run()); } };