diff options
| author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2020-01-20 13:40:20 +0100 |
|---|---|---|
| committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2020-01-22 12:41:23 +0000 |
| commit | 7961cea6d1041e3e454dae6a1da660b453efd238 (patch) | |
| tree | c0eeb4a9ff9ba32986289c1653d9608e53ccb444 /chromium/extensions/browser | |
| parent | b7034d0803538058e5c9d904ef03cf5eab34f6ef (diff) | |
| download | qtwebengine-chromium-7961cea6d1041e3e454dae6a1da660b453efd238.tar.gz | |
BASELINE: Update Chromium to 78.0.3904.130
Change-Id: If185e0c0061b3437531c97c9c8c78f239352a68b
Reviewed-by: Allan Sandfeld Jensen <allan.jensen@qt.io>
Diffstat (limited to 'chromium/extensions/browser')
382 files changed, 3889 insertions, 3539 deletions
diff --git a/chromium/extensions/browser/BUILD.gn b/chromium/extensions/browser/BUILD.gn index a4f05021eb9..9ad769b7a3f 100644 --- a/chromium/extensions/browser/BUILD.gn +++ b/chromium/extensions/browser/BUILD.gn @@ -86,6 +86,7 @@ jumbo_source_set("browser_sources") { "content_verifier/content_hash.cc", "content_verifier/content_hash.h", "content_verifier/content_verifier_key.h", + "content_verifier/scoped_uma_recorder.h", "content_verifier_delegate.h", "content_verifier_io_data.cc", "content_verifier_io_data.h", @@ -213,12 +214,6 @@ jumbo_source_set("browser_sources") { "guest_view/extension_options/extension_options_guest.h", "guest_view/extension_options/extension_options_guest_delegate.cc", "guest_view/extension_options/extension_options_guest_delegate.h", - "guest_view/extension_view/extension_view_constants.cc", - "guest_view/extension_view/extension_view_constants.h", - "guest_view/extension_view/extension_view_guest.cc", - "guest_view/extension_view/extension_view_guest.h", - "guest_view/extension_view/whitelist/extension_view_whitelist.cc", - "guest_view/extension_view/whitelist/extension_view_whitelist.h", "guest_view/extensions_guest_view_manager_delegate.cc", "guest_view/extensions_guest_view_manager_delegate.h", "guest_view/extensions_guest_view_message_filter.cc", @@ -343,6 +338,8 @@ jumbo_source_set("browser_sources") { "state_store.h", "suggest_permission_util.cc", "suggest_permission_util.h", + "task_queue_util.cc", + "task_queue_util.h", "uninstall_ping_sender.cc", "uninstall_ping_sender.h", "uninstall_reason.h", @@ -380,6 +377,7 @@ jumbo_source_set("browser_sources") { "//components/keyed_service/core", "//components/pref_registry", "//components/prefs", + "//components/services/unzip/content", "//components/services/unzip/public/cpp", "//components/sessions", "//components/sync", @@ -416,6 +414,11 @@ jumbo_source_set("browser_sources") { "//ipc", ] + if (is_mac) { + # For LSCopyDisplayNameForURL, path_util.cc. + libs = [ "CoreServices.framework" ] + } + configs += [ "//build/config:precompiled_headers", @@ -575,7 +578,6 @@ source_set("unit_tests") { "api/declarative/deduping_factory_unittest.cc", "api/declarative/rules_registry_unittest.cc", "api/declarative_net_request/composite_matcher_unittest.cc", - "api/declarative_net_request/declarative_net_request_api_unittest.cc", "api/declarative_net_request/file_sequence_helper_unittest.cc", "api/declarative_net_request/flat_ruleset_indexer_unittest.cc", "api/declarative_net_request/indexed_rule_unittest.cc", @@ -624,6 +626,7 @@ source_set("unit_tests") { "extension_pref_value_map_unittest.cc", "extension_registrar_unittest.cc", "extension_registry_unittest.cc", + "extension_util_unittest.cc", "file_highlighter_unittest.cc", "file_reader_unittest.cc", "image_loader_unittest.cc", @@ -674,8 +677,8 @@ source_set("unit_tests") { "//components/onc", "//components/pref_registry:pref_registry", "//components/prefs:test_support", - "//components/services/unzip:lib", - "//components/services/unzip/public/cpp:test_support", + "//components/services/unzip:in_process", + "//components/services/unzip/content", "//components/sync_preferences:test_support", "//components/update_client", "//components/url_matcher", diff --git a/chromium/extensions/browser/DEPS b/chromium/extensions/browser/DEPS index b9b9c3d946e..30f20f54803 100644 --- a/chromium/extensions/browser/DEPS +++ b/chromium/extensions/browser/DEPS @@ -3,6 +3,7 @@ include_rules = [ "+components/guest_view", "+components/keyed_service", "+components/pref_registry", + "+components/services/unzip/content", "+components/services/unzip/public", "+components/sessions", "+components/signin/public", diff --git a/chromium/extensions/browser/api/BUILD.gn b/chromium/extensions/browser/api/BUILD.gn index 133e877fe06..d3940980c82 100644 --- a/chromium/extensions/browser/api/BUILD.gn +++ b/chromium/extensions/browser/api/BUILD.gn @@ -26,8 +26,6 @@ source_set("api") { "extensions_api_client.h", "guest_view/app_view/app_view_guest_internal_api.cc", "guest_view/app_view/app_view_guest_internal_api.h", - "guest_view/extension_view/extension_view_internal_api.cc", - "guest_view/extension_view/extension_view_internal_api.h", "guest_view/guest_view_internal_api.cc", "guest_view/guest_view_internal_api.h", "guest_view/web_view/web_view_internal_api.cc", diff --git a/chromium/extensions/browser/api/OWNERS b/chromium/extensions/browser/api/OWNERS index 7eafe922486..cdd8f14e020 100644 --- a/chromium/extensions/browser/api/OWNERS +++ b/chromium/extensions/browser/api/OWNERS @@ -1,2 +1,3 @@ # For Chrome OS apps APIs. tbarzic@chromium.org +# COMPONENT: Platform>Extensions>API diff --git a/chromium/extensions/browser/api/alarms/alarm_manager.cc b/chromium/extensions/browser/api/alarms/alarm_manager.cc index 4129bb3fc8a..12db37d6868 100644 --- a/chromium/extensions/browser/api/alarms/alarm_manager.cc +++ b/chromium/extensions/browser/api/alarms/alarm_manager.cc @@ -19,7 +19,6 @@ #include "base/values.h" #include "extensions/browser/api/alarms/alarms_api_constants.h" #include "extensions/browser/event_router.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_factory.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/state_store.h" @@ -114,8 +113,7 @@ std::unique_ptr<base::ListValue> AlarmsToValue( AlarmManager::AlarmManager(content::BrowserContext* context) : browser_context_(context), clock_(base::DefaultClock::GetInstance()), - delegate_(new DefaultAlarmDelegate(context)), - extension_registry_observer_(this) { + delegate_(new DefaultAlarmDelegate(context)) { extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_)); StateStore* storage = ExtensionSystem::Get(browser_context_)->state_store(); diff --git a/chromium/extensions/browser/api/alarms/alarm_manager.h b/chromium/extensions/browser/api/alarms/alarm_manager.h index ab84025acdb..93b1481ea24 100644 --- a/chromium/extensions/browser/api/alarms/alarm_manager.h +++ b/chromium/extensions/browser/api/alarms/alarm_manager.h @@ -17,6 +17,7 @@ #include "base/scoped_observer.h" #include "base/timer/timer.h" #include "extensions/browser/browser_context_keyed_api_factory.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/common/api/alarms.h" #include "extensions/common/extension_id.h" @@ -31,7 +32,6 @@ class BrowserContext; namespace extensions { class ExtensionAlarmsSchedulingTest; -class ExtensionRegistry; struct Alarm { Alarm(); @@ -225,7 +225,7 @@ class AlarmManager : public BrowserContextKeyedAPI, // Listen to extension load notifications. ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; // The timer for this alarm manager. base::OneShotTimer timer_; diff --git a/chromium/extensions/browser/api/alarms/alarms_api.h b/chromium/extensions/browser/api/alarms/alarms_api.h index 20f5cd51e99..8b2a40693ed 100644 --- a/chromium/extensions/browser/api/alarms/alarms_api.h +++ b/chromium/extensions/browser/api/alarms/alarms_api.h @@ -17,7 +17,7 @@ namespace extensions { struct Alarm; using AlarmList = std::vector<std::unique_ptr<Alarm>>; -class AlarmsCreateFunction : public UIThreadExtensionFunction { +class AlarmsCreateFunction : public ExtensionFunction { public: AlarmsCreateFunction(); // Use |clock| instead of the default clock. Does not take ownership @@ -27,7 +27,7 @@ class AlarmsCreateFunction : public UIThreadExtensionFunction { protected: ~AlarmsCreateFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("alarms.create", ALARMS_CREATE) private: @@ -36,11 +36,11 @@ class AlarmsCreateFunction : public UIThreadExtensionFunction { base::Clock* const clock_; }; -class AlarmsGetFunction : public UIThreadExtensionFunction { +class AlarmsGetFunction : public ExtensionFunction { protected: ~AlarmsGetFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -48,11 +48,11 @@ class AlarmsGetFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("alarms.get", ALARMS_GET) }; -class AlarmsGetAllFunction : public UIThreadExtensionFunction { +class AlarmsGetAllFunction : public ExtensionFunction { protected: ~AlarmsGetAllFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -60,11 +60,11 @@ class AlarmsGetAllFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("alarms.getAll", ALARMS_GETALL) }; -class AlarmsClearFunction : public UIThreadExtensionFunction { +class AlarmsClearFunction : public ExtensionFunction { protected: ~AlarmsClearFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -72,11 +72,11 @@ class AlarmsClearFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("alarms.clear", ALARMS_CLEAR) }; -class AlarmsClearAllFunction : public UIThreadExtensionFunction { +class AlarmsClearAllFunction : public ExtensionFunction { protected: ~AlarmsClearAllFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: diff --git a/chromium/extensions/browser/api/api_resource_manager.h b/chromium/extensions/browser/api/api_resource_manager.h index ca038e049b6..ae047659934 100644 --- a/chromium/extensions/browser/api/api_resource_manager.h +++ b/chromium/extensions/browser/api/api_resource_manager.h @@ -54,7 +54,7 @@ struct NamedThreadTraits { } static scoped_refptr<base::SequencedTaskRunner> GetSequencedTaskRunner() { - return base::CreateSingleThreadTaskRunnerWithTraits({T::kThreadId}); + return base::CreateSingleThreadTaskRunner({T::kThreadId}); } }; @@ -105,9 +105,7 @@ class ApiResourceManager : public BrowserContextKeyedAPI, public ProcessManagerObserver { public: explicit ApiResourceManager(content::BrowserContext* context) - : data_(new ApiResourceData()), - extension_registry_observer_(this), - process_manager_observer_(this) { + : data_(base::MakeRefCounted<ApiResourceData>()) { extension_registry_observer_.Add(ExtensionRegistry::Get(context)); process_manager_observer_.Add(ProcessManager::Get(context)); } @@ -378,9 +376,9 @@ class ApiResourceManager : public BrowserContextKeyedAPI, scoped_refptr<ApiResourceData> data_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; ScopedObserver<ProcessManager, ProcessManagerObserver> - process_manager_observer_; + process_manager_observer_{this}; SEQUENCE_CHECKER(sequence_checker_); }; diff --git a/chromium/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.cc b/chromium/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.cc index 354fe40109b..33a1d4819f2 100644 --- a/chromium/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.cc +++ b/chromium/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.cc @@ -124,7 +124,7 @@ BoundsType GetBoundsType(const std::string& type_as_string) { bool AppCurrentWindowInternalExtensionFunction::PreRunValidation( std::string* error) { - if (!UIThreadExtensionFunction::PreRunValidation(error)) + if (!ExtensionFunction::PreRunValidation(error)) return false; AppWindowRegistry* registry = AppWindowRegistry::Get(browser_context()); diff --git a/chromium/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.h b/chromium/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.h index 72ddd534a5a..4f69356b738 100644 --- a/chromium/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.h +++ b/chromium/extensions/browser/api/app_current_window_internal/app_current_window_internal_api.h @@ -11,8 +11,7 @@ namespace extensions { class AppWindow; -class AppCurrentWindowInternalExtensionFunction - : public UIThreadExtensionFunction { +class AppCurrentWindowInternalExtensionFunction : public ExtensionFunction { protected: ~AppCurrentWindowInternalExtensionFunction() override {} diff --git a/chromium/extensions/browser/api/app_window/app_window_api.h b/chromium/extensions/browser/api/app_window/app_window_api.h index e8511581b72..2a34681d0fd 100644 --- a/chromium/extensions/browser/api/app_window/app_window_api.h +++ b/chromium/extensions/browser/api/app_window/app_window_api.h @@ -16,7 +16,7 @@ struct CreateWindowOptions; } } -class AppWindowCreateFunction : public UIThreadExtensionFunction { +class AppWindowCreateFunction : public ExtensionFunction { public: AppWindowCreateFunction(); DECLARE_EXTENSION_FUNCTION("app.window.create", APP_WINDOW_CREATE) diff --git a/chromium/extensions/browser/api/async_api_function.cc b/chromium/extensions/browser/api/async_api_function.cc index efc60cbff17..5e5441fa6b0 100644 --- a/chromium/extensions/browser/api/async_api_function.cc +++ b/chromium/extensions/browser/api/async_api_function.cc @@ -17,7 +17,7 @@ namespace extensions { // AsyncApiFunction AsyncApiFunction::AsyncApiFunction() : work_task_runner_( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})) {} + base::CreateSingleThreadTaskRunner({BrowserThread::IO})) {} AsyncApiFunction::~AsyncApiFunction() {} @@ -58,7 +58,7 @@ ExtensionFunction::ResponseAction AsyncApiFunction::Run() { void AsyncApiFunction::AsyncWorkCompleted() { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - bool rv = base::PostTaskWithTraits( + bool rv = base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&AsyncApiFunction::RespondOnUIThread, this)); DCHECK(rv); @@ -81,7 +81,7 @@ void AsyncApiFunction::SetError(const std::string& error) { } const std::string& AsyncApiFunction::GetError() const { - return error_.empty() ? UIThreadExtensionFunction::GetError() : error_; + return error_.empty() ? ExtensionFunction::GetError() : error_; } void AsyncApiFunction::WorkOnWorkThread() { @@ -102,7 +102,7 @@ void AsyncApiFunction::SendResponse(bool success) { response = results_ ? ErrorWithArguments(std::move(results_), error_) : Error(error_); } - UIThreadExtensionFunction::Respond(std::move(response)); + ExtensionFunction::Respond(std::move(response)); } } // namespace extensions diff --git a/chromium/extensions/browser/api/async_api_function.h b/chromium/extensions/browser/api/async_api_function.h index 222de6f762c..80079912b60 100644 --- a/chromium/extensions/browser/api/async_api_function.h +++ b/chromium/extensions/browser/api/async_api_function.h @@ -13,7 +13,7 @@ namespace extensions { // AsyncApiFunction provides convenient thread management for APIs that need to // do essentially all their work on a thread other than the UI thread. -class AsyncApiFunction : public UIThreadExtensionFunction { +class AsyncApiFunction : public ExtensionFunction { protected: AsyncApiFunction(); ~AsyncApiFunction() override; @@ -36,7 +36,7 @@ class AsyncApiFunction : public UIThreadExtensionFunction { // Respond. Guaranteed to happen on UI thread. virtual bool Respond() = 0; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() final; protected: diff --git a/chromium/extensions/browser/api/audio/audio_api.cc b/chromium/extensions/browser/api/audio/audio_api.cc index 939d8649bd2..79c7672eaf8 100644 --- a/chromium/extensions/browser/api/audio/audio_api.cc +++ b/chromium/extensions/browser/api/audio/audio_api.cc @@ -47,7 +47,8 @@ bool CanUseDeprecatedAudioApi(const Extension* extension) { .is_available(); } -bool CanReceiveDeprecatedAudioEvent(content::BrowserContext* context, +bool CanReceiveDeprecatedAudioEvent(content::BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* filter) { diff --git a/chromium/extensions/browser/api/audio/audio_api.h b/chromium/extensions/browser/api/audio/audio_api.h index fe070041ccd..7316913405d 100644 --- a/chromium/extensions/browser/api/audio/audio_api.h +++ b/chromium/extensions/browser/api/audio/audio_api.h @@ -56,7 +56,7 @@ class AudioAPI : public BrowserContextKeyedAPI, public AudioService::Observer { DISALLOW_COPY_AND_ASSIGN(AudioAPI); }; -class AudioGetInfoFunction : public UIThreadExtensionFunction { +class AudioGetInfoFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("audio.getInfo", AUDIO_GETINFO) @@ -65,7 +65,7 @@ class AudioGetInfoFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class AudioGetDevicesFunction : public UIThreadExtensionFunction { +class AudioGetDevicesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("audio.getDevices", AUDIO_GETDEVICES) @@ -74,7 +74,7 @@ class AudioGetDevicesFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class AudioSetActiveDevicesFunction : public UIThreadExtensionFunction { +class AudioSetActiveDevicesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("audio.setActiveDevices", AUDIO_SETACTIVEDEVICES) @@ -83,7 +83,7 @@ class AudioSetActiveDevicesFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class AudioSetPropertiesFunction : public UIThreadExtensionFunction { +class AudioSetPropertiesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("audio.setProperties", AUDIO_SETPROPERTIES) @@ -92,7 +92,7 @@ class AudioSetPropertiesFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class AudioSetMuteFunction : public UIThreadExtensionFunction { +class AudioSetMuteFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("audio.setMute", AUDIO_SETMUTE) @@ -101,7 +101,7 @@ class AudioSetMuteFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class AudioGetMuteFunction : public UIThreadExtensionFunction { +class AudioGetMuteFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("audio.getMute", AUDIO_GETMUTE) diff --git a/chromium/extensions/browser/api/audio/audio_device_id_calculator_unittest.cc b/chromium/extensions/browser/api/audio/audio_device_id_calculator_unittest.cc index 287dcdc9288..ef21a8dce63 100644 --- a/chromium/extensions/browser/api/audio/audio_device_id_calculator_unittest.cc +++ b/chromium/extensions/browser/api/audio/audio_device_id_calculator_unittest.cc @@ -3,9 +3,10 @@ // found in the LICENSE file. #include "extensions/browser/api/audio/audio_device_id_calculator.h" + #include "components/prefs/testing_pref_service.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "extensions/browser/api/audio/audio_api.h" #include "extensions/browser/test_extensions_browser_client.h" #include "testing/gtest/include/gtest/gtest.h" @@ -52,7 +53,7 @@ class AudioDeviceIdCalculatorTest : public testing::Test { content::BrowserContext* browser_context() { return &browser_context_; } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; content::TestBrowserContext browser_context_; TestExtensionsBrowserClientWithPrefService test_browser_client_; diff --git a/chromium/extensions/browser/api/audio/audio_service_chromeos.cc b/chromium/extensions/browser/api/audio/audio_service_chromeos.cc index 1128ab24c19..9bcb77149a4 100644 --- a/chromium/extensions/browser/api/audio/audio_service_chromeos.cc +++ b/chromium/extensions/browser/api/audio/audio_service_chromeos.cc @@ -123,15 +123,14 @@ class AudioServiceImpl : public AudioService, // Note: This should remain the last member so it'll be destroyed and // invalidate the weak pointers before any other members are destroyed. - base::WeakPtrFactory<AudioServiceImpl> weak_ptr_factory_; + base::WeakPtrFactory<AudioServiceImpl> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AudioServiceImpl); }; AudioServiceImpl::AudioServiceImpl(AudioDeviceIdCalculator* id_calculator) : cras_audio_handler_(chromeos::CrasAudioHandler::Get()), - id_calculator_(id_calculator), - weak_ptr_factory_(this) { + id_calculator_(id_calculator) { CHECK(id_calculator_); if (cras_audio_handler_) diff --git a/chromium/extensions/browser/api/automation_internal/automation_internal_api.h b/chromium/extensions/browser/api/automation_internal/automation_internal_api.h index 45c6ddaaf4a..afb052f372c 100644 --- a/chromium/extensions/browser/api/automation_internal/automation_internal_api.h +++ b/chromium/extensions/browser/api/automation_internal/automation_internal_api.h @@ -29,7 +29,7 @@ struct AXActionData; namespace extensions { // Implementation of the chrome.automation API. -class AutomationInternalEnableTabFunction : public UIThreadExtensionFunction { +class AutomationInternalEnableTabFunction : public ExtensionFunction { DECLARE_EXTENSION_FUNCTION("automationInternal.enableTab", AUTOMATIONINTERNAL_ENABLETAB) protected: @@ -38,8 +38,7 @@ class AutomationInternalEnableTabFunction : public UIThreadExtensionFunction { ExtensionFunction::ResponseAction Run() override; }; -class AutomationInternalPerformActionFunction - : public UIThreadExtensionFunction { +class AutomationInternalPerformActionFunction : public ExtensionFunction { DECLARE_EXTENSION_FUNCTION("automationInternal.performAction", AUTOMATIONINTERNAL_PERFORMACTION) protected: @@ -54,7 +53,7 @@ class AutomationInternalPerformActionFunction ui::AXActionData* data); }; -class AutomationInternalEnableFrameFunction : public UIThreadExtensionFunction { +class AutomationInternalEnableFrameFunction : public ExtensionFunction { DECLARE_EXTENSION_FUNCTION("automationInternal.enableFrame", AUTOMATIONINTERNAL_ENABLEFRAME) @@ -64,8 +63,7 @@ class AutomationInternalEnableFrameFunction : public UIThreadExtensionFunction { ExtensionFunction::ResponseAction Run() override; }; -class AutomationInternalEnableDesktopFunction - : public UIThreadExtensionFunction { +class AutomationInternalEnableDesktopFunction : public ExtensionFunction { DECLARE_EXTENSION_FUNCTION("automationInternal.enableDesktop", AUTOMATIONINTERNAL_ENABLEDESKTOP) protected: @@ -74,8 +72,7 @@ class AutomationInternalEnableDesktopFunction ResponseAction Run() override; }; -class AutomationInternalQuerySelectorFunction - : public UIThreadExtensionFunction { +class AutomationInternalQuerySelectorFunction : public ExtensionFunction { DECLARE_EXTENSION_FUNCTION("automationInternal.querySelector", AUTOMATIONINTERNAL_QUERYSELECTOR) diff --git a/chromium/extensions/browser/api/automation_internal/automation_internal_api_delegate.h b/chromium/extensions/browser/api/automation_internal/automation_internal_api_delegate.h index 485aaeae9d9..11668fc0e8d 100644 --- a/chromium/extensions/browser/api/automation_internal/automation_internal_api_delegate.h +++ b/chromium/extensions/browser/api/automation_internal/automation_internal_api_delegate.h @@ -10,7 +10,7 @@ #include "extensions/common/extension_id.h" #include "extensions/common/extension_messages.h" -class UIThreadExtensionFunction; +class ExtensionFunction; namespace extensions { class AutomationInternalApiDelegate; @@ -52,7 +52,7 @@ class AutomationInternalApiDelegate { virtual int GetTabId(content::WebContents* contents) = 0; // Retrieves the active web contents. virtual content::WebContents* GetActiveWebContents( - UIThreadExtensionFunction* function) = 0; + ExtensionFunction* function) = 0; // Starts managing automation nodes on the desktop. virtual void EnableDesktop() = 0; // Gets the ax tree id for the nodes being managed for the desktop. diff --git a/chromium/extensions/browser/api/bluetooth/bluetooth_api.cc b/chromium/extensions/browser/api/bluetooth/bluetooth_api.cc index f4df9a0304c..ca254b92200 100644 --- a/chromium/extensions/browser/api/bluetooth/bluetooth_api.cc +++ b/chromium/extensions/browser/api/bluetooth/bluetooth_api.cc @@ -31,7 +31,7 @@ using content::BrowserThread; using device::BluetoothAdapter; using device::BluetoothDevice; -namespace bluetooth = extensions::api::bluetooth; +namespace bluetooth_api = extensions::api::bluetooth; namespace GetDevice = extensions::api::bluetooth::GetDevice; namespace GetDevices = extensions::api::bluetooth::GetDevices; @@ -72,11 +72,14 @@ BluetoothAPI::BluetoothAPI(content::BrowserContext* context) DCHECK_CURRENTLY_ON(BrowserThread::UI); BLUETOOTH_LOG(EVENT) << "BluetoothAPI: " << browser_context_; EventRouter* event_router = EventRouter::Get(browser_context_); + event_router->RegisterObserver( + this, bluetooth_api::OnAdapterStateChanged::kEventName); event_router->RegisterObserver(this, - bluetooth::OnAdapterStateChanged::kEventName); - event_router->RegisterObserver(this, bluetooth::OnDeviceAdded::kEventName); - event_router->RegisterObserver(this, bluetooth::OnDeviceChanged::kEventName); - event_router->RegisterObserver(this, bluetooth::OnDeviceRemoved::kEventName); + bluetooth_api::OnDeviceAdded::kEventName); + event_router->RegisterObserver(this, + bluetooth_api::OnDeviceChanged::kEventName); + event_router->RegisterObserver(this, + bluetooth_api::OnDeviceRemoved::kEventName); } BluetoothAPI::~BluetoothAPI() { @@ -116,9 +119,9 @@ BluetoothGetAdapterStateFunction::~BluetoothGetAdapterStateFunction() = default; void BluetoothGetAdapterStateFunction::DoWork( scoped_refptr<BluetoothAdapter> adapter) { - bluetooth::AdapterState state; + bluetooth_api::AdapterState state; PopulateAdapterState(*adapter, &state); - Respond(ArgumentList(bluetooth::GetAdapterState::Results::Create(state))); + Respond(ArgumentList(bluetooth_api::GetAdapterState::Results::Create(state))); } BluetoothGetDevicesFunction::BluetoothGetDevicesFunction() = default; @@ -139,7 +142,8 @@ void BluetoothGetDevicesFunction::DoWork( BluetoothAdapter::DeviceList devices; #if defined(OS_CHROMEOS) // Default filter values. - bluetooth::FilterType filter_type = bluetooth::FilterType::FILTER_TYPE_ALL; + bluetooth_api::FilterType filter_type = + bluetooth_api::FilterType::FILTER_TYPE_ALL; int limit = 0; /*no limit*/ if (params_->filter) { filter_type = params_->filter->filter_type; @@ -159,8 +163,8 @@ void BluetoothGetDevicesFunction::DoWork( const BluetoothDevice* device = *iter; DCHECK(device); - bluetooth::Device extension_device; - bluetooth::BluetoothDeviceToApiDevice(*device, &extension_device); + bluetooth_api::Device extension_device; + bluetooth_api::BluetoothDeviceToApiDevice(*device, &extension_device); device_list->Append(extension_device.ToValue()); } @@ -183,8 +187,8 @@ void BluetoothGetDeviceFunction::DoWork( BluetoothDevice* device = adapter->GetDevice(params_->device_address); if (device) { - bluetooth::Device extension_device; - bluetooth::BluetoothDeviceToApiDevice(*device, &extension_device); + bluetooth_api::Device extension_device; + bluetooth_api::BluetoothDeviceToApiDevice(*device, &extension_device); Respond(OneArgument(extension_device.ToValue())); } else { Respond(Error(kInvalidDevice)); diff --git a/chromium/extensions/browser/api/bluetooth/bluetooth_api_utils.cc b/chromium/extensions/browser/api/bluetooth/bluetooth_api_utils.cc index 8f352df820b..3d73eb42730 100644 --- a/chromium/extensions/browser/api/bluetooth/bluetooth_api_utils.cc +++ b/chromium/extensions/browser/api/bluetooth/bluetooth_api_utils.cc @@ -159,10 +159,12 @@ void BluetoothDeviceToApiDevice(const device::BluetoothDevice& device, else out->inquiry_tx_power.reset(); +#if defined(OS_CHROMEOS) if (device.battery_percentage()) out->battery_percentage.reset(new int(device.battery_percentage().value())); else out->battery_percentage.reset(); +#endif #if defined(OS_LINUX) ConvertTransportToApi(device.GetType(), &(out->transport)); diff --git a/chromium/extensions/browser/api/bluetooth/bluetooth_apitest.cc b/chromium/extensions/browser/api/bluetooth/bluetooth_apitest.cc index 656ae18c2ed..98c65dc2de5 100644 --- a/chromium/extensions/browser/api/bluetooth/bluetooth_apitest.cc +++ b/chromium/extensions/browser/api/bluetooth/bluetooth_apitest.cc @@ -87,18 +87,18 @@ class BluetoothApiTest : public extensions::ExtensionApiTest { false, device::UMABluetoothDiscoverySessionOutcome::SUCCESS); } - void RemoveDiscoverySessionOverride( - device::BluetoothDiscoveryFilter* discovery_filter, - const base::RepeatingClosure& callback, - base::OnceCallback<void(device::UMABluetoothDiscoverySessionOutcome)>& - error_callback) { + void StopScanOverride( + device::BluetoothAdapter::DiscoverySessionResultCallback callback) { if (fail_next_call_) { - std::move(error_callback) - .Run(device::UMABluetoothDiscoverySessionOutcome::UNKNOWN); + std::move(callback).Run( + /*is_error=*/true, + device::UMABluetoothDiscoverySessionOutcome::UNKNOWN); fail_next_call_ = false; return; } - callback.Run(); + std::move(callback).Run( + /*is_error=*/false, + device::UMABluetoothDiscoverySessionOutcome::SUCCESS); } void FailNextCall() { fail_next_call_ = true; } @@ -196,7 +196,6 @@ IN_PROC_BROWSER_TEST_F(BluetoothApiTest, Discovery) { utils::RunFunctionAndReturnError(start_function.get(), "[]", browser())); testing::Mock::VerifyAndClearExpectations(mock_adapter_); - // Simulate successful start discovery EXPECT_CALL(*mock_adapter_, StartScanWithFilter_(_, _)) .WillOnce(Invoke(this, &BluetoothApiTest::StartScanOverride)); @@ -205,23 +204,12 @@ IN_PROC_BROWSER_TEST_F(BluetoothApiTest, Discovery) { extensions::api_test_utils::NONE); testing::Mock::VerifyAndClearExpectations(mock_adapter_); - // Simulate stop discovery with a failure - EXPECT_CALL(*mock_adapter_, RemoveDiscoverySession_(_, _, _)) - .WillOnce( - Invoke(this, &BluetoothApiTest::RemoveDiscoverySessionOverride)); + EXPECT_CALL(*mock_adapter_, StopScan(_)) + .WillOnce(Invoke(this, &BluetoothApiTest::StopScanOverride)); FailNextCall(); scoped_refptr<api::BluetoothStopDiscoveryFunction> stop_function; stop_function = setupFunction(new api::BluetoothStopDiscoveryFunction); - error = - utils::RunFunctionAndReturnError(stop_function.get(), "[]", browser()); - ASSERT_FALSE(error.empty()); - - // Simiulate successful stop discovery - EXPECT_CALL(*mock_adapter_, RemoveDiscoverySession_(_, _, _)) - .WillOnce( - Invoke(this, &BluetoothApiTest::RemoveDiscoverySessionOverride)); - stop_function = setupFunction(new api::BluetoothStopDiscoveryFunction); (void)utils::RunFunctionAndReturnSingleResult(stop_function.get(), "[]", browser()); SetUpMockAdapter(); @@ -230,9 +218,8 @@ IN_PROC_BROWSER_TEST_F(BluetoothApiTest, Discovery) { IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DiscoveryCallback) { EXPECT_CALL(*mock_adapter_, StartScanWithFilter_(_, _)) .WillOnce(Invoke(this, &BluetoothApiTest::StartScanOverride)); - EXPECT_CALL(*mock_adapter_, RemoveDiscoverySession_(_, _, _)) - .WillOnce( - Invoke(this, &BluetoothApiTest::RemoveDiscoverySessionOverride)); + EXPECT_CALL(*mock_adapter_, StopScan(_)) + .WillOnce(Invoke(this, &BluetoothApiTest::StopScanOverride)); ResultCatcher catcher; catcher.RestrictToBrowserContext(browser()->profile()); @@ -278,9 +265,8 @@ IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DiscoveryInProgress) { EXPECT_CALL(*mock_adapter_, StartScanWithFilter_(_, _)) .WillOnce(Invoke(this, &BluetoothApiTest::StartScanOverride)); - EXPECT_CALL(*mock_adapter_, RemoveDiscoverySession_(_, _, _)) - .WillOnce( - Invoke(this, &BluetoothApiTest::RemoveDiscoverySessionOverride)); + EXPECT_CALL(*mock_adapter_, StopScan(_)) + .WillOnce(Invoke(this, &BluetoothApiTest::StopScanOverride)); ExtensionTestMessageListener discovery_started("ready", true); ASSERT_TRUE(LoadExtension( diff --git a/chromium/extensions/browser/api/bluetooth/bluetooth_event_router.cc b/chromium/extensions/browser/api/bluetooth/bluetooth_event_router.cc index 88a8d998b0a..9a7c13aff8f 100644 --- a/chromium/extensions/browser/api/bluetooth/bluetooth_event_router.cc +++ b/chromium/extensions/browser/api/bluetooth/bluetooth_event_router.cc @@ -29,7 +29,6 @@ #include "extensions/browser/api/bluetooth/bluetooth_private_api.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/notification_types.h" #include "extensions/common/api/bluetooth.h" #include "extensions/common/api/bluetooth_private.h" @@ -57,9 +56,7 @@ namespace bluetooth = api::bluetooth; namespace bt_private = api::bluetooth_private; BluetoothEventRouter::BluetoothEventRouter(content::BrowserContext* context) - : browser_context_(context), - adapter_(nullptr), - extension_registry_observer_(this) { + : browser_context_(context), adapter_(nullptr) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); BLUETOOTH_LOG(USER) << "BluetoothEventRouter()"; DCHECK(browser_context_); @@ -186,7 +183,13 @@ void BluetoothEventRouter::SetDiscoveryFilter( const base::Closure& callback, const base::Closure& error_callback) { BLUETOOTH_LOG(USER) << "SetDiscoveryFilter"; + if (!adapter_.get()) { + BLUETOOTH_LOG(ERROR) << "Unable to get Bluetooth adapter."; + error_callback.Run(); + return; + } if (adapter != adapter_.get()) { + BLUETOOTH_LOG(ERROR) << "Bluetooth adapter mismatch."; error_callback.Run(); return; } @@ -200,9 +203,14 @@ void BluetoothEventRouter::SetDiscoveryFilter( return; } - // extension is already running discovery, update it's discovery filter - iter->second->SetDiscoveryFilter(std::move(discovery_filter), callback, - error_callback); + // If the session has already started simply start a new one. The callback + // will automatically delete the old session and put the new session (with its + // new filter) in as this extension's session + adapter->StartDiscoverySessionWithFilter( + std::move(discovery_filter), + base::Bind(&BluetoothEventRouter::OnStartDiscoverySession, + weak_ptr_factory_.GetWeakPtr(), extension_id, callback), + error_callback); } BluetoothApiPairingDelegate* BluetoothEventRouter::GetPairingDelegate( @@ -249,6 +257,7 @@ void BluetoothEventRouter::AddPairingDelegateImpl( LOG(ERROR) << "Unable to get adapter for extension_id: " << extension_id; return; } + if (base::Contains(pairing_delegate_map_, extension_id)) { // For WebUI there may be more than one page open to the same url // (e.g. chrome://settings). These will share the same pairing delegate. diff --git a/chromium/extensions/browser/api/bluetooth/bluetooth_event_router.h b/chromium/extensions/browser/api/bluetooth/bluetooth_event_router.h index 8dd778a4678..593a2179d3f 100644 --- a/chromium/extensions/browser/api/bluetooth/bluetooth_event_router.h +++ b/chromium/extensions/browser/api/bluetooth/bluetooth_event_router.h @@ -17,6 +17,7 @@ #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "extensions/browser/extension_event_histogram_value.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/common/api/bluetooth.h" #include "extensions/common/api/bluetooth_private.h" @@ -34,7 +35,6 @@ class BluetoothDiscoverySession; namespace extensions { class BluetoothApiPairingDelegate; -class ExtensionRegistry; struct EventListenerInfo; class BluetoothEventRouter : public device::BluetoothAdapter::Observer, @@ -181,7 +181,7 @@ class BluetoothEventRouter : public device::BluetoothAdapter::Observer, content::NotificationRegistrar registrar_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; base::WeakPtrFactory<BluetoothEventRouter> weak_ptr_factory_{this}; diff --git a/chromium/extensions/browser/api/bluetooth/bluetooth_event_router_unittest.cc b/chromium/extensions/browser/api/bluetooth/bluetooth_event_router_unittest.cc index 5b61182aa03..c7b265b51b4 100644 --- a/chromium/extensions/browser/api/bluetooth/bluetooth_event_router_unittest.cc +++ b/chromium/extensions/browser/api/bluetooth/bluetooth_event_router_unittest.cc @@ -117,13 +117,18 @@ TEST_F(BluetoothEventRouterTest, SetDiscoveryFilter) { EXPECT_CALL( *mock_adapter_, StartScanWithFilter_(testing::Pointee(IsFilterEqual(&df)), testing::_)) - .Times(1); + .WillOnce(testing::Invoke( + [](const device::BluetoothDiscoveryFilter* filter, + base::OnceCallback<void( + /*is_error*/ bool, + device::UMABluetoothDiscoverySessionOutcome)>& callback) { + std::move(callback).Run( + false, device::UMABluetoothDiscoverySessionOutcome::SUCCESS); + })); // RemoveDiscoverySession will be called when the BluetoothDiscoverySession // is destroyed - EXPECT_CALL(*mock_adapter_, - RemoveDiscoverySession_(testing::_, testing::_, testing::_)) - .Times(1); + EXPECT_CALL(*mock_adapter_, StopScan(testing::_)).Times(1); router_->StartDiscoverySession(mock_adapter_, kTestExtensionId, base::DoNothing(), base::DoNothing()); diff --git a/chromium/extensions/browser/api/bluetooth/bluetooth_extension_function.h b/chromium/extensions/browser/api/bluetooth/bluetooth_extension_function.h index 56e506363f9..2c49cba7a0d 100644 --- a/chromium/extensions/browser/api/bluetooth/bluetooth_extension_function.h +++ b/chromium/extensions/browser/api/bluetooth/bluetooth_extension_function.h @@ -22,7 +22,7 @@ namespace api { // Base class for bluetooth extension functions. This class initializes // bluetooth adapter and calls (on the UI thread) DoWork() implemented by // individual bluetooth extension functions. -class BluetoothExtensionFunction : public UIThreadExtensionFunction { +class BluetoothExtensionFunction : public ExtensionFunction { public: BluetoothExtensionFunction(); diff --git a/chromium/extensions/browser/api/bluetooth/bluetooth_private_api.cc b/chromium/extensions/browser/api/bluetooth/bluetooth_private_api.cc index d88298ebb55..9dba360ebfe 100644 --- a/chromium/extensions/browser/api/bluetooth/bluetooth_private_api.cc +++ b/chromium/extensions/browser/api/bluetooth/bluetooth_private_api.cc @@ -697,6 +697,8 @@ void BluetoothPrivateRecordPairingFunction::DoWork( RecordPairingResult(params_->success, params_->transport, params_->pairing_duration_ms); RecordPairingTransport(params_->transport); + + Respond(NoArguments()); } //////////////////////////////////////////////////////////////////////////////// @@ -720,6 +722,8 @@ void BluetoothPrivateRecordReconnectionFunction::DoWork( base::UmaHistogramBoolean( "Bluetooth.ChromeOS.UserInitiatedReconnectionAttempt.Result.Settings", params_->success); + + Respond(NoArguments()); } //////////////////////////////////////////////////////////////////////////////// @@ -758,6 +762,8 @@ void BluetoothPrivateRecordDeviceSelectionFunction::DoWork( base::TimeDelta::FromMilliseconds(params_->selection_duration_ms), device::BluetoothUiSurface::kSettings, params_->was_paired, transport); #endif + + Respond(NoArguments()); } //////////////////////////////////////////////////////////////////////////////// diff --git a/chromium/extensions/browser/api/bluetooth/bluetooth_private_apitest.cc b/chromium/extensions/browser/api/bluetooth/bluetooth_private_apitest.cc index 887aff70e7c..0312f458b30 100644 --- a/chromium/extensions/browser/api/bluetooth/bluetooth_private_apitest.cc +++ b/chromium/extensions/browser/api/bluetooth/bluetooth_private_apitest.cc @@ -131,7 +131,15 @@ class BluetoothPrivateApiTest : public ExtensionApiTest { } void StartScanOverride( - base::OnceCallback<void(/*is_error*/ bool, + base::OnceCallback<void(/*is_error=*/bool, + device::UMABluetoothDiscoverySessionOutcome)>& + callback) { + std::move(callback).Run( + false, device::UMABluetoothDiscoverySessionOutcome::SUCCESS); + } + + void UpdateFilterOverride( + base::OnceCallback<void(/*is_error=*/bool, device::UMABluetoothDiscoverySessionOutcome)>& callback) { std::move(callback).Run( @@ -247,6 +255,8 @@ IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, ForgetDevice) { #endif IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, DiscoveryFilter) { + BluetoothDiscoveryFilter discovery_filter_default( + device::BLUETOOTH_TRANSPORT_DUAL); BluetoothDiscoveryFilter discovery_filter(device::BLUETOOTH_TRANSPORT_LE); discovery_filter.SetPathloss(50); discovery_filter.AddUUID(BluetoothUUID("cafe")); @@ -258,9 +268,11 @@ IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, DiscoveryFilter) { .Times(1) .WillOnce(WithArgs<1>( Invoke(this, &BluetoothPrivateApiTest::StartScanOverride))); - EXPECT_CALL(*mock_adapter_, SetDiscoveryFilterRaw(Eq(nullptr), _, _)) + EXPECT_CALL(*mock_adapter_, + UpdateFilter_(IsFilterEqual(&discovery_filter_default), _)) .Times(1) - .WillOnce(InvokeCallbackArgument<1>()); + .WillOnce(WithArgs<1>( + Invoke(this, &BluetoothPrivateApiTest::UpdateFilterOverride))); ASSERT_TRUE(RunComponentExtensionTest("bluetooth_private/discovery_filter")) << message_; } diff --git a/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h b/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h index 346fd0cf709..ed00b5fd5cc 100644 --- a/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h +++ b/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_api.h @@ -90,7 +90,7 @@ namespace api { // Base class for bluetoothLowEnergy API functions. This class handles some of // the common logic involved in all API functions, such as checking for // platform support and returning the correct error. -class BluetoothLowEnergyExtensionFunction : public UIThreadExtensionFunction { +class BluetoothLowEnergyExtensionFunction : public ExtensionFunction { public: BluetoothLowEnergyExtensionFunction(); diff --git a/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.cc b/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.cc index 926612a9cd9..e64c166c6f8 100644 --- a/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.cc +++ b/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.cc @@ -29,7 +29,6 @@ #include "extensions/browser/api/bluetooth_low_energy/utils.h" #include "extensions/browser/event_listener_map.h" #include "extensions/browser/event_router.h" -#include "extensions/browser/extension_registry.h" #include "extensions/common/api/bluetooth/bluetooth_manifest_data.h" #include "extensions/common/extension.h" @@ -237,10 +236,7 @@ BluetoothLowEnergyEventRouter::AttributeValueRequest::~AttributeValueRequest() = BluetoothLowEnergyEventRouter::BluetoothLowEnergyEventRouter( content::BrowserContext* context) - : adapter_(NULL), - last_callback_request_id_(0), - browser_context_(context), - extension_registry_observer_(this) { + : browser_context_(context) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(browser_context_); VLOG(1) << "Initializing BluetoothLowEnergyEventRouter."; diff --git a/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h b/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h index 7deb98eea39..5c4c97531bb 100644 --- a/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h +++ b/chromium/extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h @@ -26,6 +26,7 @@ #include "device/bluetooth/bluetooth_remote_gatt_service.h" #include "device/bluetooth/public/cpp/bluetooth_uuid.h" #include "extensions/browser/extension_event_histogram_value.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/common/api/bluetooth_low_energy.h" @@ -55,7 +56,6 @@ namespace extensions { class BluetoothLowEnergyConnection; class BluetoothLowEnergyNotifySession; class Extension; -class ExtensionRegistry; // The BluetoothLowEnergyEventRouter is used by the bluetoothLowEnergy API to // interface with the internal Bluetooth API in device/bluetooth. @@ -573,7 +573,7 @@ class BluetoothLowEnergyEventRouter // requests. ExtensionToRequestsMap requests_; // The last request ID we used. - size_t last_callback_request_id_; + size_t last_callback_request_id_ = 0; // Map of locally hosted GATT service ids created by app_id. Used for cleanup. std::map<std::string, std::vector<std::string>> app_id_to_service_ids_; @@ -583,7 +583,7 @@ class BluetoothLowEnergyEventRouter // Listen to extension unloaded notification. ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; // Note: This should remain the last member so it'll be destroyed and // invalidate its weak pointers before any other members are destroyed. diff --git a/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_api.cc b/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_api.cc index 742c5711904..9a97947d622 100644 --- a/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_api.cc +++ b/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_api.cc @@ -124,7 +124,7 @@ BluetoothSocketAsyncApiFunction::BluetoothSocketAsyncApiFunction() {} BluetoothSocketAsyncApiFunction::~BluetoothSocketAsyncApiFunction() {} bool BluetoothSocketAsyncApiFunction::PreRunValidation(std::string* error) { - if (!UIThreadExtensionFunction::PreRunValidation(error)) + if (!ExtensionFunction::PreRunValidation(error)) return false; if (!BluetoothManifestData::CheckSocketPermitted(extension())) { diff --git a/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_api.h b/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_api.h index 5d9a4af25a1..cee888cd268 100644 --- a/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_api.h +++ b/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_api.h @@ -39,14 +39,14 @@ class BluetoothSocketEventDispatcher; // thread while providing methods to manage resources of that class. This // follows the pattern of AsyncApiFunction, but does not derive from it, // because BluetoothApiSocket methods must be called on the UI Thread. -class BluetoothSocketAsyncApiFunction : public UIThreadExtensionFunction { +class BluetoothSocketAsyncApiFunction : public ExtensionFunction { public: BluetoothSocketAsyncApiFunction(); protected: ~BluetoothSocketAsyncApiFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: bool PreRunValidation(std::string* error) override; content::BrowserThread::ID work_thread_id() const; @@ -84,7 +84,7 @@ class BluetoothSocketUpdateFunction : public BluetoothSocketAsyncApiFunction { protected: ~BluetoothSocketUpdateFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -102,7 +102,7 @@ class BluetoothSocketSetPausedFunction protected: ~BluetoothSocketSetPausedFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -126,7 +126,7 @@ class BluetoothSocketListenFunction : public BluetoothSocketAsyncApiFunction { virtual int socket_id() const = 0; virtual const std::string& uuid() const = 0; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; bool PreRunValidation(std::string* error) override; @@ -206,7 +206,7 @@ class BluetoothSocketAbstractConnectFunction : protected: ~BluetoothSocketAbstractConnectFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: bool PreRunValidation(std::string* error) override; ResponseAction Run() override; @@ -251,7 +251,7 @@ class BluetoothSocketDisconnectFunction protected: ~BluetoothSocketDisconnectFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -269,7 +269,7 @@ class BluetoothSocketCloseFunction : public BluetoothSocketAsyncApiFunction { protected: ~BluetoothSocketCloseFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -285,7 +285,7 @@ class BluetoothSocketSendFunction : public BluetoothSocketAsyncApiFunction { protected: ~BluetoothSocketSendFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -309,7 +309,7 @@ class BluetoothSocketGetInfoFunction : public BluetoothSocketAsyncApiFunction { protected: ~BluetoothSocketGetInfoFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -327,7 +327,7 @@ class BluetoothSocketGetSocketsFunction protected: ~BluetoothSocketGetSocketsFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; diff --git a/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_event_dispatcher.cc b/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_event_dispatcher.cc index b6dd6de729f..c8df92dfbcf 100644 --- a/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_event_dispatcher.cc +++ b/chromium/extensions/browser/api/bluetooth_socket/bluetooth_socket_event_dispatcher.cc @@ -209,7 +209,7 @@ void BluetoothSocketEventDispatcher::ReceiveCallback( // Post a task to delay the read until the socket is available, as // calling StartReceive at this point would error with ERR_IO_PENDING. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {params.thread_id}, base::BindOnce(&BluetoothSocketEventDispatcher::StartReceive, params)); } @@ -305,7 +305,7 @@ void BluetoothSocketEventDispatcher::AcceptCallback( // Post a task to delay the accept until the socket is available, as // calling StartAccept at this point would error with ERR_IO_PENDING. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {params.thread_id}, base::BindOnce(&BluetoothSocketEventDispatcher::StartAccept, params)); } @@ -351,10 +351,9 @@ void BluetoothSocketEventDispatcher::PostEvent(const SocketParams& params, std::unique_ptr<Event> event) { DCHECK_CURRENTLY_ON(params.thread_id); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&DispatchEvent, params.browser_context_id, - params.extension_id, std::move(event))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&DispatchEvent, params.browser_context_id, + params.extension_id, std::move(event))); } // static diff --git a/chromium/extensions/browser/api/cast_channel/cast_channel_api.cc b/chromium/extensions/browser/api/cast_channel/cast_channel_api.cc index 438baeec4af..35eb5f00004 100644 --- a/chromium/extensions/browser/api/cast_channel/cast_channel_api.cc +++ b/chromium/extensions/browser/api/cast_channel/cast_channel_api.cc @@ -515,8 +515,8 @@ void CastChannelAPI::CastMessageHandler::OnError( OnError::Create(channel_info, error_info); std::unique_ptr<Event> event(new Event( events::CAST_CHANNEL_ON_ERROR, OnError::kEventName, std::move(results))); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(ui_dispatch_cb_, std::move(event))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(ui_dispatch_cb_, std::move(event))); } void CastChannelAPI::CastMessageHandler::OnMessage( @@ -536,8 +536,8 @@ void CastChannelAPI::CastMessageHandler::OnMessage( std::unique_ptr<Event> event(new Event(events::CAST_CHANNEL_ON_MESSAGE, OnMessage::kEventName, std::move(results))); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(ui_dispatch_cb_, std::move(event))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(ui_dispatch_cb_, std::move(event))); } } // namespace extensions diff --git a/chromium/extensions/browser/api/cast_channel/cast_channel_apitest.cc b/chromium/extensions/browser/api/cast_channel/cast_channel_apitest.cc index dda8e384a32..8787a78d285 100644 --- a/chromium/extensions/browser/api/cast_channel/cast_channel_apitest.cc +++ b/chromium/extensions/browser/api/cast_channel/cast_channel_apitest.cc @@ -204,11 +204,10 @@ class CastChannelAPITest : public extensions::ExtensionApiTest { protected: void CallOnMessage(const std::string& message) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&CastChannelAPITest::DoCallOnMessage, - base::Unretained(this), GetApi(), mock_cast_socket_, - message)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&CastChannelAPITest::DoCallOnMessage, + base::Unretained(this), GetApi(), + mock_cast_socket_, message)); } void DoCallOnMessage(extensions::CastChannelAPI* api, @@ -221,10 +220,9 @@ class CastChannelAPITest : public extensions::ExtensionApiTest { // Fires a timer on the IO thread. void FireTimeout() { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&CastChannelAPITest::DoFireTimeout, - base::Unretained(this), mock_cast_socket_)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&CastChannelAPITest::DoFireTimeout, + base::Unretained(this), mock_cast_socket_)); } void DoFireTimeout(MockCastSocket* cast_socket) { @@ -257,11 +255,10 @@ class CastChannelAPITest : public extensions::ExtensionApiTest { }; ACTION_P2(InvokeObserverOnError, api_test, cast_socket_service) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&CastChannelAPITest::DoCallOnError, - base::Unretained(api_test), - base::Unretained(cast_socket_service))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&CastChannelAPITest::DoCallOnError, + base::Unretained(api_test), + base::Unretained(cast_socket_service))); } // TODO(kmarshall): Win Dbg has a workaround that makes RunExtensionSubtest diff --git a/chromium/extensions/browser/api/cec_private/cec_private_api.cc b/chromium/extensions/browser/api/cec_private/cec_private_api.cc index 936a7895ef4..6fb61720f78 100644 --- a/chromium/extensions/browser/api/cec_private/cec_private_api.cc +++ b/chromium/extensions/browser/api/cec_private/cec_private_api.cc @@ -58,7 +58,7 @@ CecPrivateFunction::~CecPrivateFunction() = default; // Only allow calls from kiosk mode extensions. bool CecPrivateFunction::PreRunValidation(std::string* error) { - if (!UIThreadExtensionFunction::PreRunValidation(error)) + if (!ExtensionFunction::PreRunValidation(error)) return false; if (KioskModeInfo::IsKioskEnabled(extension())) diff --git a/chromium/extensions/browser/api/cec_private/cec_private_api.h b/chromium/extensions/browser/api/cec_private/cec_private_api.h index 6a2029b5cda..a1c8fae6b51 100644 --- a/chromium/extensions/browser/api/cec_private/cec_private_api.h +++ b/chromium/extensions/browser/api/cec_private/cec_private_api.h @@ -14,7 +14,7 @@ namespace extensions { namespace api { -class CecPrivateFunction : public UIThreadExtensionFunction { +class CecPrivateFunction : public ExtensionFunction { public: CecPrivateFunction(); diff --git a/chromium/extensions/browser/api/clipboard/clipboard_api.h b/chromium/extensions/browser/api/clipboard/clipboard_api.h index ecd6a69fe7c..67b272606d5 100644 --- a/chromium/extensions/browser/api/clipboard/clipboard_api.h +++ b/chromium/extensions/browser/api/clipboard/clipboard_api.h @@ -37,7 +37,7 @@ class ClipboardAPI : public BrowserContextKeyedAPI, content::BrowserContext* const browser_context_; }; -class ClipboardSetImageDataFunction : public UIThreadExtensionFunction { +class ClipboardSetImageDataFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("clipboard.setImageData", CLIPBOARD_SETIMAGEDATA) diff --git a/chromium/extensions/browser/api/declarative/declarative_api.cc b/chromium/extensions/browser/api/declarative/declarative_api.cc index 6fa9f7b36fd..e5cf129353e 100644 --- a/chromium/extensions/browser/api/declarative/declarative_api.cc +++ b/chromium/extensions/browser/api/declarative/declarative_api.cc @@ -188,8 +188,7 @@ ExtensionFunction::ResponseAction RulesFunction::Run() { return RespondNow(RunAsyncOnCorrectThread()); scoped_refptr<base::SingleThreadTaskRunner> thread_task_runner = - base::CreateSingleThreadTaskRunnerWithTraits( - {rules_registry_->owner_thread()}); + base::CreateSingleThreadTaskRunner({rules_registry_->owner_thread()}); base::PostTaskAndReplyWithResult( thread_task_runner.get(), FROM_HERE, base::BindOnce(&RulesFunction::RunAsyncOnCorrectThread, this), diff --git a/chromium/extensions/browser/api/declarative/declarative_api.h b/chromium/extensions/browser/api/declarative/declarative_api.h index ceaa341ca75..e50aa5d6a68 100644 --- a/chromium/extensions/browser/api/declarative/declarative_api.h +++ b/chromium/extensions/browser/api/declarative/declarative_api.h @@ -29,7 +29,7 @@ struct Params; } // namespace events } // namespace api -class RulesFunction : public UIThreadExtensionFunction { +class RulesFunction : public ExtensionFunction { public: RulesFunction(); diff --git a/chromium/extensions/browser/api/declarative/rules_cache_delegate.cc b/chromium/extensions/browser/api/declarative/rules_cache_delegate.cc index 4e29c3606fd..22e5f35db04 100644 --- a/chromium/extensions/browser/api/declarative/rules_cache_delegate.cc +++ b/chromium/extensions/browser/api/declarative/rules_cache_delegate.cc @@ -143,7 +143,7 @@ void RulesCacheDelegate::CheckIfReady() { if (notified_registry_ || !waiting_for_extensions_.empty()) return; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {rules_registry_thread_}, base::BindOnce(&RulesRegistry::MarkReady, registry_, storage_init_time_)); notified_registry_ = true; @@ -211,10 +211,9 @@ void RulesCacheDelegate::ReadFromStorageCallback( std::unique_ptr<base::Value> value) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_EQ(Type::kPersistent, type_); - base::PostTaskWithTraits( - FROM_HERE, {rules_registry_thread_}, - base::BindOnce(&RulesRegistry::DeserializeAndAddRules, registry_, - extension_id, std::move(value))); + base::PostTask(FROM_HERE, {rules_registry_thread_}, + base::BindOnce(&RulesRegistry::DeserializeAndAddRules, + registry_, extension_id, std::move(value))); waiting_for_extensions_.erase(extension_id); diff --git a/chromium/extensions/browser/api/declarative/rules_registry.cc b/chromium/extensions/browser/api/declarative/rules_registry.cc index 0081dab5327..ab59b6b30a2 100644 --- a/chromium/extensions/browser/api/declarative/rules_registry.cc +++ b/chromium/extensions/browser/api/declarative/rules_registry.cc @@ -348,7 +348,7 @@ void RulesRegistry::ProcessChangedRules(const std::string& extension_id) { std::vector<const api::events::Rule*> new_rules; GetRules(extension_id, &rules_, &new_rules); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&RulesCacheDelegate::UpdateRules, cache_delegate_, extension_id, RulesToValue(new_rules))); diff --git a/chromium/extensions/browser/api/declarative/rules_registry_service.cc b/chromium/extensions/browser/api/declarative/rules_registry_service.cc index dedb8a37994..78d8eba39dc 100644 --- a/chromium/extensions/browser/api/declarative/rules_registry_service.cc +++ b/chromium/extensions/browser/api/declarative/rules_registry_service.cc @@ -20,7 +20,6 @@ #include "extensions/browser/api/declarative_webrequest/webrequest_rules_registry.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/api/web_request/web_request_api.h" -#include "extensions/browser/extension_registry.h" #include "extensions/common/extension.h" #include "extensions/common/features/feature.h" #include "extensions/common/features/feature_provider.h" @@ -44,7 +43,6 @@ const int RulesRegistryService::kInvalidRulesRegistryID = -1; RulesRegistryService::RulesRegistryService(content::BrowserContext* context) : current_rules_registry_id_(kDefaultRulesRegistryID), content_rules_registry_(NULL), - extension_registry_observer_(this), browser_context_(context) { if (browser_context_) { extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_)); @@ -231,10 +229,10 @@ void RulesRegistryService::NotifyRegistriesHelper( if (content::BrowserThread::CurrentlyOn(registry->owner_thread())) { (registry.get()->*notification_callback)(extension); } else { - base::PostTaskWithTraits(FROM_HERE, {registry->owner_thread()}, - base::BindOnce(&NotifyWithExtensionSafe, - base::WrapRefCounted(extension), - notification_callback, registry)); + base::PostTask(FROM_HERE, {registry->owner_thread()}, + base::BindOnce(&NotifyWithExtensionSafe, + base::WrapRefCounted(extension), + notification_callback, registry)); } } } diff --git a/chromium/extensions/browser/api/declarative/rules_registry_service.h b/chromium/extensions/browser/api/declarative/rules_registry_service.h index 77ca6169227..5d89ff443e4 100644 --- a/chromium/extensions/browser/api/declarative/rules_registry_service.h +++ b/chromium/extensions/browser/api/declarative/rules_registry_service.h @@ -17,6 +17,7 @@ #include "extensions/browser/api/declarative/rules_cache_delegate.h" #include "extensions/browser/api/declarative/rules_registry.h" #include "extensions/browser/browser_context_keyed_api_factory.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" namespace content { @@ -25,7 +26,6 @@ class BrowserContext; namespace extensions { class ContentRulesRegistry; -class ExtensionRegistry; } namespace extensions { @@ -165,7 +165,7 @@ class RulesRegistryService : public BrowserContextKeyedAPI, // Listen to extension load, unloaded notification. ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; content::BrowserContext* browser_context_; diff --git a/chromium/extensions/browser/api/declarative/rules_registry_unittest.cc b/chromium/extensions/browser/api/declarative/rules_registry_unittest.cc index 2b21e363248..45197fd649d 100644 --- a/chromium/extensions/browser/api/declarative/rules_registry_unittest.cc +++ b/chromium/extensions/browser/api/declarative/rules_registry_unittest.cc @@ -9,7 +9,7 @@ #include "base/run_loop.h" #include "base/values.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/declarative/rules_registry_service.h" #include "extensions/browser/api/declarative/test_rules_registry.h" #include "extensions/browser/api_test_utils.h" @@ -28,7 +28,7 @@ namespace extensions { using api_test_utils::ParseDictionary; TEST(RulesRegistryTest, FillOptionalIdentifiers) { - content::TestBrowserThreadBundle test_browser_thread_bundle; + content::BrowserTaskEnvironment task_environment; std::string error; scoped_refptr<RulesRegistry> registry = @@ -150,7 +150,7 @@ TEST(RulesRegistryTest, FillOptionalIdentifiers) { } TEST(RulesRegistryTest, FillOptionalPriority) { - content::TestBrowserThreadBundle test_browser_thread_bundle; + content::BrowserTaskEnvironment task_environment; std::string error; scoped_refptr<RulesRegistry> registry = @@ -188,7 +188,7 @@ TEST(RulesRegistryTest, FillOptionalPriority) { // Test verifies 2 rules defined in the manifest appear in the registry. TEST(RulesRegistryTest, TwoRulesInManifest) { - content::TestBrowserThreadBundle test_browser_thread_bundle; + content::BrowserTaskEnvironment task_environment; // Create extension std::unique_ptr<base::DictionaryValue> manifest = ParseDictionary( @@ -270,7 +270,7 @@ TEST(RulesRegistryTest, TwoRulesInManifest) { // Tests verifies that rules defined in the manifest cannot be deleted but // programmatically added rules still can be deleted. TEST(RulesRegistryTest, DeleteRuleInManifest) { - content::TestBrowserThreadBundle test_browser_thread_bundle; + content::BrowserTaskEnvironment task_environment; // Create extension std::unique_ptr<base::DictionaryValue> manifest = ParseDictionary( diff --git a/chromium/extensions/browser/api/declarative_net_request/BUILD.gn b/chromium/extensions/browser/api/declarative_net_request/BUILD.gn index 9d3188e33a4..ffdd5ce2e06 100644 --- a/chromium/extensions/browser/api/declarative_net_request/BUILD.gn +++ b/chromium/extensions/browser/api/declarative_net_request/BUILD.gn @@ -4,6 +4,8 @@ source_set("declarative_net_request") { sources = [ + "action_tracker.cc", + "action_tracker.h", "composite_matcher.cc", "composite_matcher.h", "constants.cc", diff --git a/chromium/extensions/browser/api/declarative_net_request/action_tracker.cc b/chromium/extensions/browser/api/declarative_net_request/action_tracker.cc new file mode 100644 index 00000000000..037a9d4e184 --- /dev/null +++ b/chromium/extensions/browser/api/declarative_net_request/action_tracker.cc @@ -0,0 +1,96 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "extensions/browser/api/declarative_net_request/action_tracker.h" + +#include "base/stl_util.h" +#include "extensions/browser/api/declarative_net_request/rules_monitor_service.h" +#include "extensions/browser/api/extensions_api_client.h" +#include "extensions/browser/extension_prefs.h" +#include "extensions/common/constants.h" + +namespace extensions { +namespace declarative_net_request { + +ActionTracker::ActionTracker(content::BrowserContext* browser_context) + : browser_context_(browser_context) { + extension_prefs_ = ExtensionPrefs::Get(browser_context_); +} + +ActionTracker::~ActionTracker() { + DCHECK(actions_matched_.empty()); +} + +void ActionTracker::OnRuleMatched(const std::vector<ExtensionId>& extension_ids, + int tab_id) { + if (tab_id == extension_misc::kUnknownTabId) + return; + + for (const auto& extension_id : extension_ids) { + auto key = std::make_pair(extension_id, tab_id); + int action_count = ++actions_matched_[key]; + + if (extension_prefs_->GetDNRUseActionCountAsBadgeText(extension_id)) { + DCHECK(ExtensionsAPIClient::Get()); + ExtensionsAPIClient::Get()->UpdateActionCount( + browser_context_, extension_id, tab_id, action_count, + false /* clear_badge_text */); + } + } +} + +void ActionTracker::OnPreferenceEnabled(const ExtensionId& extension_id) const { + DCHECK(extension_prefs_->GetDNRUseActionCountAsBadgeText(extension_id)); + + for (auto it = actions_matched_.begin(); it != actions_matched_.end(); ++it) { + if (it->first.first != extension_id) + continue; + + int tab_id = it->first.second; + int action_count = it->second; + ExtensionsAPIClient::Get()->UpdateActionCount( + browser_context_, extension_id, tab_id, action_count, + true /* clear_badge_text */); + } +} + +void ActionTracker::ClearExtensionData(const ExtensionId& extension_id) { + auto compare_by_extension_id = + [&extension_id](const std::pair<ExtensionTabKey, size_t>& it) { + return it.first.first == extension_id; + }; + + base::EraseIf(actions_matched_, compare_by_extension_id); +} + +void ActionTracker::ClearTabData(int tab_id) { + auto compare_by_tab_id = + [&tab_id](const std::pair<ExtensionTabKey, size_t>& it) { + return it.first.second == tab_id; + }; + + base::EraseIf(actions_matched_, compare_by_tab_id); +} + +void ActionTracker::ResetActionCountForTab(int tab_id) { + RulesMonitorService* rules_monitor_service = + RulesMonitorService::Get(browser_context_); + + DCHECK(rules_monitor_service); + for (const auto& extension_id : + rules_monitor_service->extensions_with_rulesets()) { + auto key = std::make_pair(extension_id, tab_id); + actions_matched_[key] = 0; + + if (extension_prefs_->GetDNRUseActionCountAsBadgeText(extension_id)) { + DCHECK(ExtensionsAPIClient::Get()); + ExtensionsAPIClient::Get()->UpdateActionCount( + browser_context_, extension_id, tab_id, 0 /* action_count */, + false /* clear_badge_text */); + } + } +} + +} // namespace declarative_net_request +} // namespace extensions diff --git a/chromium/extensions/browser/api/declarative_net_request/action_tracker.h b/chromium/extensions/browser/api/declarative_net_request/action_tracker.h new file mode 100644 index 00000000000..3933d7ef8ac --- /dev/null +++ b/chromium/extensions/browser/api/declarative_net_request/action_tracker.h @@ -0,0 +1,68 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef EXTENSIONS_BROWSER_API_DECLARATIVE_NET_REQUEST_ACTION_TRACKER_H_ +#define EXTENSIONS_BROWSER_API_DECLARATIVE_NET_REQUEST_ACTION_TRACKER_H_ + +#include <map> +#include <vector> + +#include "base/macros.h" +#include "extensions/common/extension_id.h" + +namespace content { +class BrowserContext; +} + +namespace extensions { + +class ExtensionPrefs; + +namespace declarative_net_request { + +class ActionTracker { + public: + explicit ActionTracker(content::BrowserContext* browser_context); + ~ActionTracker(); + + // Called whenever a request matches with a rule. + void OnRuleMatched(const std::vector<ExtensionId>& extension_ids, int tab_id); + + // Updates the action count for all tabs for the specified |extension_id|'s + // extension action. Called when chrome.setActionCountAsBadgeText(true) is + // called by an extension. + void OnPreferenceEnabled(const ExtensionId& extension_id) const; + + // Clears the action count for the specified |extension_id| for all tabs. + // Called when an extension's ruleset is removed. + void ClearExtensionData(const ExtensionId& extension_id); + + // Clears the action count for every extension for the specified |tab_id|. + // Called when the tab has been closed. + void ClearTabData(int tab_id); + + // Sets the action count for every extension for the specified |tab_id| to 0 + // and notifies the extension action to set the badge text to 0 for that tab. + // Called when the a main-frame navigation to a different document finishes on + // the tab. + void ResetActionCountForTab(int tab_id); + + private: + using ExtensionTabKey = std::pair<ExtensionId, int>; + + // Maps a pair of (extension ID, tab ID) to the number of actions matched for + // the extension and tab specified. + std::map<ExtensionTabKey, int> actions_matched_; + + content::BrowserContext* browser_context_; + + ExtensionPrefs* extension_prefs_; + + DISALLOW_COPY_AND_ASSIGN(ActionTracker); +}; + +} // namespace declarative_net_request +} // namespace extensions + +#endif // EXTENSIONS_BROWSER_API_DECLARATIVE_NET_REQUEST_ACTION_TRACKER_H_ diff --git a/chromium/extensions/browser/api/declarative_net_request/composite_matcher_unittest.cc b/chromium/extensions/browser/api/declarative_net_request/composite_matcher_unittest.cc index 16cc9ab395d..215911bbe14 100644 --- a/chromium/extensions/browser/api/declarative_net_request/composite_matcher_unittest.cc +++ b/chromium/extensions/browser/api/declarative_net_request/composite_matcher_unittest.cc @@ -47,7 +47,8 @@ TEST_F(CompositeMatcherTest, RulesetPriority) { redirect_rule_1.condition->url_filter = std::string("example.com"); redirect_rule_1.priority = kMinValidPriority; redirect_rule_1.action->type = std::string("redirect"); - redirect_rule_1.action->redirect_url = std::string("http://ruleset1.com"); + redirect_rule_1.action->redirect.emplace(); + redirect_rule_1.action->redirect->url = std::string("http://ruleset1.com"); redirect_rule_1.id = kMinValidID + 1; // Create the first ruleset matcher. @@ -64,7 +65,8 @@ TEST_F(CompositeMatcherTest, RulesetPriority) { TestRule allow_rule = block_rule; allow_rule.action->type = std::string("allow"); TestRule redirect_rule_2 = redirect_rule_1; - redirect_rule_2.action->redirect_url = std::string("http://ruleset2.com"); + redirect_rule_2.action->redirect.emplace(); + redirect_rule_2.action->redirect->url = std::string("http://ruleset2.com"); std::unique_ptr<RulesetMatcher> matcher_2; ASSERT_TRUE(CreateVerifiedMatcher( {allow_rule, redirect_rule_2}, @@ -158,7 +160,8 @@ TEST_F(CompositeMatcherTest, AllowRuleOverrides) { redirect_rule_2.condition->url_filter = std::string("google.com"); redirect_rule_2.priority = kMinValidPriority; redirect_rule_2.action->type = std::string("redirect"); - redirect_rule_2.action->redirect_url = std::string("http://ruleset2.com"); + redirect_rule_2.action->redirect.emplace(); + redirect_rule_2.action->redirect->url = std::string("http://ruleset2.com"); redirect_rule_2.id = kMinValidID + 1; // Create a second ruleset matcher, which allows requests to example.com and @@ -243,7 +246,8 @@ TEST_F(CompositeMatcherTest, NotifyWithholdFromPageAccess) { redirect_rule.condition->url_filter = std::string("google.com"); redirect_rule.priority = kMinValidPriority; redirect_rule.action->type = std::string("redirect"); - redirect_rule.action->redirect_url = std::string("http://ruleset1.com"); + redirect_rule.action->redirect.emplace(); + redirect_rule.action->redirect->url = std::string("http://ruleset1.com"); redirect_rule.id = kMinValidID; TestRule upgrade_rule = CreateGenericRule(); @@ -321,7 +325,8 @@ TEST_F(CompositeMatcherTest, GetRedirectUrlFromPriority) { abc_redirect.condition->url_filter = std::string("*abc*"); abc_redirect.priority = kMinValidPriority; abc_redirect.action->type = std::string("redirect"); - abc_redirect.action->redirect_url = std::string("http://google.com"); + abc_redirect.action->redirect.emplace(); + abc_redirect.action->redirect->url = std::string("http://google.com"); abc_redirect.id = kMinValidID; TestRule def_upgrade = CreateGenericRule(); @@ -334,7 +339,8 @@ TEST_F(CompositeMatcherTest, GetRedirectUrlFromPriority) { ghi_redirect.condition->url_filter = std::string("*ghi*"); ghi_redirect.priority = kMinValidPriority + 2; ghi_redirect.action->type = std::string("redirect"); - ghi_redirect.action->redirect_url = std::string("http://example.com"); + ghi_redirect.action->redirect.emplace(); + ghi_redirect.action->redirect->url = std::string("http://example.com"); ghi_redirect.id = kMinValidID + 2; // In terms of priority: ghi > def > abc. diff --git a/chromium/extensions/browser/api/declarative_net_request/constants.cc b/chromium/extensions/browser/api/declarative_net_request/constants.cc index c24a7e213e2..3b8e29dc861 100644 --- a/chromium/extensions/browser/api/declarative_net_request/constants.cc +++ b/chromium/extensions/browser/api/declarative_net_request/constants.cc @@ -4,9 +4,16 @@ #include "extensions/browser/api/declarative_net_request/constants.h" +#include "extensions/common/constants.h" +#include "url/url_constants.h" + namespace extensions { namespace declarative_net_request { +const char* const kAllowedTransformSchemes[4] = { + url::kHttpScheme, url::kHttpsScheme, url::kFtpScheme, + extensions::kExtensionScheme}; + const char kErrorResourceTypeDuplicated[] = "Rule with id * includes and excludes the same resource."; const char kErrorEmptyRedirectRuleKey[] = @@ -32,11 +39,19 @@ const char kErrorDuplicateIDs[] = "Rule with id * does not have a unique ID."; const char kErrorPersisting[] = "Internal error while parsing rules."; const char kErrorNonAscii[] = "Rule with id * cannot have non-ascii characters as part of \"*\" key."; -const char kErrorInvalidUrlFilter[] = - "Rule with id * has an invalid value for \"*\" key."; const char kErrorEmptyRemoveHeadersList[] = "Rule with id * does not specify the value for \"*\" key. This is required " "for \"removeHeaders\" rules."; +const char kErrorInvalidKey[] = + "Rule with id * specifies an incorrect value for the \"*\" key."; +const char kErrorInvalidTransformScheme[] = + "Rule with id * specifies an incorrect value for the \"*\" key. Allowed " + "values are: [*]."; +const char kErrorQueryAndTransformBothSpecified[] = + "Rule with id * cannot specify both \"*\" and \"*\" keys."; +const char kErrorJavascriptRedirect[] = + "Rule with id * specifies an incorrect value for the \"*\" key. Redirects " + "to javascript urls are not supported."; const char kErrorListNotPassed[] = "Rules file must contain a list."; const char kRuleCountExceeded[] = @@ -61,5 +76,8 @@ const char kUpdateDynamicRulesStatusHistogram[] = const char kReadDynamicRulesJSONStatusHistogram[] = "Extensions.DeclarativeNetRequest.ReadDynamicRulesJSONStatus"; +const char kActionCountPlaceholderBadgeText[] = + "<<declarativeNetRequestActionCount>>"; + } // namespace declarative_net_request } // namespace extensions diff --git a/chromium/extensions/browser/api/declarative_net_request/constants.h b/chromium/extensions/browser/api/declarative_net_request/constants.h index 7b055ca5d09..477829eb448 100644 --- a/chromium/extensions/browser/api/declarative_net_request/constants.h +++ b/chromium/extensions/browser/api/declarative_net_request/constants.h @@ -19,7 +19,6 @@ enum class ParseResult { ERROR_RESOURCE_TYPE_DUPLICATED, ERROR_EMPTY_REDIRECT_RULE_PRIORITY, ERROR_EMPTY_UPGRADE_RULE_PRIORITY, - ERROR_EMPTY_REDIRECT_URL, ERROR_INVALID_RULE_ID, ERROR_INVALID_REDIRECT_RULE_PRIORITY, ERROR_INVALID_UPGRADE_RULE_PRIORITY, @@ -30,12 +29,22 @@ enum class ParseResult { ERROR_INVALID_REDIRECT_URL, ERROR_DUPLICATE_IDS, ERROR_PERSISTING_RULESET, + // Parse errors related to fields containing non-ascii characters. ERROR_NON_ASCII_URL_FILTER, ERROR_NON_ASCII_DOMAIN, ERROR_NON_ASCII_EXCLUDED_DOMAIN, + ERROR_INVALID_URL_FILTER, ERROR_EMPTY_REMOVE_HEADERS_LIST, + ERROR_INVALID_REDIRECT, + ERROR_INVALID_EXTENSION_PATH, + ERROR_INVALID_TRANSFORM_SCHEME, + ERROR_INVALID_TRANSFORM_PORT, + ERROR_INVALID_TRANSFORM_QUERY, + ERROR_INVALID_TRANSFORM_FRAGMENT, + ERROR_QUERY_AND_TRANSFORM_BOTH_SPECIFIED, + ERROR_JAVASCRIPT_REDIRECT, }; // Describes the ways in which updating dynamic rules can fail. @@ -80,6 +89,9 @@ enum RemoveHeadersMask : uint8_t { kRemoveHeadersMask_Max = (kRemoveHeadersMask_Last << 1) - 1, }; +// Schemes which can be used as part of url transforms. +extern const char* const kAllowedTransformSchemes[4]; + // Rule parsing errors. extern const char kErrorResourceTypeDuplicated[]; extern const char kErrorEmptyRedirectRuleKey[]; @@ -92,8 +104,11 @@ extern const char kErrorInvalidRedirectUrl[]; extern const char kErrorDuplicateIDs[]; extern const char kErrorPersisting[]; extern const char kErrorNonAscii[]; -extern const char kErrorInvalidUrlFilter[]; extern const char kErrorEmptyRemoveHeadersList[]; +extern const char kErrorInvalidKey[]; +extern const char kErrorInvalidTransformScheme[]; +extern const char kErrorQueryAndTransformBothSpecified[]; +extern const char kErrorJavascriptRedirect[]; extern const char kErrorListNotPassed[]; @@ -113,6 +128,10 @@ extern const char kManifestRulesCountHistogram[]; extern const char kUpdateDynamicRulesStatusHistogram[]; extern const char kReadDynamicRulesJSONStatusHistogram[]; +// Placeholder text to use for getBadgeText extension function call, when the +// badge text is set to the DNR action count. +extern const char kActionCountPlaceholderBadgeText[]; + } // namespace declarative_net_request } // namespace extensions diff --git a/chromium/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc b/chromium/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc index cdac88db7f0..bef84302e76 100644 --- a/chromium/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc +++ b/chromium/extensions/browser/api/declarative_net_request/declarative_net_request_api.cc @@ -13,11 +13,13 @@ #include "base/task_runner_util.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" +#include "extensions/browser/api/declarative_net_request/action_tracker.h" #include "extensions/browser/api/declarative_net_request/constants.h" #include "extensions/browser/api/declarative_net_request/rules_monitor_service.h" #include "extensions/browser/api/declarative_net_request/ruleset_manager.h" #include "extensions/browser/api/declarative_net_request/ruleset_source.h" #include "extensions/browser/api/declarative_net_request/utils.h" +#include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/extension_file_task_runner.h" #include "extensions/browser/extension_prefs.h" #include "extensions/common/api/declarative_net_request.h" @@ -106,7 +108,7 @@ DeclarativeNetRequestUpdateAllowedPagesFunction::UpdateAllowedPages( bool DeclarativeNetRequestUpdateAllowedPagesFunction::PreRunValidation( std::string* error) { - return UIThreadExtensionFunction::PreRunValidation(error) && + return ExtensionFunction::PreRunValidation(error) && HasRegisteredRuleset(browser_context(), extension_id(), error); } @@ -155,7 +157,7 @@ DeclarativeNetRequestGetAllowedPagesFunction:: bool DeclarativeNetRequestGetAllowedPagesFunction::PreRunValidation( std::string* error) { - return UIThreadExtensionFunction::PreRunValidation(error) && + return ExtensionFunction::PreRunValidation(error) && HasRegisteredRuleset(browser_context(), extension_id(), error); } @@ -193,7 +195,7 @@ DeclarativeNetRequestUpdateDynamicRulesFunction::UpdateDynamicRules( bool DeclarativeNetRequestUpdateDynamicRulesFunction::PreRunValidation( std::string* error) { - return UIThreadExtensionFunction::PreRunValidation(error) && + return ExtensionFunction::PreRunValidation(error) && HasRegisteredRuleset(browser_context(), extension_id(), error); } @@ -260,7 +262,7 @@ DeclarativeNetRequestGetDynamicRulesFunction:: bool DeclarativeNetRequestGetDynamicRulesFunction::PreRunValidation( std::string* error) { - return UIThreadExtensionFunction::PreRunValidation(error) && + return ExtensionFunction::PreRunValidation(error) && HasRegisteredRuleset(browser_context(), extension_id(), error); } @@ -329,7 +331,29 @@ DeclarativeNetRequestSetActionCountAsBadgeTextFunction::Run() { EXTENSION_FUNCTION_VALIDATE(error.empty()); ExtensionPrefs* prefs = ExtensionPrefs::Get(browser_context()); + if (params->enable == prefs->GetDNRUseActionCountAsBadgeText(extension_id())) + return RespondNow(NoArguments()); + prefs->SetDNRUseActionCountAsBadgeText(extension_id(), params->enable); + + // If the preference is switched on, update the extension's badge text with + // the number of actions matched for this extension. Otherwise, clear the + // action count for the extension's icon and show the default badge text if + // set. + if (params->enable) { + declarative_net_request::RulesMonitorService* rules_monitor_service = + declarative_net_request::RulesMonitorService::Get(browser_context()); + DCHECK(rules_monitor_service); + + const declarative_net_request::ActionTracker& action_tracker = + rules_monitor_service->ruleset_manager()->action_tracker(); + action_tracker.OnPreferenceEnabled(extension_id()); + } else { + DCHECK(ExtensionsAPIClient::Get()); + ExtensionsAPIClient::Get()->ClearActionCount(browser_context(), + *extension()); + } + return RespondNow(NoArguments()); } diff --git a/chromium/extensions/browser/api/declarative_net_request/declarative_net_request_api.h b/chromium/extensions/browser/api/declarative_net_request/declarative_net_request_api.h index c3b7f3c8e2b..5f5e3dc15cc 100644 --- a/chromium/extensions/browser/api/declarative_net_request/declarative_net_request_api.h +++ b/chromium/extensions/browser/api/declarative_net_request/declarative_net_request_api.h @@ -26,7 +26,7 @@ struct ReadJSONRulesResult; // Helper base class to update the set of allowed pages. class DeclarativeNetRequestUpdateAllowedPagesFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { protected: enum class Action { ADD, // Add allowed pages. @@ -87,8 +87,7 @@ class DeclarativeNetRequestRemoveAllowedPagesFunction // Implements the "declarativeNetRequest.getAllowedPages" extension // function. -class DeclarativeNetRequestGetAllowedPagesFunction - : public UIThreadExtensionFunction { +class DeclarativeNetRequestGetAllowedPagesFunction : public ExtensionFunction { public: DeclarativeNetRequestGetAllowedPagesFunction(); DECLARE_EXTENSION_FUNCTION("declarativeNetRequest.getAllowedPages", @@ -106,7 +105,7 @@ class DeclarativeNetRequestGetAllowedPagesFunction }; class DeclarativeNetRequestUpdateDynamicRulesFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { protected: DeclarativeNetRequestUpdateDynamicRulesFunction(); ~DeclarativeNetRequestUpdateDynamicRulesFunction() override; @@ -157,8 +156,7 @@ class DeclarativeNetRequestRemoveDynamicRulesFunction DISALLOW_COPY_AND_ASSIGN(DeclarativeNetRequestRemoveDynamicRulesFunction); }; -class DeclarativeNetRequestGetDynamicRulesFunction - : public UIThreadExtensionFunction { +class DeclarativeNetRequestGetDynamicRulesFunction : public ExtensionFunction { public: DeclarativeNetRequestGetDynamicRulesFunction(); DECLARE_EXTENSION_FUNCTION("declarativeNetRequest.getDynamicRules", @@ -178,8 +176,7 @@ class DeclarativeNetRequestGetDynamicRulesFunction DISALLOW_COPY_AND_ASSIGN(DeclarativeNetRequestGetDynamicRulesFunction); }; -class DeclarativeNetRequestGetMatchedRulesFunction - : public UIThreadExtensionFunction { +class DeclarativeNetRequestGetMatchedRulesFunction : public ExtensionFunction { public: DeclarativeNetRequestGetMatchedRulesFunction(); DECLARE_EXTENSION_FUNCTION("declarativeNetRequest.getMatchedRules", @@ -196,7 +193,7 @@ class DeclarativeNetRequestGetMatchedRulesFunction }; class DeclarativeNetRequestSetActionCountAsBadgeTextFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DeclarativeNetRequestSetActionCountAsBadgeTextFunction(); DECLARE_EXTENSION_FUNCTION("declarativeNetRequest.setActionCountAsBadgeText", diff --git a/chromium/extensions/browser/api/declarative_net_request/declarative_net_request_api_unittest.cc b/chromium/extensions/browser/api/declarative_net_request/declarative_net_request_api_unittest.cc deleted file mode 100644 index 5214289c47d..00000000000 --- a/chromium/extensions/browser/api/declarative_net_request/declarative_net_request_api_unittest.cc +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "extensions/browser/api/declarative_net_request/declarative_net_request_api.h" - -#include "base/memory/ref_counted.h" -#include "components/version_info/version_info.h" -#include "extensions/browser/api_test_utils.h" -#include "extensions/browser/api_unittest.h" -#include "extensions/browser/extension_prefs.h" -#include "extensions/common/extension.h" -#include "extensions/common/features/feature_channel.h" - -namespace extensions { -namespace { - -using DeclarativeNetRequestApiUnittest = ApiUnitTest; - -TEST_F(DeclarativeNetRequestApiUnittest, SetActionCountAsBadgeText) { - // Set the current channel to trunk. - ScopedCurrentChannel scoped_channel(version_info::Channel::UNKNOWN); - ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(browser_context()); - - // Preference should be false by default. - EXPECT_FALSE( - extension_prefs->GetDNRUseActionCountAsBadgeText(extension()->id())); - - auto function = base::MakeRefCounted< - DeclarativeNetRequestSetActionCountAsBadgeTextFunction>(); - function->set_extension(extension()); - - api_test_utils::RunFunction(function.get(), "[true]", browser_context()); - extension_prefs = ExtensionPrefs::Get(browser_context()); - - EXPECT_TRUE( - extension_prefs->GetDNRUseActionCountAsBadgeText(extension()->id())); -} - -} // namespace -} // namespace extensions diff --git a/chromium/extensions/browser/api/declarative_net_request/file_sequence_helper.cc b/chromium/extensions/browser/api/declarative_net_request/file_sequence_helper.cc index d1138450fc8..705f376b684 100644 --- a/chromium/extensions/browser/api/declarative_net_request/file_sequence_helper.cc +++ b/chromium/extensions/browser/api/declarative_net_request/file_sequence_helper.cc @@ -369,7 +369,7 @@ void FileSequenceHelper::LoadRulesets( } if (success) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(std::move(ui_callback), std::move(load_data))); return; @@ -402,10 +402,9 @@ void FileSequenceHelper::UpdateDynamicRules( UpdateDynamicRulesStatus status) { base::UmaHistogramEnumeration(kUpdateDynamicRulesStatusHistogram, status); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(ui_callback), std::move(load_data), - std::move(error))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(ui_callback), std::move(load_data), + std::move(error))); }; int new_ruleset_checksum = -1; @@ -450,9 +449,8 @@ void FileSequenceHelper::OnRulesetsReindexed(LoadRulesetsUICallback ui_callback, } // The UI thread will handle success or failure. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(ui_callback), std::move(load_data))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(ui_callback), std::move(load_data))); } } // namespace declarative_net_request diff --git a/chromium/extensions/browser/api/declarative_net_request/file_sequence_helper_unittest.cc b/chromium/extensions/browser/api/declarative_net_request/file_sequence_helper_unittest.cc index dba51a41305..bda889b008d 100644 --- a/chromium/extensions/browser/api/declarative_net_request/file_sequence_helper_unittest.cc +++ b/chromium/extensions/browser/api/declarative_net_request/file_sequence_helper_unittest.cc @@ -268,7 +268,8 @@ TEST_F(FileSequenceHelperTest, UpdateDynamicRules) { TestRule rule = CreateGenericRule(); rule.id = kMinValidID + 1; rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("http://google.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("http://google.com"); api_rules.clear(); api_rules.push_back(GetAPIRule(rule)); TestAddDynamicRules( diff --git a/chromium/extensions/browser/api/declarative_net_request/flat/extension_ruleset.fbs b/chromium/extensions/browser/api/declarative_net_request/flat/extension_ruleset.fbs index a51e371959e..8eafd6c621a 100644 --- a/chromium/extensions/browser/api/declarative_net_request/flat/extension_ruleset.fbs +++ b/chromium/extensions/browser/api/declarative_net_request/flat/extension_ruleset.fbs @@ -10,6 +10,43 @@ include "components/url_pattern_index/flat/url_pattern_index.fbs"; namespace extensions.declarative_net_request.flat; +table QueryKeyValue { + key : string (required); + value : string (required); +} + +table UrlTransform { + scheme : string; + host : string; + + clear_port : bool = false; + port : string; + + clear_path : bool = false; + path : string; + + clear_query : bool = false; + + /// If valid, doesn't include the '?' separator. + query : string; + + /// Query params to be removed. These are already sorted and escaped using + /// net::EscapeQueryParamValue. + remove_query_params : [string]; + + /// Query params to be added/replaced. These are already escaped using + /// net::EscapeQueryParamValue. + add_or_replace_query_params : [QueryKeyValue]; + + clear_fragment : bool = false; + + /// If valid, doesn't include the '#' separator. + fragment : string; + + username : string; + password : string; +} + /// Additional extension related metadata for a url_pattern_index UrlRule. table UrlRuleMetadata { /// ID of the UrlRule for which this metadata is stored. @@ -17,6 +54,10 @@ table UrlRuleMetadata { /// Redirect url for this rule. Should represent a valid GURL. redirect_url : string; + + /// UrlTransform for this rule. Exactly one of |redirect_url| or |transform| + /// should be specified for redirect rules. + transform : UrlTransform; } /// This provides a mapping from an action to its index within the |index_list| diff --git a/chromium/extensions/browser/api/declarative_net_request/flat_ruleset_indexer.cc b/chromium/extensions/browser/api/declarative_net_request/flat_ruleset_indexer.cc index 85414f5bc9d..ee2b2d04c1e 100644 --- a/chromium/extensions/browser/api/declarative_net_request/flat_ruleset_indexer.cc +++ b/chromium/extensions/browser/api/declarative_net_request/flat_ruleset_indexer.cc @@ -9,6 +9,7 @@ #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "extensions/browser/api/declarative_net_request/indexed_rule.h" +#include "net/base/escape.h" namespace extensions { namespace declarative_net_request { @@ -28,17 +29,18 @@ using FlatStringOffset = FlatOffset<flatbuffers::String>; using FlatStringListOffset = FlatVectorOffset<flatbuffers::String>; // Writes to |builder| a flatbuffer vector of shared strings corresponding to -// |vec| and returns the offset to it. If |vec| is empty, returns an empty -// offset. +// |container| and returns the offset to it. If |container| is empty, returns an +// empty offset. +template <typename T> FlatStringListOffset BuildVectorOfSharedStrings( flatbuffers::FlatBufferBuilder* builder, - const std::vector<std::string>& vec) { - if (vec.empty()) + const T& container) { + if (container.empty()) return FlatStringListOffset(); std::vector<FlatStringOffset> offsets; - offsets.reserve(vec.size()); - for (const auto& str : vec) + offsets.reserve(container.size()); + for (const std::string& str : container) offsets.push_back(builder->CreateSharedString(str)); return builder->CreateVector(offsets); } @@ -54,6 +56,101 @@ CreateIndexBuilders(flatbuffers::FlatBufferBuilder* builder) { return result; } +FlatOffset<flat::UrlTransform> BuildTransformOffset( + flatbuffers::FlatBufferBuilder* builder, + const dnr_api::URLTransform& transform) { + auto create_string_offset = + [builder](const std::unique_ptr<std::string>& str) { + if (!str) + return FlatStringOffset(); + + return builder->CreateSharedString(*str); + }; + + auto skip_separator_and_create_string_offset = + [builder](const std::unique_ptr<std::string>& str, char separator) { + if (!str) + return FlatStringOffset(); + + DCHECK(!str->empty()); + DCHECK_EQ(separator, str->at(0)); + + return builder->CreateSharedString(str->c_str() + 1, str->length() - 1); + }; + + auto should_clear_component = [](const std::unique_ptr<std::string>& str) { + return str && str->empty(); + }; + + const FlatStringOffset kNullOffset; + + FlatStringOffset scheme = create_string_offset(transform.scheme); + FlatStringOffset host = create_string_offset(transform.host); + + bool clear_port = should_clear_component(transform.port); + FlatStringOffset port = + clear_port ? kNullOffset : create_string_offset(transform.port); + + // Don't skip separator for path. Not all paths begin with '/'. + bool clear_path = should_clear_component(transform.path); + FlatStringOffset path = + clear_path ? kNullOffset : create_string_offset(transform.path); + + bool clear_query = should_clear_component(transform.query); + FlatStringOffset query = + clear_query + ? kNullOffset + : skip_separator_and_create_string_offset(transform.query, '?'); + + bool clear_fragment = should_clear_component(transform.fragment); + FlatStringOffset fragment = + clear_fragment + ? kNullOffset + : skip_separator_and_create_string_offset(transform.fragment, '#'); + + FlatStringOffset username = create_string_offset(transform.username); + FlatStringOffset password = create_string_offset(transform.password); + + FlatStringListOffset remove_query_params; + const bool use_plus = true; + if (transform.query_transform && transform.query_transform->remove_params) { + // Escape, sort and remove duplicates. + std::set<std::string> remove_params_escaped; + for (const std::string& remove_param : + *transform.query_transform->remove_params) { + remove_params_escaped.insert( + net::EscapeQueryParamValue(remove_param, use_plus)); + } + + remove_query_params = + BuildVectorOfSharedStrings(builder, remove_params_escaped); + } + + FlatVectorOffset<flat::QueryKeyValue> add_or_replace_params; + if (transform.query_transform && + transform.query_transform->add_or_replace_params && + !transform.query_transform->add_or_replace_params->empty()) { + std::vector<FlatOffset<flat::QueryKeyValue>> add_or_replace_queries; + add_or_replace_queries.reserve( + transform.query_transform->add_or_replace_params->size()); + for (const dnr_api::QueryKeyValue& query_pair : + *transform.query_transform->add_or_replace_params) { + FlatStringOffset key = builder->CreateSharedString( + net::EscapeQueryParamValue(query_pair.key, use_plus)); + FlatStringOffset value = builder->CreateSharedString( + net::EscapeQueryParamValue(query_pair.value, use_plus)); + add_or_replace_queries.push_back( + flat::CreateQueryKeyValue(*builder, key, value)); + } + add_or_replace_params = builder->CreateVector(add_or_replace_queries); + } + + return flat::CreateUrlTransform(*builder, scheme, host, clear_port, port, + clear_path, path, clear_query, query, + remove_query_params, add_or_replace_params, + clear_fragment, fragment, username, password); +} + } // namespace FlatRulesetIndexer::FlatRulesetIndexer() @@ -87,11 +184,22 @@ void FlatRulesetIndexer::AddUrlRule(const IndexedRule& indexed_rule) { // Store additional metadata required for a redirect rule. if (indexed_rule.action_type == dnr_api::RULE_ACTION_TYPE_REDIRECT) { - DCHECK(!indexed_rule.redirect_url.empty()); - FlatStringOffset redirect_url_offset = - builder_.CreateSharedString(indexed_rule.redirect_url); - metadata_.push_back(flat::CreateUrlRuleMetadata(builder_, indexed_rule.id, - redirect_url_offset)); + DCHECK(indexed_rule.redirect_url || indexed_rule.url_transform); + + if (indexed_rule.redirect_url) { + DCHECK(!indexed_rule.redirect_url->empty()); + FlatStringOffset redirect_url_offset = + builder_.CreateSharedString(*indexed_rule.redirect_url); + metadata_.push_back(flat::CreateUrlRuleMetadata( + builder_, indexed_rule.id, redirect_url_offset, + FlatOffset<flat::UrlTransform>())); + } else { + FlatOffset<flat::UrlTransform> transform_offset = + BuildTransformOffset(&builder_, *indexed_rule.url_transform); + metadata_.push_back(flat::CreateUrlRuleMetadata( + builder_, indexed_rule.id, FlatStringOffset() /* redirect_url */, + transform_offset)); + } } } diff --git a/chromium/extensions/browser/api/declarative_net_request/flat_ruleset_indexer_unittest.cc b/chromium/extensions/browser/api/declarative_net_request/flat_ruleset_indexer_unittest.cc index 2c641c6b345..8c77a14a5b2 100644 --- a/chromium/extensions/browser/api/declarative_net_request/flat_ruleset_indexer_unittest.cc +++ b/chromium/extensions/browser/api/declarative_net_request/flat_ruleset_indexer_unittest.cc @@ -9,6 +9,7 @@ #include <string> #include "base/format_macros.h" +#include "base/json/json_reader.h" #include "base/strings/stringprintf.h" #include "components/url_pattern_index/flat/url_pattern_index_generated.h" #include "extensions/browser/api/declarative_net_request/constants.h" @@ -43,6 +44,71 @@ std::vector<std::string> ToVector( return result; } +// Helper to create a generic URLTransform. +std::unique_ptr<dnr_api::URLTransform> CreateUrlTransform() { + const char* transform = R"( + { + "scheme" : "http", + "host" : "foo.com", + "port" : "80", + "path" : "", + "queryTransform" : { + "removeParams" : ["x1", "x2"], + "addOrReplaceParams" : [ + {"key": "y1", "value" : "foo"} + ] + }, + "fragment" : "#xx", + "username" : "user", + "password" : "pass" + } + )"; + + base::Optional<base::Value> value = base::JSONReader::Read(transform); + CHECK(value); + + base::string16 error; + auto result = dnr_api::URLTransform::FromValue(*value, &error); + CHECK(result); + CHECK(error.empty()); + return result; +} + +// Helper to verify the indexed form of URlTransform created by +// |CreateUrlTransform()|. +bool VerifyUrlTransform(const flat::UrlTransform& flat_transform) { + auto is_string_equal = [](base::StringPiece str, + const flatbuffers::String* flat_str) { + return flat_str && ToString(flat_str) == str; + }; + + auto verify_add_or_replace_params = [&flat_transform, &is_string_equal]() { + if (!flat_transform.add_or_replace_query_params() || + flat_transform.add_or_replace_query_params()->size() != 1) { + return false; + } + + const flat::QueryKeyValue* query_pair = + flat_transform.add_or_replace_query_params()->Get(0); + return query_pair && is_string_equal("y1", query_pair->key()) && + is_string_equal("foo", query_pair->value()); + }; + + return is_string_equal("http", flat_transform.scheme()) && + is_string_equal("foo.com", flat_transform.host()) && + !flat_transform.clear_port() && + is_string_equal("80", flat_transform.port()) && + flat_transform.clear_path() && !flat_transform.path() && + !flat_transform.clear_query() && !flat_transform.query() && + flat_transform.remove_query_params() && + std::vector<std::string>{"x1", "x2"} == + ToVector(flat_transform.remove_query_params()) && + verify_add_or_replace_params() && !flat_transform.clear_fragment() && + is_string_equal("xx", flat_transform.fragment()) && + is_string_equal("user", flat_transform.username()) && + is_string_equal("pass", flat_transform.password()); +} + // Helper to create an IndexedRule. IndexedRule CreateIndexedRule( uint32_t id, @@ -56,9 +122,10 @@ IndexedRule CreateIndexedRule( std::string url_pattern, std::vector<std::string> domains, std::vector<std::string> excluded_domains, - std::string redirect_url, + base::Optional<std::string> redirect_url, dnr_api::RuleActionType action_type, - std::set<dnr_api::RemoveHeaderType> remove_headers_set) { + std::set<dnr_api::RemoveHeaderType> remove_headers_set, + std::unique_ptr<dnr_api::URLTransform> url_transform = nullptr) { IndexedRule rule; rule.id = id; rule.priority = priority; @@ -74,6 +141,7 @@ IndexedRule CreateIndexedRule( rule.redirect_url = std::move(redirect_url); rule.action_type = action_type; rule.remove_headers_set = std::move(remove_headers_set); + rule.url_transform = std::move(url_transform); return rule; } @@ -81,6 +149,9 @@ IndexedRule CreateIndexedRule( // since it's not stored as part of flat_rule::UrlRule. bool AreRulesEqual(const IndexedRule* indexed_rule, const flat_rule::UrlRule* rule) { + CHECK(indexed_rule); + CHECK(rule); + return indexed_rule->id == rule->id() && indexed_rule->priority == rule->priority() && indexed_rule->options == rule->options() && @@ -177,12 +248,25 @@ void VerifyExtensionMetadata( previous_id = current_id; } + // Returns whether the metadata for the given rule was correctly indexed. + auto is_metadata_correct = [](const MetadataPair& pair) { + CHECK(pair.indexed_rule->redirect_url || pair.indexed_rule->url_transform); + + if (pair.indexed_rule->redirect_url) { + if (!pair.metadata->redirect_url()) + return false; + return pair.indexed_rule->redirect_url == + ToString(pair.metadata->redirect_url()); + } + + return pair.metadata->transform() && + VerifyUrlTransform(*pair.metadata->transform()); + }; + // Iterate over the map and verify equality of the redirect rules. for (const auto& elem : map) { - EXPECT_EQ(elem.second.indexed_rule->redirect_url, - ToString(elem.second.metadata->redirect_url())) - << base::StringPrintf( - "Redirect rule with id %u was incorrectly indexed", elem.first); + EXPECT_TRUE(is_metadata_correct(elem.second)) << base::StringPrintf( + "Redirect rule with id %u was incorrectly indexed", elem.first); } } @@ -235,14 +319,14 @@ TEST_F(FlatRulesetIndexerTest, MultipleRules) { 7, kMinValidPriority, flat_rule::OptionFlag_NONE, flat_rule::ElementType_OBJECT, flat_rule::ActivationType_NONE, flat_rule::UrlPatternType_SUBSTRING, flat_rule::AnchorType_NONE, - flat_rule::AnchorType_BOUNDARY, "google.com", {"a.com"}, {"x.a.com"}, "", - dnr_api::RULE_ACTION_TYPE_BLOCK, {})); + flat_rule::AnchorType_BOUNDARY, "google.com", {"a.com"}, {"x.a.com"}, + base::nullopt, dnr_api::RULE_ACTION_TYPE_BLOCK, {})); rules_to_index.push_back(CreateIndexedRule( 2, kMinValidPriority, flat_rule::OptionFlag_APPLIES_TO_THIRD_PARTY, flat_rule::ElementType_IMAGE | flat_rule::ElementType_WEBSOCKET, flat_rule::ActivationType_NONE, flat_rule::UrlPatternType_WILDCARDED, flat_rule::AnchorType_NONE, flat_rule::AnchorType_NONE, "*google*", - {"a.com"}, {}, "", dnr_api::RULE_ACTION_TYPE_BLOCK, {})); + {"a.com"}, {}, base::nullopt, dnr_api::RULE_ACTION_TYPE_BLOCK, {})); // Redirect rules. rules_to_index.push_back(CreateIndexedRule( @@ -263,6 +347,12 @@ TEST_F(FlatRulesetIndexerTest, MultipleRules) { flat_rule::ActivationType_NONE, flat_rule::UrlPatternType_WILDCARDED, flat_rule::AnchorType_NONE, flat_rule::AnchorType_NONE, "*", {}, {}, "http://example2.com", dnr_api::RULE_ACTION_TYPE_REDIRECT, {})); + rules_to_index.push_back(CreateIndexedRule( + 100, 3, flat_rule::OptionFlag_NONE, flat_rule::ElementType_NONE, + flat_rule::ActivationType_NONE, flat_rule::UrlPatternType_WILDCARDED, + flat_rule::AnchorType_NONE, flat_rule::AnchorType_NONE, "*", {}, {}, + base::nullopt, dnr_api::RULE_ACTION_TYPE_REDIRECT, {}, + CreateUrlTransform())); // Allow rules. rules_to_index.push_back(CreateIndexedRule( @@ -270,15 +360,15 @@ TEST_F(FlatRulesetIndexerTest, MultipleRules) { flat_rule::ElementType_PING | flat_rule::ElementType_SCRIPT, flat_rule::ActivationType_NONE, flat_rule::UrlPatternType_SUBSTRING, flat_rule::AnchorType_SUBDOMAIN, flat_rule::AnchorType_NONE, - "example1.com", {"xyz.com"}, {}, "", dnr_api::RULE_ACTION_TYPE_ALLOW, - {})); + "example1.com", {"xyz.com"}, {}, base::nullopt, + dnr_api::RULE_ACTION_TYPE_ALLOW, {})); rules_to_index.push_back(CreateIndexedRule( 16, kMinValidPriority, flat_rule::OptionFlag_IS_WHITELIST | flat_rule::OptionFlag_IS_CASE_INSENSITIVE, flat_rule::ElementType_IMAGE, flat_rule::ActivationType_NONE, flat_rule::UrlPatternType_SUBSTRING, flat_rule::AnchorType_NONE, - flat_rule::AnchorType_NONE, "example3", {}, {}, "", + flat_rule::AnchorType_NONE, "example3", {}, {}, base::nullopt, dnr_api::RULE_ACTION_TYPE_ALLOW, {})); // Remove request header rules. @@ -286,7 +376,7 @@ TEST_F(FlatRulesetIndexerTest, MultipleRules) { 20, kMinValidPriority, flat_rule::OptionFlag_IS_CASE_INSENSITIVE, flat_rule::ElementType_SUBDOCUMENT, flat_rule::ActivationType_NONE, flat_rule::UrlPatternType_SUBSTRING, flat_rule::AnchorType_SUBDOMAIN, - flat_rule::AnchorType_NONE, "abc", {}, {}, "", + flat_rule::AnchorType_NONE, "abc", {}, {}, base::nullopt, dnr_api::RULE_ACTION_TYPE_REMOVEHEADERS, {dnr_api::REMOVE_HEADER_TYPE_COOKIE, dnr_api::REMOVE_HEADER_TYPE_SETCOOKIE})); @@ -294,7 +384,7 @@ TEST_F(FlatRulesetIndexerTest, MultipleRules) { 21, kMinValidPriority, flat_rule::OptionFlag_NONE, flat_rule::ElementType_NONE, flat_rule::ActivationType_NONE, flat_rule::UrlPatternType_SUBSTRING, flat_rule::AnchorType_NONE, - flat_rule::AnchorType_BOUNDARY, "xyz", {}, {"exclude.com"}, "", + flat_rule::AnchorType_BOUNDARY, "xyz", {}, {"exclude.com"}, base::nullopt, dnr_api::RULE_ACTION_TYPE_REMOVEHEADERS, {dnr_api::REMOVE_HEADER_TYPE_SETCOOKIE, dnr_api::REMOVE_HEADER_TYPE_COOKIE, @@ -308,15 +398,16 @@ TEST_F(FlatRulesetIndexerTest, MultipleRules) { expected_index_lists[flat::ActionIndex_block] = {&rules_to_index[0], &rules_to_index[1]}; expected_index_lists[flat::ActionIndex_redirect] = { - &rules_to_index[2], &rules_to_index[3], &rules_to_index[4]}; - expected_index_lists[flat::ActionIndex_allow] = {&rules_to_index[5], - &rules_to_index[6]}; + &rules_to_index[2], &rules_to_index[3], &rules_to_index[4], + &rules_to_index[5]}; + expected_index_lists[flat::ActionIndex_allow] = {&rules_to_index[6], + &rules_to_index[7]}; expected_index_lists[flat::ActionIndex_remove_cookie_header] = { - &rules_to_index[7], &rules_to_index[8]}; + &rules_to_index[8], &rules_to_index[9]}; expected_index_lists[flat::ActionIndex_remove_referer_header] = { - &rules_to_index[8]}; + &rules_to_index[9]}; expected_index_lists[flat::ActionIndex_remove_set_cookie_header] = { - &rules_to_index[7], &rules_to_index[8]}; + &rules_to_index[8], &rules_to_index[9]}; AddRulesAndVerifyIndex(rules_to_index, expected_index_lists); } diff --git a/chromium/extensions/browser/api/declarative_net_request/indexed_rule.cc b/chromium/extensions/browser/api/declarative_net_request/indexed_rule.cc index 11f79bfdbfd..aa20994eac0 100644 --- a/chromium/extensions/browser/api/declarative_net_request/indexed_rule.cc +++ b/chromium/extensions/browser/api/declarative_net_request/indexed_rule.cc @@ -8,12 +8,15 @@ #include <utility> #include "base/numerics/safe_conversions.h" +#include "base/stl_util.h" +#include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "components/url_pattern_index/url_pattern_index.h" #include "extensions/browser/api/declarative_net_request/constants.h" #include "extensions/common/api/declarative_net_request.h" #include "extensions/common/api/declarative_net_request/utils.h" #include "url/gurl.h" +#include "url/url_constants.h" namespace extensions { namespace declarative_net_request { @@ -260,6 +263,93 @@ bool IsRedirectUrlRelative(const std::string& redirect_url) { return !redirect_url.empty() && redirect_url[0] == '/'; } +bool IsValidTransformScheme(const std::unique_ptr<std::string>& scheme) { + if (!scheme) + return true; + + for (size_t i = 0; i < base::size(kAllowedTransformSchemes); ++i) { + if (*scheme == kAllowedTransformSchemes[i]) + return true; + } + return false; +} + +bool IsValidPort(const std::unique_ptr<std::string>& port) { + if (!port || port->empty()) + return true; + + unsigned port_num = 0; + return base::StringToUint(*port, &port_num) && port_num <= 65535; +} + +bool IsEmptyOrStartsWith(const std::unique_ptr<std::string>& str, + char starts_with) { + return !str || str->empty() || str->at(0) == starts_with; +} + +// Validates the given url |transform|. +ParseResult ValidateTransform(const dnr_api::URLTransform& transform) { + if (!IsValidTransformScheme(transform.scheme)) + return ParseResult::ERROR_INVALID_TRANSFORM_SCHEME; + + if (!IsValidPort(transform.port)) + return ParseResult::ERROR_INVALID_TRANSFORM_PORT; + + if (!IsEmptyOrStartsWith(transform.query, '?')) + return ParseResult::ERROR_INVALID_TRANSFORM_QUERY; + + if (!IsEmptyOrStartsWith(transform.fragment, '#')) + return ParseResult::ERROR_INVALID_TRANSFORM_FRAGMENT; + + // Only one of |query| or |query_transform| should be specified. + if (transform.query && transform.query_transform) + return ParseResult::ERROR_QUERY_AND_TRANSFORM_BOTH_SPECIFIED; + + return ParseResult::SUCCESS; +} + +// Parses the "action.redirect" dictionary of a dnr_api::Rule. +ParseResult ParseRedirect(dnr_api::Redirect redirect, + const GURL& base_url, + IndexedRule* indexed_rule) { + DCHECK(indexed_rule); + + if (redirect.url) { + GURL redirect_url = GURL(*redirect.url); + if (!redirect_url.is_valid()) + return ParseResult::ERROR_INVALID_REDIRECT_URL; + + if (redirect_url.SchemeIs(url::kJavaScriptScheme)) + return ParseResult::ERROR_JAVASCRIPT_REDIRECT; + + indexed_rule->redirect_url = std::move(*redirect.url); + return ParseResult::SUCCESS; + } + + if (redirect.extension_path) { + if (!IsRedirectUrlRelative(*redirect.extension_path)) + return ParseResult::ERROR_INVALID_EXTENSION_PATH; + + GURL redirect_url = base_url.Resolve(*redirect.extension_path); + + // Sanity check that Resolve works as expected. + DCHECK_EQ(base_url.GetOrigin(), redirect_url.GetOrigin()); + + if (!redirect_url.is_valid()) + return ParseResult::ERROR_INVALID_EXTENSION_PATH; + + indexed_rule->redirect_url = redirect_url.spec(); + return ParseResult::SUCCESS; + } + + if (redirect.transform) { + indexed_rule->url_transform = std::move(redirect.transform); + return ValidateTransform(*indexed_rule->url_transform); + } + + return ParseResult::ERROR_INVALID_REDIRECT; +} + } // namespace IndexedRule::IndexedRule() = default; @@ -292,15 +382,13 @@ ParseResult IndexedRule::CreateIndexedRule(dnr_api::Rule parsed_rule, } if (is_redirect_rule) { - if (!parsed_rule.action.redirect_url || - parsed_rule.action.redirect_url->empty()) { - return ParseResult::ERROR_EMPTY_REDIRECT_URL; - } + if (!parsed_rule.action.redirect) + return ParseResult::ERROR_INVALID_REDIRECT; - if (!IsRedirectUrlRelative(*parsed_rule.action.redirect_url) && - !GURL(*parsed_rule.action.redirect_url).is_valid()) { - return ParseResult::ERROR_INVALID_REDIRECT_URL; - } + ParseResult result = ParseRedirect(std::move(*parsed_rule.action.redirect), + base_url, indexed_rule); + if (result != ParseResult::SUCCESS) + return result; } if (parsed_rule.condition.domains && parsed_rule.condition.domains->empty()) @@ -343,17 +431,6 @@ ParseResult IndexedRule::CreateIndexedRule(dnr_api::Rule parsed_rule, return ParseResult::ERROR_NON_ASCII_EXCLUDED_DOMAIN; } - if (is_redirect_rule) { - if (IsRedirectUrlRelative(*parsed_rule.action.redirect_url)) { - GURL::Replacements relative_path; - relative_path.SetPathStr(parsed_rule.action.redirect_url->c_str()); - indexed_rule->redirect_url = - base_url.ReplaceComponents(relative_path).spec(); - } else { - indexed_rule->redirect_url = std::move(*parsed_rule.action.redirect_url); - } - } - // Parse the |anchor_left|, |anchor_right|, |url_pattern_type| and // |url_pattern| fields. UrlFilterParser::Parse(std::move(parsed_rule.condition.url_filter), diff --git a/chromium/extensions/browser/api/declarative_net_request/indexed_rule.h b/chromium/extensions/browser/api/declarative_net_request/indexed_rule.h index 42790e64dfd..52afdb68916 100644 --- a/chromium/extensions/browser/api/declarative_net_request/indexed_rule.h +++ b/chromium/extensions/browser/api/declarative_net_request/indexed_rule.h @@ -55,8 +55,13 @@ struct IndexedRule { std::vector<std::string> domains; std::vector<std::string> excluded_domains; - // The redirect url, valid iff this is a redirect rule. - std::string redirect_url; + // The redirect url for the rule. For redirect rules, exactly one of + // |redirect_url| or |url_transform| will be valid. + base::Optional<std::string> redirect_url; + + // UrlTransform for this rule. For redirect rules, exactly one of + // |redirect_url| or |url_transform| will be valid. + std::unique_ptr<api::declarative_net_request::URLTransform> url_transform; // List of headers to remove, valid iff this is a remove headers rule. std::set<api::declarative_net_request::RemoveHeaderType> remove_headers_set; diff --git a/chromium/extensions/browser/api/declarative_net_request/indexed_rule_unittest.cc b/chromium/extensions/browser/api/declarative_net_request/indexed_rule_unittest.cc index a88a053c81c..353465f4715 100644 --- a/chromium/extensions/browser/api/declarative_net_request/indexed_rule_unittest.cc +++ b/chromium/extensions/browser/api/declarative_net_request/indexed_rule_unittest.cc @@ -8,6 +8,7 @@ #include <utility> #include "base/format_macros.h" +#include "base/json/json_reader.h" #include "base/macros.h" #include "base/numerics/safe_conversions.h" #include "base/stl_util.h" @@ -34,6 +35,12 @@ GURL GetBaseURL() { return Extension::GetBaseURLFromExtensionId(kTestExtensionId); } +std::unique_ptr<dnr_api::Redirect> MakeRedirectUrl(const char* redirect_url) { + auto redirect = std::make_unique<dnr_api::Redirect>(); + redirect->url = std::make_unique<std::string>(redirect_url); + return redirect; +} + dnr_api::Rule CreateGenericParsedRule() { dnr_api::Rule rule; rule.id = kMinValidID; @@ -112,8 +119,7 @@ TEST_F(IndexedRuleTest, PriorityParsing) { rule.action.type = cases[i].action_type; if (cases[i].action_type == dnr_api::RULE_ACTION_TYPE_REDIRECT) { - rule.action.redirect_url = - std::make_unique<std::string>("http://google.com"); + rule.action.redirect = MakeRedirectUrl("http://google.com"); } IndexedRule indexed_rule; @@ -410,25 +416,20 @@ TEST_F(IndexedRuleTest, DomainsParsing) { TEST_F(IndexedRuleTest, RedirectUrlParsing) { struct { - std::unique_ptr<std::string> redirect_url; + const char* redirect_url; const ParseResult expected_result; // Only valid if |expected_result| is SUCCESS. const std::string expected_redirect_url; } cases[] = { - {std::make_unique<std::string>(""), ParseResult::ERROR_EMPTY_REDIRECT_URL, - ""}, - {nullptr, ParseResult::ERROR_EMPTY_REDIRECT_URL, ""}, - {std::make_unique<std::string>("http://google.com"), ParseResult::SUCCESS, - "http://google.com"}, - {std::make_unique<std::string>("/relative/url"), ParseResult::SUCCESS, - "chrome-extension://" + std::string(kTestExtensionId) + "/relative/url"}, - {std::make_unique<std::string>("abc"), - ParseResult::ERROR_INVALID_REDIRECT_URL, ""}}; + {"", ParseResult::ERROR_INVALID_REDIRECT_URL, ""}, + {"http://google.com", ParseResult::SUCCESS, "http://google.com"}, + {"/relative/url?q=1", ParseResult::ERROR_INVALID_REDIRECT_URL, ""}, + {"abc", ParseResult::ERROR_INVALID_REDIRECT_URL, ""}}; for (size_t i = 0; i < base::size(cases); ++i) { SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i)); dnr_api::Rule rule = CreateGenericParsedRule(); - rule.action.redirect_url = std::move(cases[i].redirect_url); + rule.action.redirect = MakeRedirectUrl(cases[i].redirect_url); rule.action.type = dnr_api::RULE_ACTION_TYPE_REDIRECT; rule.priority = std::make_unique<int>(kMinValidPriority); @@ -436,7 +437,7 @@ TEST_F(IndexedRuleTest, RedirectUrlParsing) { ParseResult result = IndexedRule::CreateIndexedRule( std::move(rule), GetBaseURL(), &indexed_rule); - EXPECT_EQ(cases[i].expected_result, result); + EXPECT_EQ(cases[i].expected_result, result) << static_cast<int>(result); if (result == ParseResult::SUCCESS) EXPECT_EQ(cases[i].expected_redirect_url, indexed_rule.redirect_url); } @@ -486,6 +487,156 @@ TEST_F(IndexedRuleTest, RemoveHeadersParsing) { } } +TEST_F(IndexedRuleTest, RedirectParsing) { + struct { + std::string redirect_dictionary_json; + ParseResult expected_result; + base::Optional<std::string> expected_redirect_url; + } cases[] = { + // clang-format off + { + "{}", + ParseResult::ERROR_INVALID_REDIRECT, + base::nullopt + }, + { + R"({"url": "xyz"})", + ParseResult::ERROR_INVALID_REDIRECT_URL, + base::nullopt + }, + { + R"({"url": "javascript:window.alert(\"hello,world\");"})", + ParseResult::ERROR_JAVASCRIPT_REDIRECT, + base::nullopt + }, + { + R"({"url": "http://google.com"})", + ParseResult::SUCCESS, + std::string("http://google.com") + }, + { + R"({"extensionPath": "foo/xyz/"})", + ParseResult::ERROR_INVALID_EXTENSION_PATH, + base::nullopt + }, + { + R"({"extensionPath": "/foo/xyz?q=1"})", + ParseResult::SUCCESS, + GetBaseURL().Resolve("/foo/xyz?q=1").spec() + }, + { + R"( + { + "transform": { + "scheme": "", + "host": "foo.com" + } + })", ParseResult::ERROR_INVALID_TRANSFORM_SCHEME, base::nullopt + }, + { + R"( + { + "transform": { + "scheme": "javascript", + "host": "foo.com" + } + })", ParseResult::ERROR_INVALID_TRANSFORM_SCHEME, base::nullopt + }, + { + R"( + { + "transform": { + "scheme": "http", + "port": "-1" + } + })", ParseResult::ERROR_INVALID_TRANSFORM_PORT, base::nullopt + }, + { + R"( + { + "transform": { + "scheme": "http", + "query": "abc" + } + })", ParseResult::ERROR_INVALID_TRANSFORM_QUERY, base::nullopt + }, + { + R"({"transform": {"path": "abc"}})", + ParseResult::SUCCESS, + base::nullopt + }, + { + R"({"transform": {"fragment": "abc"}})", + ParseResult::ERROR_INVALID_TRANSFORM_FRAGMENT, + base::nullopt + }, + { + R"({"transform": {"path": ""}})", + ParseResult::SUCCESS, + base::nullopt + }, + { + R"( + { + "transform": { + "scheme": "http", + "query": "?abc", + "queryTransform": { + "removeParams": ["abc"] + } + } + })", ParseResult::ERROR_QUERY_AND_TRANSFORM_BOTH_SPECIFIED, base::nullopt + }, + { + R"( + { + "transform": { + "scheme": "https", + "host": "foo.com", + "port": "80", + "path": "/foo", + "queryTransform": { + "removeParams": ["x1", "x2"], + "addOrReplaceParams": [ + {"key": "y1", "value": "foo"} + ] + }, + "fragment": "", + "username": "user" + } + })", ParseResult::SUCCESS, base::nullopt + } + }; + // clang-format on + + for (size_t i = 0; i < base::size(cases); ++i) { + SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i)); + dnr_api::Rule rule = CreateGenericParsedRule(); + rule.action.type = dnr_api::RULE_ACTION_TYPE_REDIRECT; + rule.priority = std::make_unique<int>(kMinValidPriority); + + base::Optional<base::Value> redirect_val = + base::JSONReader::Read(cases[i].redirect_dictionary_json); + ASSERT_TRUE(redirect_val); + + base::string16 error; + rule.action.redirect = dnr_api::Redirect::FromValue(*redirect_val, &error); + ASSERT_TRUE(rule.action.redirect); + ASSERT_TRUE(error.empty()); + + IndexedRule indexed_rule; + ParseResult result = IndexedRule::CreateIndexedRule( + std::move(rule), GetBaseURL(), &indexed_rule); + EXPECT_EQ(cases[i].expected_result, result) << static_cast<int>(result); + if (result != ParseResult::SUCCESS) + continue; + + EXPECT_TRUE(indexed_rule.url_transform || indexed_rule.redirect_url); + EXPECT_FALSE(indexed_rule.url_transform && indexed_rule.redirect_url); + EXPECT_EQ(cases[i].expected_redirect_url, indexed_rule.redirect_url); + } +} + } // namespace } // namespace declarative_net_request } // namespace extensions diff --git a/chromium/extensions/browser/api/declarative_net_request/indexed_ruleset_format_version_unittest.cc b/chromium/extensions/browser/api/declarative_net_request/indexed_ruleset_format_version_unittest.cc index ddac7df2bc1..2667906b9b2 100644 --- a/chromium/extensions/browser/api/declarative_net_request/indexed_ruleset_format_version_unittest.cc +++ b/chromium/extensions/browser/api/declarative_net_request/indexed_ruleset_format_version_unittest.cc @@ -20,9 +20,30 @@ namespace { const char* kFlatbufferSchemaExpected = R"( include "components/url_pattern_index/flat/url_pattern_index.fbs"; namespace extensions.declarative_net_request.flat; +table QueryKeyValue { + key : string (required); + value : string (required); +} +table UrlTransform { + scheme : string; + host : string; + clear_port : bool = false; + port : string; + clear_path : bool = false; + path : string; + clear_query : bool = false; + query : string; + remove_query_params : [string]; + add_or_replace_query_params : [QueryKeyValue]; + clear_fragment : bool = false; + fragment : string; + username : string; + password : string; +} table UrlRuleMetadata { id : uint (key); redirect_url : string; + transform : UrlTransform; } enum ActionIndex : ubyte { block = 0, @@ -104,7 +125,7 @@ TEST_F(IndexedRulesetFormatVersionTest, CheckVersionUpdated) { EXPECT_EQ(StripCommentsAndWhitespace(kFlatbufferSchemaExpected), StripCommentsAndWhitespace(flatbuffer_schema)) << "Schema change detected; update this test and the schema version."; - EXPECT_EQ(8, GetIndexedRulesetFormatVersionForTesting()) + EXPECT_EQ(11, GetIndexedRulesetFormatVersionForTesting()) << "Update this test if you update the schema version."; } diff --git a/chromium/extensions/browser/api/declarative_net_request/parse_info.cc b/chromium/extensions/browser/api/declarative_net_request/parse_info.cc index 4fd3758123c..802f3caaaa8 100644 --- a/chromium/extensions/browser/api/declarative_net_request/parse_info.cc +++ b/chromium/extensions/browser/api/declarative_net_request/parse_info.cc @@ -4,13 +4,28 @@ #include "extensions/browser/api/declarative_net_request/parse_info.h" +#include "base/containers/span.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" #include "extensions/common/error_utils.h" namespace extensions { namespace declarative_net_request { +namespace { + +// Helper to ensure pointers to string literals can be used with +// base::JoinString. +std::string JoinString(base::span<const char* const> parts) { + std::vector<base::StringPiece> parts_piece; + for (const char* part : parts) + parts_piece.push_back(part); + return base::JoinString(parts_piece, ", "); +} + +} // namespace + ParseInfo::ParseInfo(ParseResult result) : result_(result) {} ParseInfo::ParseInfo(ParseResult result, int rule_id) : result_(result), rule_id_(rule_id) {} @@ -40,11 +55,6 @@ std::string ParseInfo::GetErrorDescription() const { error = ErrorUtils::FormatErrorMessage(kErrorEmptyUpgradeRulePriority, base::NumberToString(*rule_id_)); break; - case ParseResult::ERROR_EMPTY_REDIRECT_URL: - error = ErrorUtils::FormatErrorMessage(kErrorEmptyRedirectRuleKey, - base::NumberToString(*rule_id_), - kRedirectUrlKey); - break; case ParseResult::ERROR_INVALID_RULE_ID: error = ErrorUtils::FormatErrorMessage( kErrorInvalidRuleKey, base::NumberToString(*rule_id_), kIDKey, @@ -76,7 +86,7 @@ std::string ParseInfo::GetErrorDescription() const { case ParseResult::ERROR_INVALID_REDIRECT_URL: error = ErrorUtils::FormatErrorMessage(kErrorInvalidRedirectUrl, base::NumberToString(*rule_id_), - kRedirectUrlKey); + kRedirectUrlPath); break; case ParseResult::ERROR_DUPLICATE_IDS: error = ErrorUtils::FormatErrorMessage(kErrorDuplicateIDs, @@ -98,15 +108,54 @@ std::string ParseInfo::GetErrorDescription() const { kErrorNonAscii, base::NumberToString(*rule_id_), kExcludedDomainsKey); break; case ParseResult::ERROR_INVALID_URL_FILTER: - error = ErrorUtils::FormatErrorMessage(kErrorInvalidUrlFilter, - base::NumberToString(*rule_id_), - kUrlFilterKey); + error = ErrorUtils::FormatErrorMessage( + kErrorInvalidKey, base::NumberToString(*rule_id_), kUrlFilterKey); break; case ParseResult::ERROR_EMPTY_REMOVE_HEADERS_LIST: error = ErrorUtils::FormatErrorMessage(kErrorEmptyRemoveHeadersList, base::NumberToString(*rule_id_), kRemoveHeadersListKey); break; + case ParseResult::ERROR_INVALID_REDIRECT: + error = ErrorUtils::FormatErrorMessage( + kErrorInvalidKey, base::NumberToString(*rule_id_), kRedirectPath); + break; + case ParseResult::ERROR_INVALID_EXTENSION_PATH: + error = ErrorUtils::FormatErrorMessage(kErrorInvalidKey, + base::NumberToString(*rule_id_), + kExtensionPathPath); + break; + case ParseResult::ERROR_INVALID_TRANSFORM_SCHEME: + error = ErrorUtils::FormatErrorMessage( + kErrorInvalidTransformScheme, base::NumberToString(*rule_id_), + kTransformSchemePath, + JoinString(base::span<const char* const>(kAllowedTransformSchemes))); + break; + case ParseResult::ERROR_INVALID_TRANSFORM_PORT: + error = ErrorUtils::FormatErrorMessage(kErrorInvalidKey, + base::NumberToString(*rule_id_), + kTransformPortPath); + break; + case ParseResult::ERROR_INVALID_TRANSFORM_QUERY: + error = ErrorUtils::FormatErrorMessage(kErrorInvalidKey, + base::NumberToString(*rule_id_), + kTransformQueryPath); + break; + case ParseResult::ERROR_INVALID_TRANSFORM_FRAGMENT: + error = ErrorUtils::FormatErrorMessage(kErrorInvalidKey, + base::NumberToString(*rule_id_), + kTransformFragmentPath); + break; + case ParseResult::ERROR_QUERY_AND_TRANSFORM_BOTH_SPECIFIED: + error = ErrorUtils::FormatErrorMessage( + kErrorQueryAndTransformBothSpecified, base::NumberToString(*rule_id_), + kTransformQueryPath, kTransformQueryTransformPath); + break; + case ParseResult::ERROR_JAVASCRIPT_REDIRECT: + error = ErrorUtils::FormatErrorMessage(kErrorJavascriptRedirect, + base::NumberToString(*rule_id_), + kRedirectUrlPath); + break; } return error; } diff --git a/chromium/extensions/browser/api/declarative_net_request/rules_monitor_service.cc b/chromium/extensions/browser/api/declarative_net_request/rules_monitor_service.cc index ffac35c119d..604d6bed5d7 100644 --- a/chromium/extensions/browser/api/declarative_net_request/rules_monitor_service.cc +++ b/chromium/extensions/browser/api/declarative_net_request/rules_monitor_service.cc @@ -26,7 +26,6 @@ #include "extensions/browser/extension_file_task_runner.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_prefs_factory.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_factory.h" #include "extensions/browser/warning_service.h" #include "extensions/browser/warning_service_factory.h" @@ -145,8 +144,7 @@ void RulesMonitorService::UpdateDynamicRules( RulesMonitorService::RulesMonitorService( content::BrowserContext* browser_context) - : registry_observer_(this), - file_sequence_bridge_(std::make_unique<FileSequenceBridge>()), + : file_sequence_bridge_(std::make_unique<FileSequenceBridge>()), prefs_(ExtensionPrefs::Get(browser_context)), extension_registry_(ExtensionRegistry::Get(browser_context)), warning_service_(WarningService::Get(browser_context)), diff --git a/chromium/extensions/browser/api/declarative_net_request/rules_monitor_service.h b/chromium/extensions/browser/api/declarative_net_request/rules_monitor_service.h index 54c4c2a66a4..2d3bc2db3e0 100644 --- a/chromium/extensions/browser/api/declarative_net_request/rules_monitor_service.h +++ b/chromium/extensions/browser/api/declarative_net_request/rules_monitor_service.h @@ -17,6 +17,7 @@ #include "base/scoped_observer.h" #include "extensions/browser/api/declarative_net_request/ruleset_manager.h" #include "extensions/browser/browser_context_keyed_api_factory.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/common/extension_id.h" @@ -26,7 +27,6 @@ class BrowserContext; namespace extensions { class ExtensionPrefs; -class ExtensionRegistry; class WarningService; namespace api { @@ -61,6 +61,10 @@ class RulesMonitorService : public BrowserContextKeyedAPI, // the given |extension_id|. bool HasRegisteredRuleset(const ExtensionId& extension_id) const; + const std::set<ExtensionId>& extensions_with_rulesets() const { + return extensions_with_rulesets_; + } + // Updates the dynamic rules for the |extension| and then invokes // |callback| with an optional error. using DynamicRuleUpdateUICallback = @@ -114,7 +118,7 @@ class RulesMonitorService : public BrowserContextKeyedAPI, std::unique_ptr<RulesetMatcher> ruleset_matcher); ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - registry_observer_; + registry_observer_{this}; std::set<ExtensionId> extensions_with_rulesets_; diff --git a/chromium/extensions/browser/api/declarative_net_request/ruleset_manager.cc b/chromium/extensions/browser/api/declarative_net_request/ruleset_manager.cc index 49c8521929c..a8f1ebdfe7a 100644 --- a/chromium/extensions/browser/api/declarative_net_request/ruleset_manager.cc +++ b/chromium/extensions/browser/api/declarative_net_request/ruleset_manager.cc @@ -14,7 +14,6 @@ #include "base/optional.h" #include "base/stl_util.h" #include "components/web_cache/browser/web_cache_manager.h" -#include "content/public/browser/resource_request_info.h" #include "extensions/browser/api/declarative_net_request/composite_matcher.h" #include "extensions/browser/api/declarative_net_request/constants.h" #include "extensions/browser/api/declarative_net_request/utils.h" @@ -87,28 +86,24 @@ bool IsRequestPageAllowed(const WebRequestInfo& request, if (request.type == content::ResourceType::kMainFrame) return allowed_pages.MatchesURL(request.url); - // This should happen for: - // - Requests not corresponding to a render frame e.g. non-navigation - // browser requests or service worker requests. - // - Requests made by a render frame but when we don't have cached FrameData - // for the request. This should occur rarely and is tracked by the - // "Extensions.ExtensionFrameMapCacheHit" histogram - if (!request.frame_data) + // This should happen for requests not corresponding to a render frame e.g. + // non-navigation browser requests or service worker requests. + if (request.frame_data.frame_id == ExtensionApiFrameIdMap::kInvalidFrameId) return false; const bool evaluate_pending_main_frame_url = - request.frame_data->pending_main_frame_url && - *request.frame_data->pending_main_frame_url != - request.frame_data->last_committed_main_frame_url; + request.frame_data.pending_main_frame_url && + *request.frame_data.pending_main_frame_url != + request.frame_data.last_committed_main_frame_url; if (!evaluate_pending_main_frame_url) { return allowed_pages.MatchesURL( - request.frame_data->last_committed_main_frame_url); + request.frame_data.last_committed_main_frame_url); } // |pending_main_frame_url| should only be set for main-frame subresource // loads. - DCHECK_EQ(ExtensionApiFrameIdMap::kTopFrameId, request.frame_data->frame_id); + DCHECK_EQ(ExtensionApiFrameIdMap::kTopFrameId, request.frame_data.frame_id); auto log_uma = [](PageAllowingInitiatorCheck value) { UMA_HISTOGRAM_ENUMERATION( @@ -127,18 +122,17 @@ bool IsRequestPageAllowed(const WebRequestInfo& request, log_uma(PageAllowingInitiatorCheck::kInitiatorAbsent); } else { const bool initiator_matches_pending_url = - url::Origin::Create(*request.frame_data->pending_main_frame_url) == + url::Origin::Create(*request.frame_data.pending_main_frame_url) == *request.initiator; const bool initiator_matches_committed_url = - url::Origin::Create( - request.frame_data->last_committed_main_frame_url) == + url::Origin::Create(request.frame_data.last_committed_main_frame_url) == *request.initiator; if (initiator_matches_pending_url && !initiator_matches_committed_url) { // We predict that |pending_main_frame_url| is the actual main frame url. log_uma(PageAllowingInitiatorCheck::kPendingCandidateMatchesInitiator); return allowed_pages.MatchesURL( - *request.frame_data->pending_main_frame_url); + *request.frame_data.pending_main_frame_url); } if (initiator_matches_committed_url && !initiator_matches_pending_url) { @@ -146,7 +140,7 @@ bool IsRequestPageAllowed(const WebRequestInfo& request, // frame url. log_uma(PageAllowingInitiatorCheck::kCommittedCandidateMatchesInitiator); return allowed_pages.MatchesURL( - request.frame_data->last_committed_main_frame_url); + request.frame_data.last_committed_main_frame_url); } if (initiator_matches_pending_url && initiator_matches_committed_url) { @@ -163,8 +157,8 @@ bool IsRequestPageAllowed(const WebRequestInfo& request, // subresource requests might be incorrectly allowed by the page // allowing API. return allowed_pages.MatchesURL( - request.frame_data->last_committed_main_frame_url) || - allowed_pages.MatchesURL(*request.frame_data->pending_main_frame_url); + request.frame_data.last_committed_main_frame_url) || + allowed_pages.MatchesURL(*request.frame_data.pending_main_frame_url); } bool ShouldCollapseResourceType(flat_rule::ElementType type) { @@ -229,7 +223,8 @@ RulesetManager::Action& RulesetManager::Action::operator=(Action&&) = default; RulesetManager::RulesetManager(content::BrowserContext* browser_context) : browser_context_(browser_context), prefs_(ExtensionPrefs::Get(browser_context)), - permission_helper_(PermissionHelper::Get(browser_context)) { + permission_helper_(PermissionHelper::Get(browser_context)), + action_tracker_(browser_context) { DCHECK(browser_context_); // RulesetManager can be created on any sequence. @@ -274,6 +269,7 @@ void RulesetManager::RemoveRuleset(const ExtensionId& extension_id) { << "RemoveRuleset called without a corresponding AddRuleset for " << extension_id; + action_tracker_.ClearExtensionData(extension_id); base::EraseIf(rulesets_, compare_by_id); if (test_observer_) @@ -405,9 +401,11 @@ base::Optional<RulesetManager::Action> RulesetManager::GetBlockOrCollapseAction( const RequestParams& params) const { for (const ExtensionRulesetData* ruleset : rulesets) { if (ruleset->matcher->ShouldBlockRequest(params)) { - return ShouldCollapseResourceType(params.element_type) - ? Action(Action::Type::COLLAPSE) - : Action(Action::Type::BLOCK); + Action action = ShouldCollapseResourceType(params.element_type) + ? Action(Action::Type::COLLAPSE) + : Action(Action::Type::BLOCK); + action.extension_ids.push_back(ruleset->extension_id); + return action; } } return base::nullopt; @@ -453,6 +451,7 @@ RulesetManager::GetRedirectOrUpgradeAction( Action action(Action::Type::REDIRECT); action.redirect_url = std::move(redirect_action.redirect_url); + action.extension_ids.push_back(ruleset->extension_id); return action; } @@ -462,14 +461,19 @@ RulesetManager::GetRedirectOrUpgradeAction( base::Optional<RulesetManager::Action> RulesetManager::GetRemoveHeadersAction( const std::vector<const ExtensionRulesetData*>& rulesets, const RequestParams& params) const { + Action action(Action::Type::REMOVE_HEADERS); uint8_t mask = 0; - for (const ExtensionRulesetData* ruleset : rulesets) - mask |= ruleset->matcher->GetRemoveHeadersMask(params, mask); + for (const ExtensionRulesetData* ruleset : rulesets) { + uint8_t ruleset_mask = ruleset->matcher->GetRemoveHeadersMask(params, mask); + if (ruleset_mask) + action.extension_ids.push_back(ruleset->extension_id); + + mask |= ruleset_mask; + } if (!mask) return base::nullopt; - Action action(Action::Type::REMOVE_HEADERS); PopulateHeadersFromMask(mask, &action.request_headers_to_remove, &action.response_headers_to_remove); return action; @@ -494,8 +498,7 @@ RulesetManager::Action RulesetManager::EvaluateRequestInternal( "Extensions.DeclarativeNetRequest.EvaluateRequestTime.AllExtensions2"); const RequestParams params(request); - const int tab_id = request.frame_data ? request.frame_data->tab_id - : extension_misc::kUnknownTabId; + const int tab_id = request.frame_data.tab_id; // |crosses_incognito| is used to ensure that a split mode extension process // can't intercept requests from a cross browser context. Since declarative diff --git a/chromium/extensions/browser/api/declarative_net_request/ruleset_manager.h b/chromium/extensions/browser/api/declarative_net_request/ruleset_manager.h index 652fe90e979..7f7bef6a9b1 100644 --- a/chromium/extensions/browser/api/declarative_net_request/ruleset_manager.h +++ b/chromium/extensions/browser/api/declarative_net_request/ruleset_manager.h @@ -14,6 +14,7 @@ #include "base/optional.h" #include "base/sequence_checker.h" #include "base/time/time.h" +#include "extensions/browser/api/declarative_net_request/action_tracker.h" #include "extensions/browser/api/declarative_net_request/utils.h" #include "extensions/common/extension_id.h" #include "extensions/common/permissions/permissions_data.h" @@ -61,6 +62,11 @@ class RulesetManager { // Valid iff |type| is |REDIRECT|. base::Optional<GURL> redirect_url; + // The ids of the extensions the action is attributed to. + // TODO(crbug.com/991420): This is not exactly correct for attributing + // an Action to the extension(s) for |REMOVE_HEADERS| rules. + std::vector<ExtensionId> extension_ids; + // Valid iff |type| is |REMOVE_HEADERS|. The vectors point to strings of // static storage duration. std::vector<const char*> request_headers_to_remove; @@ -124,6 +130,9 @@ class RulesetManager { // Sets the TestObserver. Client maintains ownership of |observer|. void SetObserverForTest(TestObserver* observer); + const ActionTracker& action_tracker() const { return action_tracker_; } + ActionTracker& action_tracker() { return action_tracker_; } + private: struct ExtensionRulesetData { ExtensionRulesetData(const ExtensionId& extension_id, @@ -187,6 +196,10 @@ class RulesetManager { // Non-owning pointer to TestObserver. TestObserver* test_observer_ = nullptr; + // Mutable because this is updated in multiple const methods where we create + // and return the appropriate action based on the rule matched. + mutable ActionTracker action_tracker_; + SEQUENCE_CHECKER(sequence_checker_); DISALLOW_COPY_AND_ASSIGN(RulesetManager); diff --git a/chromium/extensions/browser/api/declarative_net_request/ruleset_matcher.cc b/chromium/extensions/browser/api/declarative_net_request/ruleset_matcher.cc index 642f0a40222..0e8e5a3a45c 100644 --- a/chromium/extensions/browser/api/declarative_net_request/ruleset_matcher.cc +++ b/chromium/extensions/browser/api/declarative_net_request/ruleset_matcher.cc @@ -4,6 +4,7 @@ #include "extensions/browser/api/declarative_net_request/ruleset_matcher.h" +#include <algorithm> #include <limits> #include <utility> @@ -12,6 +13,7 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" +#include "base/strings/strcat.h" #include "base/timer/elapsed_timer.h" #include "content/public/common/resource_type.h" #include "extensions/browser/api/declarative_net_request/constants.h" @@ -21,6 +23,8 @@ #include "extensions/common/api/declarative_net_request.h" #include "extensions/common/api/declarative_net_request/utils.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" +#include "net/base/url_util.h" +#include "url/url_constants.h" namespace extensions { namespace declarative_net_request { @@ -77,8 +81,7 @@ flat_rule::ElementType GetElementType(const WebRequestInfo& request) { if (request.url.SchemeIsWSOrWSS()) return flat_rule::ElementType_WEBSOCKET; - return request.type.has_value() ? GetElementType(request.type.value()) - : flat_rule::ElementType_OTHER; + return GetElementType(request.type); } // Returns whether the request to |url| is third party to its |document_origin|. @@ -144,6 +147,156 @@ bool IsExtraHeadersMatcherInternal( return false; } +base::StringPiece CreateStringPiece(const ::flatbuffers::String& str) { + return base::StringPiece(str.c_str(), str.size()); +} + +// Returns true if the given |vec| is nullptr or empty. +template <typename T> +bool IsEmpty(const flatbuffers::Vector<T>* vec) { + return !vec || vec->size() == 0; +} + +// Performs any required query transformations on the |url|. Returns true if the +// query should be modified and populates |modified_query|. +bool GetModifiedQuery(const GURL& url, + const flat::UrlTransform& transform, + std::string* modified_query) { + DCHECK(modified_query); + + // |remove_query_params| should always be sorted. + DCHECK( + IsEmpty(transform.remove_query_params()) || + std::is_sorted(transform.remove_query_params()->begin(), + transform.remove_query_params()->end(), + [](const flatbuffers::String* x1, + const flatbuffers::String* x2) { return *x1 < *x2; })); + + // Return early if there's nothing to modify. + if (IsEmpty(transform.remove_query_params()) && + IsEmpty(transform.add_or_replace_query_params())) { + return false; + } + + std::vector<base::StringPiece> remove_query_params; + if (!IsEmpty(transform.remove_query_params())) { + remove_query_params.reserve(transform.remove_query_params()->size()); + for (const ::flatbuffers::String* str : *transform.remove_query_params()) + remove_query_params.push_back(CreateStringPiece(*str)); + } + + // We don't use a map from keys to vector of values to ensure the relative + // order of different params specified by the extension is respected. We use a + // std::list to support fast removal from middle of the list. Note that the + // key value pairs should already be escaped. + std::list<std::pair<base::StringPiece, base::StringPiece>> + add_or_replace_query_params; + if (!IsEmpty(transform.add_or_replace_query_params())) { + for (const flat::QueryKeyValue* query_pair : + *transform.add_or_replace_query_params()) { + DCHECK(query_pair->key()); + DCHECK(query_pair->value()); + add_or_replace_query_params.emplace_back( + CreateStringPiece(*query_pair->key()), + CreateStringPiece(*query_pair->value())); + } + } + + std::vector<std::string> query_parts; + + auto create_query_part = [](base::StringPiece key, base::StringPiece value) { + return base::StrCat({key, "=", value}); + }; + + bool query_changed = false; + for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) { + std::string key = it.GetKey(); + // Remove query param. + if (std::binary_search(remove_query_params.begin(), + remove_query_params.end(), key)) { + query_changed = true; + continue; + } + + auto replace_iterator = std::find_if( + add_or_replace_query_params.begin(), add_or_replace_query_params.end(), + [&key](const std::pair<base::StringPiece, base::StringPiece>& param) { + return param.first == key; + }); + + // Nothing to do. + if (replace_iterator == add_or_replace_query_params.end()) { + query_parts.push_back(create_query_part(key, it.GetValue())); + continue; + } + + // Replace query param. + query_changed = true; + query_parts.push_back(create_query_part(key, replace_iterator->second)); + add_or_replace_query_params.erase(replace_iterator); + } + + // Append any remaining query params. + for (const auto& params : add_or_replace_query_params) { + query_changed = true; + query_parts.push_back(create_query_part(params.first, params.second)); + } + + if (!query_changed) + return false; + + *modified_query = base::JoinString(query_parts, "&"); + return true; +} + +GURL GetTransformedURL(const RequestParams& params, + const flat::UrlTransform& transform) { + GURL::Replacements replacements; + + if (transform.scheme()) + replacements.SetSchemeStr(CreateStringPiece(*transform.scheme())); + + if (transform.host()) + replacements.SetHostStr(CreateStringPiece(*transform.host())); + + DCHECK(!(transform.clear_port() && transform.port())); + if (transform.clear_port()) + replacements.ClearPort(); + else if (transform.port()) + replacements.SetPortStr(CreateStringPiece(*transform.port())); + + DCHECK(!(transform.clear_path() && transform.path())); + if (transform.clear_path()) + replacements.ClearPath(); + else if (transform.path()) + replacements.SetPathStr(CreateStringPiece(*transform.path())); + + // |query| is defined outside the if conditions since url::Replacements does + // not own the strings it uses. + std::string query; + if (transform.clear_query()) { + replacements.ClearQuery(); + } else if (transform.query()) { + replacements.SetQueryStr(CreateStringPiece(*transform.query())); + } else if (GetModifiedQuery(*params.url, transform, &query)) { + replacements.SetQueryStr(query); + } + + DCHECK(!(transform.clear_fragment() && transform.fragment())); + if (transform.clear_fragment()) + replacements.ClearRef(); + else if (transform.fragment()) + replacements.SetRefStr(CreateStringPiece(*transform.fragment())); + + if (transform.password()) + replacements.SetPasswordStr(CreateStringPiece(*transform.password())); + + if (transform.username()) + replacements.SetUsernameStr(CreateStringPiece(*transform.username())); + + return params.url->ReplaceComponents(replacements); +} + } // namespace RequestParams::RequestParams(const WebRequestInfo& info) @@ -256,12 +409,22 @@ const flat_rule::UrlRule* RulesetMatcher::GetRedirectRule( // There must be a UrlRuleMetadata object corresponding to each redirect rule. DCHECK(metadata); DCHECK_EQ(metadata->id(), rule->id()); + DCHECK(metadata->redirect_url() || metadata->transform()); + + if (metadata->redirect_url()) + *redirect_url = GURL(CreateStringPiece(*metadata->redirect_url())); + else + *redirect_url = GetTransformedURL(params, *metadata->transform()); + + // Sanity check that we don't redirect to a javascript url. Specifying + // redirect to a javascript url and specifying javascript as a transform + // scheme is prohibited. In addition extensions can't intercept requests to + // javascript urls. Hence we should never end up with a javascript url here. + DCHECK(!redirect_url->SchemeIs(url::kJavaScriptScheme)); - *redirect_url = GURL(base::StringPiece(metadata->redirect_url()->c_str(), - metadata->redirect_url()->size())); - DCHECK(redirect_url->is_valid()); // Prevent a redirect loop where a URL continuously redirects to itself. - return *params.url == *redirect_url ? nullptr : rule; + return (redirect_url->is_valid() && *params.url != *redirect_url) ? rule + : nullptr; } const flat_rule::UrlRule* RulesetMatcher::GetUpgradeRule( diff --git a/chromium/extensions/browser/api/declarative_net_request/ruleset_matcher_unittest.cc b/chromium/extensions/browser/api/declarative_net_request/ruleset_matcher_unittest.cc index 084976913d5..3df466cbe58 100644 --- a/chromium/extensions/browser/api/declarative_net_request/ruleset_matcher_unittest.cc +++ b/chromium/extensions/browser/api/declarative_net_request/ruleset_matcher_unittest.cc @@ -9,6 +9,8 @@ #include "base/files/file_util.h" #include "base/logging.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" #include "components/url_pattern_index/flat/url_pattern_index_generated.h" #include "components/version_info/version_info.h" #include "extensions/browser/api/declarative_net_request/constants.h" @@ -69,7 +71,8 @@ TEST_F(RulesetMatcherTest, RedirectRule) { rule.condition->url_filter = std::string("google.com"); rule.priority = kMinValidPriority; rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("http://yahoo.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("http://yahoo.com"); std::unique_ptr<RulesetMatcher> matcher; ASSERT_TRUE(CreateVerifiedMatcher({rule}, CreateTemporarySource(), &matcher)); @@ -101,7 +104,8 @@ TEST_F(RulesetMatcherTest, PreventSelfRedirect) { rule.condition->url_filter = std::string("go*"); rule.priority = kMinValidPriority; rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("http://google.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("http://google.com"); std::unique_ptr<RulesetMatcher> matcher; ASSERT_TRUE(CreateVerifiedMatcher({rule}, CreateTemporarySource(), &matcher)); @@ -210,6 +214,197 @@ TEST_F(RulesetMatcherTest, RemoveHeaders) { EXPECT_EQ(current_mask, matcher->GetRemoveHeadersMask(params, current_mask)); } +// Tests a rule to redirect to an extension path. +TEST_F(RulesetMatcherTest, RedirectToExtensionPath) { + TestRule rule = CreateGenericRule(); + rule.condition->url_filter = std::string("example.com"); + rule.action->type = std::string("redirect"); + rule.priority = kMinValidPriority; + rule.action->redirect.emplace(); + rule.action->redirect->extension_path = "/path/newfile.js?query#fragment"; + + std::unique_ptr<RulesetMatcher> matcher; + const size_t kId = 1; + const size_t kPriority = 1; + const size_t kRuleCountLimit = 10; + const ExtensionId extension_id = "extension_id"; + ASSERT_TRUE(CreateVerifiedMatcher( + {rule}, + CreateTemporarySource(kId, kPriority, kRuleCountLimit, extension_id), + &matcher)); + + GURL example_url("http://example.com"); + RequestParams params; + params.url = &example_url; + + GURL redirect_url; + EXPECT_TRUE(matcher->GetRedirectRule(params, &redirect_url)); + GURL expected_redirect_url( + "chrome-extension://extension_id/path/newfile.js?query#fragment"); + EXPECT_EQ(expected_redirect_url, redirect_url); +} + +// Tests a rule to redirect to a static url. +TEST_F(RulesetMatcherTest, RedirectToStaticUrl) { + TestRule rule = CreateGenericRule(); + rule.condition->url_filter = std::string("example.com"); + rule.action->type = std::string("redirect"); + rule.priority = kMinValidPriority; + rule.action->redirect.emplace(); + rule.action->redirect->url = "https://google.com"; + + std::unique_ptr<RulesetMatcher> matcher; + ASSERT_TRUE(CreateVerifiedMatcher({rule}, CreateTemporarySource(), &matcher)); + + GURL example_url("http://example.com"); + RequestParams params; + params.url = &example_url; + + GURL redirect_url; + GURL expected_redirect_url("https://google.com"); + EXPECT_TRUE(matcher->GetRedirectRule(params, &redirect_url)); + EXPECT_EQ(expected_redirect_url, redirect_url); +} + +// Tests url transformation rules. +TEST_F(RulesetMatcherTest, UrlTransform) { + struct TestCase { + std::string url; + // Valid if a redirect is expected. + base::Optional<std::string> expected_redirect_url; + }; + + std::vector<TestCase> cases; + std::vector<TestRule> rules; + + auto create_transform_rule = [](size_t id, const std::string& filter) { + TestRule rule = CreateGenericRule(); + rule.id = id; + rule.condition->url_filter = filter; + rule.priority = kMinValidPriority; + rule.action->type = std::string("redirect"); + rule.action->redirect.emplace(); + rule.action->redirect->transform.emplace(); + return rule; + }; + + TestRule rule = create_transform_rule(1, "||1.com"); + rule.action->redirect->transform->scheme = "https"; + rules.push_back(rule); + cases.push_back({"http://1.com/path?query", "https://1.com/path?query"}); + + rule = create_transform_rule(2, "||2.com"); + rule.action->redirect->transform->scheme = "ftp"; + rule.action->redirect->transform->host = "ftp.host.com"; + rule.action->redirect->transform->port = "70"; + rules.push_back(rule); + cases.push_back( + {"http://2.com:100/path?query", "ftp://ftp.host.com:70/path?query"}); + + rule = create_transform_rule(3, "||3.com"); + rule.action->redirect->transform->port = ""; + rule.action->redirect->transform->path = ""; + rule.action->redirect->transform->query = "?new_query"; + rule.action->redirect->transform->fragment = "#fragment"; + rules.push_back(rule); + // The path separator '/' is output even when cleared, except when there is no + // authority, query and fragment. + cases.push_back( + {"http://3.com:100/path?query", "http://3.com/?new_query#fragment"}); + + rule = create_transform_rule(4, "||4.com"); + rule.action->redirect->transform->scheme = "http"; + rule.action->redirect->transform->path = " "; + rules.push_back(rule); + cases.push_back({"http://4.com/xyz", "http://4.com/%20"}); + + rule = create_transform_rule(5, "||5.com"); + rule.action->redirect->transform->path = "/"; + rule.action->redirect->transform->query = ""; + rule.action->redirect->transform->fragment = "#"; + rules.push_back(rule); + cases.push_back( + {"http://5.com:100/path?query#fragment", "http://5.com:100/#"}); + + rule = create_transform_rule(6, "||6.com"); + rule.action->redirect->transform->path = "/path?query"; + rules.push_back(rule); + // The "?" in path is url encoded since it's not part of the query. + cases.push_back({"http://6.com/xyz?q1", "http://6.com/path%3Fquery?q1"}); + + rule = create_transform_rule(7, "||7.com"); + rule.action->redirect->transform->username = "new_user"; + rule.action->redirect->transform->password = "new_pass"; + rules.push_back(rule); + cases.push_back( + {"http://user@7.com/xyz", "http://new_user:new_pass@7.com/xyz"}); + + auto make_query = [](const std::string& key, const std::string& value) { + TestRuleQueryKeyValue query; + query.key = key; + query.value = value; + return query; + }; + + rule = create_transform_rule(8, "||8.com"); + rule.action->redirect->transform->query_transform.emplace(); + rule.action->redirect->transform->query_transform->remove_params = + std::vector<std::string>({"r1", "r2"}); + rule.action->redirect->transform->query_transform->add_or_replace_params = + std::vector<TestRuleQueryKeyValue>( + {make_query("a1", "#"), make_query("a2", ""), + make_query("a1", "new2"), make_query("a1", "new3")}); + rules.push_back(rule); + cases.push_back( + {"http://8.com/" + "path?r1&r1=val1&a1=val1&r2=val&x3=val&a1=val2&a2=val&r1=val2", + "http://8.com/path?a1=%23&x3=val&a1=new2&a2=&a1=new3"}); + cases.push_back({"http://8.com/path?query", + "http://8.com/path?query=&a1=%23&a2=&a1=new2&a1=new3"}); + + rule = create_transform_rule(9, "||9.com"); + rule.action->redirect->transform->query_transform.emplace(); + rule.action->redirect->transform->query_transform->remove_params = + std::vector<std::string>({"r1", "r2"}); + rules.push_back(rule); + // No redirect is performed since the url won't change. + cases.push_back({"http://9.com/path?query#fragment", base::nullopt}); + + rule = create_transform_rule(10, "||10.com"); + rule.action->redirect->transform->query_transform.emplace(); + rule.action->redirect->transform->query_transform->remove_params = + std::vector<std::string>({"q1"}); + rule.action->redirect->transform->query_transform->add_or_replace_params = + std::vector<TestRuleQueryKeyValue>({make_query("q1", "new")}); + rules.push_back(rule); + cases.push_back( + {"https://10.com/path?q1=1&q1=2&q1=3", "https://10.com/path?q1=new"}); + + std::unique_ptr<RulesetMatcher> matcher; + ASSERT_TRUE(CreateVerifiedMatcher(rules, CreateTemporarySource(), &matcher)); + + for (const auto& test_case : cases) { + SCOPED_TRACE(base::StringPrintf("Testing url %s", test_case.url.c_str())); + + GURL url(test_case.url); + ASSERT_TRUE(url.is_valid()) << test_case.url; + RequestParams params; + params.url = &url; + + GURL redirect_url; + if (!test_case.expected_redirect_url) { + EXPECT_FALSE(matcher->GetRedirectRule(params, &redirect_url)) + << redirect_url.spec(); + continue; + } + + ASSERT_TRUE(GURL(*test_case.expected_redirect_url).is_valid()) + << *test_case.expected_redirect_url; + EXPECT_TRUE(matcher->GetRedirectRule(params, &redirect_url)); + EXPECT_EQ(*test_case.expected_redirect_url, redirect_url.spec()); + } +} + } // namespace } // namespace declarative_net_request } // namespace extensions diff --git a/chromium/extensions/browser/api/declarative_net_request/test_utils.cc b/chromium/extensions/browser/api/declarative_net_request/test_utils.cc index 84e800c6cfc..91236ec37a8 100644 --- a/chromium/extensions/browser/api/declarative_net_request/test_utils.cc +++ b/chromium/extensions/browser/api/declarative_net_request/test_utils.cc @@ -49,7 +49,7 @@ bool CreateVerifiedMatcher(const std::vector<TestRule>& rules, IndexAndPersistJSONRulesetResult result = source.IndexAndPersistJSONRulesetUnsafe(); if (!result.success) { - DCHECK(result.error.empty()); + DCHECK(result.error.empty()) << result.error; return false; } diff --git a/chromium/extensions/browser/api/declarative_net_request/utils.cc b/chromium/extensions/browser/api/declarative_net_request/utils.cc index 387bf4fedf9..5da9751ad42 100644 --- a/chromium/extensions/browser/api/declarative_net_request/utils.cc +++ b/chromium/extensions/browser/api/declarative_net_request/utils.cc @@ -33,7 +33,7 @@ namespace { // url_pattern_index.fbs. Whenever an extension with an indexed ruleset format // version different from the one currently used by Chrome is loaded, the // extension ruleset will be reindexed. -constexpr int kIndexedRulesetFormatVersion = 8; +constexpr int kIndexedRulesetFormatVersion = 11; // This static assert is meant to catch cases where // url_pattern_index::kUrlPatternIndexFormatVersion is incremented without @@ -150,8 +150,8 @@ void ClearRendererCacheOnNavigation() { if (content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { ClearRendererCacheOnUI(); } else { - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ClearRendererCacheOnUI)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ClearRendererCacheOnUI)); } } diff --git a/chromium/extensions/browser/api/declarative_webrequest/webrequest_action.cc b/chromium/extensions/browser/api/declarative_webrequest/webrequest_action.cc index 8f4bd4475f5..adb529d8279 100644 --- a/chromium/extensions/browser/api/declarative_webrequest/webrequest_action.cc +++ b/chromium/extensions/browser/api/declarative_webrequest/webrequest_action.cc @@ -12,7 +12,6 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" -#include "content/public/browser/resource_request_info.h" #include "content/public/common/url_constants.h" #include "extensions/browser/api/declarative/deduping_factory.h" #include "extensions/browser/api/declarative_webrequest/request_stage.h" @@ -30,7 +29,6 @@ #include "net/http/http_util.h" #include "third_party/re2/src/re2/re2.h" -using content::ResourceRequestInfo; using extension_web_request_api_helpers::EventResponseDelta; namespace extensions { @@ -118,7 +116,7 @@ scoped_refptr<const WebRequestAction> CallConstructorFactoryMethod( const base::Value* value, std::string* error, bool* bad_message) { - return scoped_refptr<const WebRequestAction>(new T); + return base::MakeRefCounted<T>(); } scoped_refptr<const WebRequestAction> CreateRedirectRequestAction( diff --git a/chromium/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute.cc b/chromium/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute.cc index 07d73657aa5..de9c8af1e1b 100644 --- a/chromium/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute.cc +++ b/chromium/extensions/browser/api/declarative_webrequest/webrequest_condition_attribute.cc @@ -17,7 +17,6 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" -#include "content/public/browser/resource_request_info.h" #include "extensions/browser/api/declarative/deduping_factory.h" #include "extensions/browser/api/declarative_webrequest/request_stage.h" #include "extensions/browser/api/declarative_webrequest/webrequest_condition.h" diff --git a/chromium/extensions/browser/api/device_permissions_manager.cc b/chromium/extensions/browser/api/device_permissions_manager.cc index 086987d0e3d..1df437f38e3 100644 --- a/chromium/extensions/browser/api/device_permissions_manager.cc +++ b/chromium/extensions/browser/api/device_permissions_manager.cc @@ -9,6 +9,7 @@ #include <utility> #include "base/bind.h" +#include "base/memory/scoped_refptr.h" #include "base/memory/singleton.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" @@ -225,11 +226,11 @@ scoped_refptr<DevicePermissionEntry> ReadDevicePermissionEntry( } if (type == kDeviceTypeUsb) { - return new DevicePermissionEntry( + return base::MakeRefCounted<DevicePermissionEntry>( DevicePermissionEntry::Type::USB, vendor_id, product_id, serial_number, manufacturer_string, product_string, last_used); } else if (type == kDeviceTypeHid) { - return new DevicePermissionEntry( + return base::MakeRefCounted<DevicePermissionEntry>( DevicePermissionEntry::Type::HID, vendor_id, product_id, serial_number, base::string16(), product_string, last_used); } @@ -562,8 +563,7 @@ void DevicePermissionsManager::AllowHidDevice( DCHECK(thread_checker_.CalledOnValidThread()); DevicePermissions* device_permissions = GetForExtension(extension_id); - scoped_refptr<DevicePermissionEntry> device_entry( - new DevicePermissionEntry(device)); + auto device_entry = base::MakeRefCounted<DevicePermissionEntry>(device); if (device_entry->IsPersistent()) { for (const auto& entry : device_permissions->entries()) { diff --git a/chromium/extensions/browser/api/device_permissions_prompt.cc b/chromium/extensions/browser/api/device_permissions_prompt.cc index f28fa322407..83cd02e3452 100644 --- a/chromium/extensions/browser/api/device_permissions_prompt.cc +++ b/chromium/extensions/browser/api/device_permissions_prompt.cc @@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/i18n/message_formatter.h" +#include "base/memory/scoped_refptr.h" #include "base/scoped_observer.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -367,8 +368,8 @@ void DevicePermissionsPrompt::AskForUsbDevices( bool multiple, std::vector<UsbDeviceFilterPtr> filters, const UsbDevicesCallback& callback) { - prompt_ = new UsbDevicePermissionsPrompt(extension, context, multiple, - std::move(filters), callback); + prompt_ = base::MakeRefCounted<UsbDevicePermissionsPrompt>( + extension, context, multiple, std::move(filters), callback); ShowDialog(); } @@ -378,8 +379,8 @@ void DevicePermissionsPrompt::AskForHidDevices( bool multiple, const std::vector<HidDeviceFilter>& filters, const HidDevicesCallback& callback) { - prompt_ = new HidDevicePermissionsPrompt(extension, context, multiple, - filters, callback); + prompt_ = base::MakeRefCounted<HidDevicePermissionsPrompt>( + extension, context, multiple, filters, callback); ShowDialog(); } diff --git a/chromium/extensions/browser/api/diagnostics/diagnostics_api.h b/chromium/extensions/browser/api/diagnostics/diagnostics_api.h index 9f45b96b7ad..d566dec7c72 100644 --- a/chromium/extensions/browser/api/diagnostics/diagnostics_api.h +++ b/chromium/extensions/browser/api/diagnostics/diagnostics_api.h @@ -14,7 +14,7 @@ namespace extensions { -class DiagnosticsSendPacketFunction : public UIThreadExtensionFunction { +class DiagnosticsSendPacketFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("diagnostics.sendPacket", DIAGNOSTICS_SENDPACKET) @@ -23,7 +23,7 @@ class DiagnosticsSendPacketFunction : public UIThreadExtensionFunction { protected: ~DiagnosticsSendPacketFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: diff --git a/chromium/extensions/browser/api/display_source/display_source_api.h b/chromium/extensions/browser/api/display_source/display_source_api.h index d36e630a502..1f0a34ce575 100644 --- a/chromium/extensions/browser/api/display_source/display_source_api.h +++ b/chromium/extensions/browser/api/display_source/display_source_api.h @@ -11,8 +11,7 @@ namespace extensions { -class DisplaySourceGetAvailableSinksFunction - : public UIThreadExtensionFunction { +class DisplaySourceGetAvailableSinksFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("displaySource.getAvailableSinks", DISPLAYSOURCE_GETAVAILABLESINKS) @@ -29,8 +28,7 @@ class DisplaySourceGetAvailableSinksFunction DISALLOW_COPY_AND_ASSIGN(DisplaySourceGetAvailableSinksFunction); }; -class DisplaySourceRequestAuthenticationFunction - : public UIThreadExtensionFunction { +class DisplaySourceRequestAuthenticationFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("displaySource.requestAuthentication", DISPLAYSOURCE_REQUESTAUTHENTICATION) diff --git a/chromium/extensions/browser/api/display_source/display_source_apitestbase.cc b/chromium/extensions/browser/api/display_source/display_source_apitestbase.cc index 21541a9ba6e..c46d83ffff2 100644 --- a/chromium/extensions/browser/api/display_source/display_source_apitestbase.cc +++ b/chromium/extensions/browser/api/display_source/display_source_apitestbase.cc @@ -336,9 +336,9 @@ void MockDisplaySourceConnectionDelegate::Connect( // Bind sink to udp socket at this stage // And store udp port to udp_port_ string in order to be used - // In a message exchange. Then make a base::PostTaskWithTraits + // In a message exchange. Then make a base::PostTask // on UI thread and call OnSinkConnected() to proceed with the test - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&MockDisplaySourceConnectionDelegate::BindToUdpSocket, base::Unretained(this))); @@ -431,8 +431,8 @@ EnqueueSinkMessage(std::string message) { AdaptMessagePattern(found_clientport_key, kClientPortKey, kUdpPortLength, udp_port_, message); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(message_received_cb_, message)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(message_received_cb_, message)); } void MockDisplaySourceConnectionDelegate:: @@ -487,7 +487,7 @@ void MockDisplaySourceConnectionDelegate::BindToUdpSocket() { udp_port_ = std::to_string(port); // When we got an udp socket established and udp port is known // Change sink's status to connected and proceed with the test. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&MockDisplaySourceConnectionDelegate::OnSinkConnected, base::Unretained(this))); @@ -524,7 +524,7 @@ void MockDisplaySourceConnectionDelegate::OnMediaPacketReceived( // We received at least one media packet. // Test is completed. socket_->Close(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&MockDisplaySourceConnectionDelegate::Disconnect, base::Unretained(this), StringCallback())); diff --git a/chromium/extensions/browser/api/display_source/wifi_display/wifi_display_media_service_impl.cc b/chromium/extensions/browser/api/display_source/wifi_display/wifi_display_media_service_impl.cc index c5dde5e968a..7a00e4f086c 100644 --- a/chromium/extensions/browser/api/display_source/wifi_display/wifi_display_media_service_impl.cc +++ b/chromium/extensions/browser/api/display_source/wifi_display/wifi_display_media_service_impl.cc @@ -56,7 +56,7 @@ void WiFiDisplayMediaServiceImpl::Create( void WiFiDisplayMediaServiceImpl::BindToRequest( mojom::WiFiDisplayMediaServiceRequest request, content::RenderFrameHost* render_frame_host) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(WiFiDisplayMediaServiceImpl::Create, std::move(request))); } diff --git a/chromium/extensions/browser/api/dns/dns_api.h b/chromium/extensions/browser/api/dns/dns_api.h index 65e57334c70..2c63292b10b 100644 --- a/chromium/extensions/browser/api/dns/dns_api.h +++ b/chromium/extensions/browser/api/dns/dns_api.h @@ -15,7 +15,7 @@ namespace extensions { -class DnsResolveFunction : public UIThreadExtensionFunction, +class DnsResolveFunction : public ExtensionFunction, public network::ResolveHostClientBase { public: DECLARE_EXTENSION_FUNCTION("dns.resolve", DNS_RESOLVE) @@ -25,7 +25,7 @@ class DnsResolveFunction : public UIThreadExtensionFunction, protected: ~DnsResolveFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: diff --git a/chromium/extensions/browser/api/document_scan/document_scan_api.h b/chromium/extensions/browser/api/document_scan/document_scan_api.h index b8ac8b7273b..ba490af6616 100644 --- a/chromium/extensions/browser/api/document_scan/document_scan_api.h +++ b/chromium/extensions/browser/api/document_scan/document_scan_api.h @@ -17,7 +17,7 @@ namespace extensions { namespace api { -class DocumentScanScanFunction : public UIThreadExtensionFunction { +class DocumentScanScanFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("documentScan.scan", DOCUMENT_SCAN_SCAN) DocumentScanScanFunction(); @@ -25,7 +25,7 @@ class DocumentScanScanFunction : public UIThreadExtensionFunction { protected: ~DocumentScanScanFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: diff --git a/chromium/extensions/browser/api/document_scan/document_scan_interface_chromeos_unittest.cc b/chromium/extensions/browser/api/document_scan/document_scan_interface_chromeos_unittest.cc index 57aff6c6e1d..7eaf20d94ce 100644 --- a/chromium/extensions/browser/api/document_scan/document_scan_interface_chromeos_unittest.cc +++ b/chromium/extensions/browser/api/document_scan/document_scan_interface_chromeos_unittest.cc @@ -9,7 +9,7 @@ #include "base/bind.h" #include "base/run_loop.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_lorgnette_manager_client.h" #include "testing/gtest/include/gtest/gtest.h" @@ -35,7 +35,7 @@ class DocumentScanInterfaceChromeosTest : public testing::Test { } protected: - base::test::ScopedTaskEnvironment scoped_task_environment_; + base::test::TaskEnvironment task_environment_; DocumentScanInterfaceChromeos scan_interface_; }; diff --git a/chromium/extensions/browser/api/execute_code_function.cc b/chromium/extensions/browser/api/execute_code_function.cc index 26854abe48d..002b4997fb9 100644 --- a/chromium/extensions/browser/api/execute_code_function.cc +++ b/chromium/extensions/browser/api/execute_code_function.cc @@ -245,9 +245,10 @@ bool ExecuteCodeFunction::LoadFile(const std::string& file, std::unique_ptr<std::string> data( new std::string(resource.data(), resource.size())); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&ExecuteCodeFunction:: GetFileURLAndLocalizeComponentResourceInBackground, this, std::move(data), extension_id, extension_path, diff --git a/chromium/extensions/browser/api/execute_code_function.h b/chromium/extensions/browser/api/execute_code_function.h index ceb911afe6e..1971898ab57 100644 --- a/chromium/extensions/browser/api/execute_code_function.h +++ b/chromium/extensions/browser/api/execute_code_function.h @@ -17,7 +17,7 @@ namespace extensions { // Base class for javascript code injection. // This is used by both chrome.webview.executeScript and // chrome.tabs.executeScript. -class ExecuteCodeFunction : public UIThreadExtensionFunction { +class ExecuteCodeFunction : public ExtensionFunction { public: ExecuteCodeFunction(); diff --git a/chromium/extensions/browser/api/extensions_api_client.cc b/chromium/extensions/browser/api/extensions_api_client.cc index bac64cb90f6..825127022e8 100644 --- a/chromium/extensions/browser/api/extensions_api_client.cc +++ b/chromium/extensions/browser/api/extensions_api_client.cc @@ -54,6 +54,15 @@ void ExtensionsAPIClient::NotifyWebRequestWithheld( int render_frame_id, const ExtensionId& extension_id) {} +void ExtensionsAPIClient::UpdateActionCount(content::BrowserContext* context, + const ExtensionId& extension_id, + int tab_id, + int action_count, + bool clear_badge_text) {} + +void ExtensionsAPIClient::ClearActionCount(content::BrowserContext* context, + const Extension& extension) {} + AppViewGuestDelegate* ExtensionsAPIClient::CreateAppViewGuestDelegate() const { return NULL; } diff --git a/chromium/extensions/browser/api/extensions_api_client.h b/chromium/extensions/browser/api/extensions_api_client.h index 1b6021c4e8b..b9b9144eaa3 100644 --- a/chromium/extensions/browser/api/extensions_api_client.h +++ b/chromium/extensions/browser/api/extensions_api_client.h @@ -15,6 +15,7 @@ #include "extensions/browser/api/declarative_content/content_rules_registry.h" #include "extensions/browser/api/storage/settings_namespace.h" #include "extensions/common/api/clipboard.h" +#include "extensions/common/extension.h" #include "extensions/common/extension_id.h" class GURL; @@ -109,6 +110,19 @@ class ExtensionsAPIClient { int render_frame_id, const ExtensionId& extension_id); + // Updates an extension's matched action count stored in an ExtensionAction + // and optionally clears the extension's explicitly set badge text for the + // tab specified by |tab_id|. + virtual void UpdateActionCount(content::BrowserContext* context, + const ExtensionId& extension_id, + int tab_id, + int action_count, + bool clear_badge_text); + + // Clears an extension's matched action count stored in an ExtensionAction. + virtual void ClearActionCount(content::BrowserContext* context, + const Extension& extension); + // Creates the AppViewGuestDelegate. virtual AppViewGuestDelegate* CreateAppViewGuestDelegate() const; diff --git a/chromium/extensions/browser/api/feedback_private/BUILD.gn b/chromium/extensions/browser/api/feedback_private/BUILD.gn index a5ad9d228a8..d5067651ef3 100644 --- a/chromium/extensions/browser/api/feedback_private/BUILD.gn +++ b/chromium/extensions/browser/api/feedback_private/BUILD.gn @@ -36,6 +36,9 @@ source_set("feedback_private") { "log_source_resource.h", ] - deps += [ "//ash/public/cpp" ] + deps += [ + "//ash/public/cpp", + "//chromeos/services/assistant/public/mojom", + ] } } diff --git a/chromium/extensions/browser/api/feedback_private/DEPS b/chromium/extensions/browser/api/feedback_private/DEPS index d3e51a7729a..89fb4ef9c62 100644 --- a/chromium/extensions/browser/api/feedback_private/DEPS +++ b/chromium/extensions/browser/api/feedback_private/DEPS @@ -1,4 +1,4 @@ include_rules = [ "+components/feedback", - "+ash/public/interfaces", + "+ash/public/cpp", ] diff --git a/chromium/extensions/browser/api/feedback_private/feedback_private_api.h b/chromium/extensions/browser/api/feedback_private/feedback_private_api.h index 9c526d4c99c..af2d73fcab0 100644 --- a/chromium/extensions/browser/api/feedback_private/feedback_private_api.h +++ b/chromium/extensions/browser/api/feedback_private/feedback_private_api.h @@ -68,7 +68,7 @@ class FeedbackPrivateAPI : public BrowserContextKeyedAPI { }; // Feedback strings. -class FeedbackPrivateGetStringsFunction : public UIThreadExtensionFunction { +class FeedbackPrivateGetStringsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("feedbackPrivate.getStrings", FEEDBACKPRIVATE_GETSTRINGS) @@ -88,7 +88,7 @@ class FeedbackPrivateGetStringsFunction : public UIThreadExtensionFunction { static base::Closure* test_callback_; }; -class FeedbackPrivateGetUserEmailFunction : public UIThreadExtensionFunction { +class FeedbackPrivateGetUserEmailFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("feedbackPrivate.getUserEmail", FEEDBACKPRIVATE_GETUSEREMAIL) @@ -98,8 +98,7 @@ class FeedbackPrivateGetUserEmailFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class FeedbackPrivateGetSystemInformationFunction - : public UIThreadExtensionFunction { +class FeedbackPrivateGetSystemInformationFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("feedbackPrivate.getSystemInformation", FEEDBACKPRIVATE_GETSYSTEMINFORMATION) @@ -114,7 +113,7 @@ class FeedbackPrivateGetSystemInformationFunction // This function only reads from actual log sources on Chrome OS. On other // platforms, it just returns EmptyResponse(). -class FeedbackPrivateReadLogSourceFunction : public UIThreadExtensionFunction { +class FeedbackPrivateReadLogSourceFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("feedbackPrivate.readLogSource", FEEDBACKPRIVATE_READLOGSOURCE) @@ -130,7 +129,7 @@ class FeedbackPrivateReadLogSourceFunction : public UIThreadExtensionFunction { #endif // defined(OS_CHROMEOS) }; -class FeedbackPrivateSendFeedbackFunction : public UIThreadExtensionFunction { +class FeedbackPrivateSendFeedbackFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("feedbackPrivate.sendFeedback", FEEDBACKPRIVATE_SENDFEEDBACK) @@ -146,8 +145,7 @@ class FeedbackPrivateSendFeedbackFunction : public UIThreadExtensionFunction { void OnCompleted(api::feedback_private::LandingPageType type, bool success); }; -class FeedbackPrivateLoginFeedbackCompleteFunction - : public UIThreadExtensionFunction { +class FeedbackPrivateLoginFeedbackCompleteFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("feedbackPrivate.loginFeedbackComplete", FEEDBACKPRIVATE_LOGINFEEDBACKCOMPLETE) diff --git a/chromium/extensions/browser/api/feedback_private/feedback_private_api_chromeos_unittest.cc b/chromium/extensions/browser/api/feedback_private/feedback_private_api_chromeos_unittest.cc index 2163ddbb96d..f763c836cf1 100644 --- a/chromium/extensions/browser/api/feedback_private/feedback_private_api_chromeos_unittest.cc +++ b/chromium/extensions/browser/api/feedback_private/feedback_private_api_chromeos_unittest.cc @@ -207,7 +207,7 @@ TEST_F(FeedbackPrivateApiUnittest, Anonymize) { EXPECT_TRUE( RunReadLogSourceFunction(params, &result_reader_id, &result_string)); EXPECT_EQ(*params.reader_id, result_reader_id); - EXPECT_EQ("11:22:33:00:00:01", result_string); + EXPECT_EQ("[MAC OUI=11:22:33 IFACE=1]", result_string); } TEST_F(FeedbackPrivateApiUnittest, ReadLogSourceMultipleSources) { diff --git a/chromium/extensions/browser/api/feedback_private/feedback_service.cc b/chromium/extensions/browser/api/feedback_private/feedback_service.cc index 0df3feacd89..9678af8350d 100644 --- a/chromium/extensions/browser/api/feedback_private/feedback_service.cc +++ b/chromium/extensions/browser/api/feedback_private/feedback_service.cc @@ -17,8 +17,8 @@ #include "net/base/network_change_notifier.h" #if defined(OS_CHROMEOS) -#include "ash/public/interfaces/assistant_controller.mojom.h" -#include "ash/public/interfaces/constants.mojom.h" +#include "ash/public/cpp/assistant/assistant_interface_binder.h" +#include "chromeos/services/assistant/public/mojom/assistant.mojom.h" #include "extensions/browser/api/feedback_private/log_source_access_manager.h" #include "services/service_manager/public/cpp/connector.h" #endif // defined(OS_CHROMEOS) @@ -102,9 +102,9 @@ void FeedbackService::CompleteSendFeedback( #if defined(OS_CHROMEOS) // Send feedback to Assistant server if triggered from Google Assistant. if (feedback_data->from_assistant()) { - ash::mojom::AssistantControllerPtr assistant_controller; - content::BrowserContext::GetConnectorFor(browser_context_) - ->BindInterface(ash::mojom::kServiceName, &assistant_controller); + chromeos::assistant::mojom::AssistantControllerPtr assistant_controller; + ash::AssistantInterfaceBinder::GetInstance()->BindController( + mojo::MakeRequest(&assistant_controller)); assistant_controller->SendAssistantFeedback( feedback_data->assistant_debug_info_allowed(), feedback_data->description(), feedback_data->image()); diff --git a/chromium/extensions/browser/api/feedback_private/log_source_access_manager.cc b/chromium/extensions/browser/api/feedback_private/log_source_access_manager.cc index 2b9001c227c..a214d89b2b0 100644 --- a/chromium/extensions/browser/api/feedback_private/log_source_access_manager.cc +++ b/chromium/extensions/browser/api/feedback_private/log_source_access_manager.cc @@ -74,16 +74,15 @@ void AnonymizeResults( LogSourceAccessManager::LogSourceAccessManager(content::BrowserContext* context) : context_(context), tick_clock_(base::DefaultTickClock::GetInstance()), - task_runner_for_anonymizer_(base::CreateSequencedTaskRunnerWithTraits( + task_runner_for_anonymizer_(base::CreateSequencedTaskRunner( // User visible as the feedback_api is used by the Chrome (OS) // feedback extension while the user may be looking at a spinner. - {base::TaskPriority::USER_VISIBLE, + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})), anonymizer_container_( base::MakeRefCounted<feedback::AnonymizerToolContainer>( task_runner_for_anonymizer_, - /* first_party_extension_ids= */ nullptr)), - weak_factory_(this) {} + /* first_party_extension_ids= */ nullptr)) {} LogSourceAccessManager::~LogSourceAccessManager() {} diff --git a/chromium/extensions/browser/api/feedback_private/log_source_access_manager.h b/chromium/extensions/browser/api/feedback_private/log_source_access_manager.h index 56d409a9734..1a5ac8fd3bf 100644 --- a/chromium/extensions/browser/api/feedback_private/log_source_access_manager.h +++ b/chromium/extensions/browser/api/feedback_private/log_source_access_manager.h @@ -159,7 +159,7 @@ class LogSourceAccessManager { scoped_refptr<base::SequencedTaskRunner> task_runner_for_anonymizer_; scoped_refptr<feedback::AnonymizerToolContainer> anonymizer_container_; - base::WeakPtrFactory<LogSourceAccessManager> weak_factory_; + base::WeakPtrFactory<LogSourceAccessManager> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LogSourceAccessManager); }; diff --git a/chromium/extensions/browser/api/file_handlers/app_file_handler_util.cc b/chromium/extensions/browser/api/file_handlers/app_file_handler_util.cc index 96fd9b31d89..5e1e198f29a 100644 --- a/chromium/extensions/browser/api/file_handlers/app_file_handler_util.cc +++ b/chromium/extensions/browser/api/file_handlers/app_file_handler_util.cc @@ -4,13 +4,17 @@ #include "extensions/browser/api/file_handlers/app_file_handler_util.h" +#include <vector> + #include "base/bind.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/memory/scoped_refptr.h" #include "base/task/post_task.h" #include "base/task/task_traits.h" #include "build/build_config.h" +#include "components/services/app_service/public/cpp/file_handler_info.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" @@ -37,7 +41,7 @@ const char kSecurityError[] = "Security error"; namespace { -bool FileHandlerCanHandleFileWithExtension(const FileHandlerInfo& handler, +bool FileHandlerCanHandleFileWithExtension(const apps::FileHandlerInfo& handler, const base::FilePath& path) { for (auto extension = handler.extensions.cbegin(); extension != handler.extensions.cend(); ++extension) { @@ -66,7 +70,7 @@ bool FileHandlerCanHandleFileWithExtension(const FileHandlerInfo& handler, return false; } -bool FileHandlerCanHandleFileWithMimeType(const FileHandlerInfo& handler, +bool FileHandlerCanHandleFileWithMimeType(const apps::FileHandlerInfo& handler, const std::string& mime_type) { for (auto type = handler.types.cbegin(); type != handler.types.cend(); ++type) { @@ -169,8 +173,10 @@ void WritableFileChecker::Check() { continue; } #endif - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::TaskPriority::USER_BLOCKING, base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::USER_BLOCKING, + base::MayBlock()}, base::Bind(&PrepareNativeLocalFileForWritableApp, path, is_directory), base::Bind(&WritableFileChecker::OnPrepareFileDone, this, path)); } @@ -206,8 +212,8 @@ void WritableFileChecker::OnPrepareFileDone(const base::FilePath& path, } // namespace -const FileHandlerInfo* FileHandlerForId(const Extension& app, - const std::string& handler_id) { +const apps::FileHandlerInfo* FileHandlerForId(const Extension& app, + const std::string& handler_id) { const FileHandlersInfo* file_handlers = FileHandlers::GetFileHandlers(&app); if (!file_handlers) return NULL; @@ -222,17 +228,24 @@ const FileHandlerInfo* FileHandlerForId(const Extension& app, std::vector<FileHandlerMatch> FindFileHandlerMatchesForEntries( const Extension& app, const std::vector<EntryInfo>& entries) { - std::vector<FileHandlerMatch> matches; if (entries.empty()) - return matches; + return std::vector<FileHandlerMatch>(); // Look for file handlers which can handle all the MIME types // or file name extensions specified. const FileHandlersInfo* file_handlers = FileHandlers::GetFileHandlers(&app); if (!file_handlers) - return matches; + return std::vector<FileHandlerMatch>(); + + return MatchesFromFileHandlersForEntries(*file_handlers, entries); +} + +std::vector<FileHandlerMatch> MatchesFromFileHandlersForEntries( + const FileHandlersInfo& file_handlers, + const std::vector<EntryInfo>& entries) { + std::vector<FileHandlerMatch> matches; - for (const FileHandlerInfo& handler : *file_handlers) { + for (const apps::FileHandlerInfo& handler : file_handlers) { bool handles_all_types = true; FileHandlerMatch match; @@ -266,7 +279,7 @@ std::vector<FileHandlerMatch> FindFileHandlerMatchesForEntries( return matches; } -bool FileHandlerCanHandleEntry(const FileHandlerInfo& handler, +bool FileHandlerCanHandleEntry(const apps::FileHandlerInfo& handler, const EntryInfo& entry) { if (entry.is_directory) return handler.include_directories; @@ -313,8 +326,8 @@ void PrepareFilesForWritableApp( const std::set<base::FilePath>& directory_paths, const base::Closure& on_success, const base::Callback<void(const base::FilePath&)>& on_failure) { - scoped_refptr<WritableFileChecker> checker(new WritableFileChecker( - paths, context, directory_paths, on_success, on_failure)); + auto checker = base::MakeRefCounted<WritableFileChecker>( + paths, context, directory_paths, on_success, on_failure); checker->Check(); } diff --git a/chromium/extensions/browser/api/file_handlers/app_file_handler_util.h b/chromium/extensions/browser/api/file_handlers/app_file_handler_util.h index 428f0343089..c9694025f18 100644 --- a/chromium/extensions/browser/api/file_handlers/app_file_handler_util.h +++ b/chromium/extensions/browser/api/file_handlers/app_file_handler_util.h @@ -18,10 +18,13 @@ namespace content { class BrowserContext; } +namespace apps { +struct FileHandlerInfo; +} + namespace extensions { struct EntryInfo; -struct FileHandlerInfo; struct FileHandlerMatch; struct GrantedFileEntry; @@ -34,8 +37,8 @@ extern const char kSecurityError[]; // Returns the file handler with the specified |handler_id|, or NULL if there // is no such handler. -const FileHandlerInfo* FileHandlerForId(const Extension& app, - const std::string& handler_id); +const apps::FileHandlerInfo* FileHandlerForId(const Extension& app, + const std::string& handler_id); // Returns the handlers that can handle all files in |entries| // along with metadata about how the handler matched (MIME or file extension) @@ -43,7 +46,13 @@ std::vector<FileHandlerMatch> FindFileHandlerMatchesForEntries( const Extension& extension, const std::vector<EntryInfo>& entries); -bool FileHandlerCanHandleEntry(const FileHandlerInfo& handler, +// Returns the handlers that can handle all files in |entries| +// along with metadata about how the handler matched (MIME or file) +std::vector<FileHandlerMatch> MatchesFromFileHandlersForEntries( + const FileHandlersInfo& file_handlers, + const std::vector<EntryInfo>& entries); + +bool FileHandlerCanHandleEntry(const apps::FileHandlerInfo& handler, const EntryInfo& entry); // Creates a new file entry and allows |renderer_id| to access |path|. This diff --git a/chromium/extensions/browser/api/file_handlers/app_file_handler_util_unittest.cc b/chromium/extensions/browser/api/file_handlers/app_file_handler_util_unittest.cc index dffb7ab3ed2..0275a929baf 100644 --- a/chromium/extensions/browser/api/file_handlers/app_file_handler_util_unittest.cc +++ b/chromium/extensions/browser/api/file_handlers/app_file_handler_util_unittest.cc @@ -4,6 +4,7 @@ #include "extensions/browser/api/file_handlers/app_file_handler_util.h" +#include "components/services/app_service/public/cpp/file_handler_info.h" #include "extensions/browser/entry_info.h" #include "testing/gtest/include/gtest/gtest.h" @@ -11,15 +12,16 @@ namespace extensions { namespace app_file_handler_util { namespace { -FileHandlerInfo CreateHandlerInfoFromExtension(const std::string& extension) { - FileHandlerInfo handler_info; +apps::FileHandlerInfo CreateHandlerInfoFromExtension( + const std::string& extension) { + apps::FileHandlerInfo handler_info; handler_info.extensions.insert(extension); return handler_info; } -FileHandlerInfo CreateHandlerInfoFromIncludeDirectories( +apps::FileHandlerInfo CreateHandlerInfoFromIncludeDirectories( bool include_directories) { - FileHandlerInfo handler_info; + apps::FileHandlerInfo handler_info; handler_info.include_directories = include_directories; return handler_info; } diff --git a/chromium/extensions/browser/api/file_handlers/directory_util.cc b/chromium/extensions/browser/api/file_handlers/directory_util.cc index 3db372846a8..168a4215444 100644 --- a/chromium/extensions/browser/api/file_handlers/directory_util.cc +++ b/chromium/extensions/browser/api/file_handlers/directory_util.cc @@ -43,8 +43,8 @@ void EntryIsDirectory(content::BrowserContext* context, } #endif - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::Bind(&GetIsDirectoryFromFileInfo, path), callback); } diff --git a/chromium/extensions/browser/api/file_handlers/directory_util_unittest.cc b/chromium/extensions/browser/api/file_handlers/directory_util_unittest.cc index 9ecf7fa85eb..25b96ff1ecc 100644 --- a/chromium/extensions/browser/api/file_handlers/directory_util_unittest.cc +++ b/chromium/extensions/browser/api/file_handlers/directory_util_unittest.cc @@ -14,8 +14,8 @@ #include "base/files/file_util.h" #include "base/run_loop.h" #include "content/public/browser/browser_thread.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" #include "extensions/browser/api/extensions_api_client.h" #include "testing/gtest/include/gtest/gtest.h" @@ -45,7 +45,7 @@ class IsDirectoryUtilTest : public testing::Test { EXPECT_TRUE(base::CreateTemporaryFile(&file_path_)); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; ExtensionsAPIClient extensions_api_client_; content::TestBrowserContext context_; base::FilePath dir_path_; diff --git a/chromium/extensions/browser/api/file_handlers/mime_util.cc b/chromium/extensions/browser/api/file_handlers/mime_util.cc index de7849c8c1f..b212e88d11b 100644 --- a/chromium/extensions/browser/api/file_handlers/mime_util.cc +++ b/chromium/extensions/browser/api/file_handlers/mime_util.cc @@ -84,8 +84,8 @@ void OnGetMimeTypeFromMetadataForNonNativeLocalPathCompleted( std::unique_ptr<std::string> mime_type_from_extension(new std::string); std::string* const mime_type_from_extension_ptr = mime_type_from_extension.get(); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::Bind(base::IgnoreResult(&net::GetMimeTypeFromFile), local_path, mime_type_from_extension_ptr), base::Bind(&OnGetMimeTypeFromFileForNonNativeLocalPathCompleted, @@ -126,8 +126,8 @@ void OnGetMimeTypeFromFileForNativeLocalPathCompleted( std::unique_ptr<std::string> sniffed_mime_type( new std::string(kMimeTypeApplicationOctetStream)); std::string* const sniffed_mime_type_ptr = sniffed_mime_type.get(); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::Bind(&SniffMimeType, local_path, sniffed_mime_type_ptr), base::Bind(&OnSniffMimeTypeForNativeLocalPathCompleted, base::Passed(&sniffed_mime_type), callback)); @@ -158,8 +158,8 @@ void GetMimeTypeForLocalPath( std::unique_ptr<std::string> mime_type_from_extension(new std::string); std::string* const mime_type_from_extension_ptr = mime_type_from_extension.get(); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::Bind(base::IgnoreResult(&net::GetMimeTypeFromFile), local_path, mime_type_from_extension_ptr), base::Bind(&OnGetMimeTypeFromFileForNativeLocalPathCompleted, local_path, diff --git a/chromium/extensions/browser/api/file_system/file_system_api.cc b/chromium/extensions/browser/api/file_system/file_system_api.cc index 176fedf6f1c..b809c614d13 100644 --- a/chromium/extensions/browser/api/file_system/file_system_api.cc +++ b/chromium/extensions/browser/api/file_system/file_system_api.cc @@ -186,8 +186,8 @@ void PassFileInfoToUIThread(const FileInfoOptCallback& callback, DCHECK_CURRENTLY_ON(content::BrowserThread::IO); std::unique_ptr<base::File::Info> file_info( result == base::File::FILE_OK ? new base::File::Info(info) : NULL); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(callback, base::Passed(&file_info))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(callback, base::Passed(&file_info))); } // Gets a WebContents instance handle for a platform app hosted in @@ -332,8 +332,9 @@ ExtensionFunction::ResponseAction FileSystemGetWritableEntryFunction::Run() { return RespondNow(Error(error)); } - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&FileSystemGetWritableEntryFunction::SetIsDirectoryAsync, this), base::BindOnce( @@ -392,7 +393,7 @@ void FileSystemChooseEntryFunction::ShowPicker( else if (g_paths_to_be_picked_for_test) test_paths = *g_paths_to_be_picked_for_test; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, test_paths.size() > 0 ? base::BindOnce(&FileSystemChooseEntryFunction::FilesSelected, @@ -517,8 +518,9 @@ void FileSystemChooseEntryFunction::FilesSelected( browser_context(), paths[0]); #endif - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce( &FileSystemChooseEntryFunction::ConfirmDirectoryAccessAsync, this, non_native_path, paths, web_contents)); @@ -539,7 +541,7 @@ void FileSystemChooseEntryFunction::ConfirmDirectoryAccessAsync( const base::FilePath check_path = non_native_path ? paths[0] : base::MakeAbsoluteFilePath(paths[0]); if (check_path.empty()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&FileSystemChooseEntryFunction::FileSelectionCanceled, this)); @@ -556,14 +558,14 @@ void FileSystemChooseEntryFunction::ConfirmDirectoryAccessAsync( if (g_skip_directory_confirmation_for_test) { if (g_allow_directory_access_for_test) break; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&FileSystemChooseEntryFunction::FileSelectionCanceled, this)); return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &FileSystemChooseEntryFunction::ConfirmSensitiveDirectoryAccess, @@ -571,7 +573,7 @@ void FileSystemChooseEntryFunction::ConfirmDirectoryAccessAsync( return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&FileSystemChooseEntryFunction::OnDirectoryAccessConfirmed, this, paths)); @@ -765,8 +767,9 @@ ExtensionFunction::ResponseAction FileSystemChooseEntryFunction::Run() { return RespondLater(); } #endif - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&base::DirectoryExists, previous_path), set_initial_path_callback); @@ -822,7 +825,7 @@ ExtensionFunction::ResponseAction FileSystemRetainEntryFunction::Run() { // It is safe to use base::Unretained() for operation_runner(), since it // is owned by |context| which will delete it on the IO thread. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( base::IgnoreResult( diff --git a/chromium/extensions/browser/api/file_system/file_system_api.h b/chromium/extensions/browser/api/file_system/file_system_api.h index db62bab9440..7df036af4c6 100644 --- a/chromium/extensions/browser/api/file_system/file_system_api.h +++ b/chromium/extensions/browser/api/file_system/file_system_api.h @@ -41,7 +41,7 @@ void SetLastChooseEntryDirectory(ExtensionPrefs* prefs, } // namespace file_system_api -class FileSystemGetDisplayPathFunction : public UIThreadExtensionFunction { +class FileSystemGetDisplayPathFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.getDisplayPath", FILESYSTEM_GETDISPLAYPATH) @@ -51,7 +51,7 @@ class FileSystemGetDisplayPathFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class FileSystemEntryFunction : public UIThreadExtensionFunction { +class FileSystemEntryFunction : public ExtensionFunction { protected: FileSystemEntryFunction(); @@ -104,7 +104,7 @@ class FileSystemGetWritableEntryFunction : public FileSystemEntryFunction { base::FilePath path_; }; -class FileSystemIsWritableEntryFunction : public UIThreadExtensionFunction { +class FileSystemIsWritableEntryFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.isWritableEntry", FILESYSTEM_ISWRITABLEENTRY) @@ -180,7 +180,7 @@ class FileSystemChooseEntryFunction : public FileSystemEntryFunction { base::FilePath initial_path_; }; -class FileSystemRetainEntryFunction : public UIThreadExtensionFunction { +class FileSystemRetainEntryFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.retainEntry", FILESYSTEM_RETAINENTRY) @@ -198,7 +198,7 @@ class FileSystemRetainEntryFunction : public UIThreadExtensionFunction { std::unique_ptr<base::File::Info> file_info); }; -class FileSystemIsRestorableFunction : public UIThreadExtensionFunction { +class FileSystemIsRestorableFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.isRestorable", FILESYSTEM_ISRESTORABLE) @@ -218,7 +218,7 @@ class FileSystemRestoreEntryFunction : public FileSystemEntryFunction { #if !defined(OS_CHROMEOS) // Stub for non Chrome OS operating systems. -class FileSystemRequestFileSystemFunction : public UIThreadExtensionFunction { +class FileSystemRequestFileSystemFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.requestFileSystem", FILESYSTEM_REQUESTFILESYSTEM) @@ -226,12 +226,12 @@ class FileSystemRequestFileSystemFunction : public UIThreadExtensionFunction { protected: ~FileSystemRequestFileSystemFunction() override {} - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ExtensionFunction::ResponseAction Run() override; }; // Stub for non Chrome OS operating systems. -class FileSystemGetVolumeListFunction : public UIThreadExtensionFunction { +class FileSystemGetVolumeListFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.getVolumeList", FILESYSTEM_GETVOLUMELIST) @@ -239,13 +239,13 @@ class FileSystemGetVolumeListFunction : public UIThreadExtensionFunction { protected: ~FileSystemGetVolumeListFunction() override {} - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ExtensionFunction::ResponseAction Run() override; }; #else // Requests a file system for the specified volume id. -class FileSystemRequestFileSystemFunction : public UIThreadExtensionFunction { +class FileSystemRequestFileSystemFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.requestFileSystem", FILESYSTEM_REQUESTFILESYSTEM) @@ -254,7 +254,7 @@ class FileSystemRequestFileSystemFunction : public UIThreadExtensionFunction { protected: ~FileSystemRequestFileSystemFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ExtensionFunction::ResponseAction Run() override; private: @@ -265,7 +265,7 @@ class FileSystemRequestFileSystemFunction : public UIThreadExtensionFunction { }; // Requests a list of available volumes. -class FileSystemGetVolumeListFunction : public UIThreadExtensionFunction { +class FileSystemGetVolumeListFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fileSystem.getVolumeList", FILESYSTEM_GETVOLUMELIST) @@ -274,7 +274,7 @@ class FileSystemGetVolumeListFunction : public UIThreadExtensionFunction { protected: ~FileSystemGetVolumeListFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ExtensionFunction::ResponseAction Run() override; private: diff --git a/chromium/extensions/browser/api/file_system/file_system_delegate.h b/chromium/extensions/browser/api/file_system/file_system_delegate.h index f8f63c9b797..4835a7eebd0 100644 --- a/chromium/extensions/browser/api/file_system/file_system_delegate.h +++ b/chromium/extensions/browser/api/file_system/file_system_delegate.h @@ -16,7 +16,7 @@ #include "extensions/common/api/file_system.h" #include "ui/shell_dialogs/select_file_dialog.h" -class UIThreadExtensionFunction; +class ExtensionFunction; namespace base { class FilePath; @@ -53,7 +53,7 @@ class FileSystemDelegate { // Shows a dialog to prompt the user to select files/directories. Returns // false if the dialog cannot be shown, i.e. there is no valid WebContents. virtual bool ShowSelectFileDialog( - scoped_refptr<UIThreadExtensionFunction> extension_function, + scoped_refptr<ExtensionFunction> extension_function, ui::SelectFileDialog::Type type, const base::FilePath& default_path, const ui::SelectFileDialog::FileTypeInfo* file_types, @@ -82,14 +82,13 @@ class FileSystemDelegate { // Grants or denies an extension's request for access to the named file // system. May prompt the user for consent. - virtual void RequestFileSystem( - content::BrowserContext* browser_context, - scoped_refptr<UIThreadExtensionFunction> requester, - const Extension& extension, - std::string volume_id, - bool writable, - const FileSystemCallback& success_callback, - const ErrorCallback& error_callback) = 0; + virtual void RequestFileSystem(content::BrowserContext* browser_context, + scoped_refptr<ExtensionFunction> requester, + const Extension& extension, + std::string volume_id, + bool writable, + const FileSystemCallback& success_callback, + const ErrorCallback& error_callback) = 0; // Immediately calls VolumeListCallback or ErrorCallback. virtual void GetVolumeList(content::BrowserContext* browser_context, diff --git a/chromium/extensions/browser/api/guest_view/app_view/app_view_guest_internal_api.h b/chromium/extensions/browser/api/guest_view/app_view/app_view_guest_internal_api.h index 04a5117f253..26d07b51137 100644 --- a/chromium/extensions/browser/api/guest_view/app_view/app_view_guest_internal_api.h +++ b/chromium/extensions/browser/api/guest_view/app_view/app_view_guest_internal_api.h @@ -10,8 +10,7 @@ namespace extensions { -class AppViewGuestInternalAttachFrameFunction - : public UIThreadExtensionFunction { +class AppViewGuestInternalAttachFrameFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("appViewGuestInternal.attachFrame", APPVIEWINTERNAL_ATTACHFRAME) @@ -25,8 +24,7 @@ class AppViewGuestInternalAttachFrameFunction DISALLOW_COPY_AND_ASSIGN(AppViewGuestInternalAttachFrameFunction); }; -class AppViewGuestInternalDenyRequestFunction - : public UIThreadExtensionFunction { +class AppViewGuestInternalDenyRequestFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("appViewGuestInternal.denyRequest", APPVIEWINTERNAL_DENYREQUEST) diff --git a/chromium/extensions/browser/api/guest_view/extension_view/extension_view_internal_api.cc b/chromium/extensions/browser/api/guest_view/extension_view/extension_view_internal_api.cc deleted file mode 100644 index 5110afa4516..00000000000 --- a/chromium/extensions/browser/api/guest_view/extension_view/extension_view_internal_api.cc +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "extensions/browser/api/guest_view/extension_view/extension_view_internal_api.h" - -#include <utility> - -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "components/crx_file/id_util.h" -#include "content/public/browser/storage_partition.h" -#include "content/public/browser/web_contents.h" -#include "content/public/common/stop_find_action.h" -#include "extensions/browser/guest_view/extension_view/whitelist/extension_view_whitelist.h" -#include "extensions/common/api/extension_view_internal.h" -#include "extensions/common/constants.h" - -namespace extensionview = extensions::api::extension_view_internal; - -namespace extensions { - -bool ExtensionViewInternalExtensionFunction::PreRunValidation( - std::string* error) { - int instance_id = 0; - EXTENSION_FUNCTION_PRERUN_VALIDATE(args_->GetInteger(0, &instance_id)); - guest_ = ExtensionViewGuest::From(source_process_id(), instance_id); - return guest_ != nullptr; -} - -// Checks the validity of |src|, including that it follows the chrome extension -// scheme and that its extension ID is valid. -// Returns true if |src| is valid. -bool IsSrcValid(const GURL& src) { - // Check if src is valid and matches the extension scheme. - if (!src.is_valid() || !src.SchemeIs(kExtensionScheme)) - return false; - - // Get the extension id and check if it is valid. - std::string extension_id = src.host(); - if (!crx_file::id_util::IdIsValid(extension_id) || - !IsExtensionIdWhitelisted(extension_id)) - return false; - - return true; -} - -ExtensionFunction::ResponseAction ExtensionViewInternalLoadSrcFunction::Run() { - std::unique_ptr<extensionview::LoadSrc::Params> params( - extensionview::LoadSrc::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - std::string src = params->src; - GURL url(src); - bool has_load_succeeded = false; - bool is_src_valid = IsSrcValid(url); - - if (is_src_valid) { - has_load_succeeded = - guest_->NavigateGuest(src, true /* force_navigation */); - } - - // Return whether load is successful. - return RespondNow( - OneArgument(std::make_unique<base::Value>(has_load_succeeded))); -} - -ExtensionFunction::ResponseAction ExtensionViewInternalParseSrcFunction::Run() { - std::unique_ptr<extensionview::ParseSrc::Params> params( - extensionview::ParseSrc::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - GURL url(params->src); - bool is_src_valid = IsSrcValid(url); - - // Return whether the src is valid and the current extension ID to - // the callback. - auto result_list = std::make_unique<base::ListValue>(); - result_list->AppendBoolean(is_src_valid); - result_list->AppendString(url.host()); - return RespondNow(ArgumentList(std::move(result_list))); -} - -} // namespace extensions diff --git a/chromium/extensions/browser/api/guest_view/extension_view/extension_view_internal_api.h b/chromium/extensions/browser/api/guest_view/extension_view/extension_view_internal_api.h deleted file mode 100644 index 86b3b93289f..00000000000 --- a/chromium/extensions/browser/api/guest_view/extension_view/extension_view_internal_api.h +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef EXTENSIONS_BROWSER_API_GUEST_VIEW_EXTENSION_VIEW_EXTENSION_VIEW_INTERNAL_API_H_ -#define EXTENSIONS_BROWSER_API_GUEST_VIEW_EXTENSION_VIEW_EXTENSION_VIEW_INTERNAL_API_H_ - -#include "base/macros.h" -#include "extensions/browser/api/execute_code_function.h" -#include "extensions/browser/extension_function.h" -#include "extensions/browser/guest_view/extension_view/extension_view_guest.h" - -namespace extensions { - -// An abstract base class for async extensionview APIs. It does a process ID -// check in PreRunValidation. -class ExtensionViewInternalExtensionFunction - : public UIThreadExtensionFunction { - public: - ExtensionViewInternalExtensionFunction() {} - - protected: - ~ExtensionViewInternalExtensionFunction() override {} - - // ExtensionFunction implementation. - bool PreRunValidation(std::string* error) final; - - ExtensionViewGuest* guest_ = nullptr; -}; - -// Attempts to load a src into the extensionview. -class ExtensionViewInternalLoadSrcFunction - : public ExtensionViewInternalExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("extensionViewInternal.loadSrc", - EXTENSIONVIEWINTERNAL_LOADSRC) - ExtensionViewInternalLoadSrcFunction() {} - - protected: - ~ExtensionViewInternalLoadSrcFunction() override {} - - private: - // UIThreadExtensionFunction implementation. - ResponseAction Run() final; - - DISALLOW_COPY_AND_ASSIGN(ExtensionViewInternalLoadSrcFunction); -}; - -// Parses a src and determines whether or not it is valid. -class ExtensionViewInternalParseSrcFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("extensionViewInternal.parseSrc", - EXTENSIONVIEWINTERNAL_PARSESRC) - ExtensionViewInternalParseSrcFunction() {} - - protected: - ~ExtensionViewInternalParseSrcFunction() override {} - - private: - // UIThreadExtensionFunction implementation. - ResponseAction Run() final; - - DISALLOW_COPY_AND_ASSIGN(ExtensionViewInternalParseSrcFunction); -}; - -} // namespace extensions - -#endif // EXTENSIONS_BROWSER_API_GUEST_VIEW_EXTENSION_VIEW_EXTENSION_VIEW_INTERNAL_API_H_ diff --git a/chromium/extensions/browser/api/guest_view/guest_view_internal_api.h b/chromium/extensions/browser/api/guest_view/guest_view_internal_api.h index 6d5b0e51832..0f395629018 100644 --- a/chromium/extensions/browser/api/guest_view/guest_view_internal_api.h +++ b/chromium/extensions/browser/api/guest_view/guest_view_internal_api.h @@ -10,7 +10,7 @@ namespace extensions { -class GuestViewInternalCreateGuestFunction : public UIThreadExtensionFunction { +class GuestViewInternalCreateGuestFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("guestViewInternal.createGuest", GUESTVIEWINTERNAL_CREATEGUEST) @@ -19,7 +19,7 @@ class GuestViewInternalCreateGuestFunction : public UIThreadExtensionFunction { protected: ~GuestViewInternalCreateGuestFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() final; private: @@ -27,7 +27,7 @@ class GuestViewInternalCreateGuestFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(GuestViewInternalCreateGuestFunction); }; -class GuestViewInternalDestroyGuestFunction : public UIThreadExtensionFunction { +class GuestViewInternalDestroyGuestFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("guestViewInternal.destroyGuest", GUESTVIEWINTERNAL_DESTROYGUEST) @@ -36,7 +36,7 @@ class GuestViewInternalDestroyGuestFunction : public UIThreadExtensionFunction { protected: ~GuestViewInternalDestroyGuestFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() final; private: @@ -44,7 +44,7 @@ class GuestViewInternalDestroyGuestFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(GuestViewInternalDestroyGuestFunction); }; -class GuestViewInternalSetSizeFunction : public UIThreadExtensionFunction { +class GuestViewInternalSetSizeFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("guestViewInternal.setSize", GUESTVIEWINTERNAL_SETAUTOSIZE) @@ -54,7 +54,7 @@ class GuestViewInternalSetSizeFunction : public UIThreadExtensionFunction { protected: ~GuestViewInternalSetSizeFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() final; private: diff --git a/chromium/extensions/browser/api/guest_view/web_view/web_view_internal_api.cc b/chromium/extensions/browser/api/guest_view/web_view/web_view_internal_api.cc index dac7336e0dc..985ba0c137e 100644 --- a/chromium/extensions/browser/api/guest_view/web_view/web_view_internal_api.cc +++ b/chromium/extensions/browser/api/guest_view/web_view/web_view_internal_api.cc @@ -266,7 +266,7 @@ std::unique_ptr<extensions::UserScriptList> ParseContentScripts( namespace extensions { bool WebViewInternalExtensionFunction::PreRunValidation(std::string* error) { - if (!UIThreadExtensionFunction::PreRunValidation(error)) + if (!ExtensionFunction::PreRunValidation(error)) return false; int instance_id = 0; diff --git a/chromium/extensions/browser/api/guest_view/web_view/web_view_internal_api.h b/chromium/extensions/browser/api/guest_view/web_view/web_view_internal_api.h index f5cba26ebca..41125883f93 100644 --- a/chromium/extensions/browser/api/guest_view/web_view/web_view_internal_api.h +++ b/chromium/extensions/browser/api/guest_view/web_view/web_view_internal_api.h @@ -20,7 +20,7 @@ // abuse by normal renderer processes. namespace extensions { -class WebViewInternalExtensionFunction : public UIThreadExtensionFunction { +class WebViewInternalExtensionFunction : public ExtensionFunction { public: WebViewInternalExtensionFunction() {} @@ -42,7 +42,7 @@ class WebViewInternalCaptureVisibleRegionFunction protected: ~WebViewInternalCaptureVisibleRegionFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -69,7 +69,7 @@ class WebViewInternalNavigateFunction protected: ~WebViewInternalNavigateFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalNavigateFunction); @@ -143,8 +143,7 @@ class WebViewInternalInsertCSSFunction DISALLOW_COPY_AND_ASSIGN(WebViewInternalInsertCSSFunction); }; -class WebViewInternalAddContentScriptsFunction - : public UIThreadExtensionFunction { +class WebViewInternalAddContentScriptsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webViewInternal.addContentScripts", WEBVIEWINTERNAL_ADDCONTENTSCRIPTS) @@ -160,8 +159,7 @@ class WebViewInternalAddContentScriptsFunction DISALLOW_COPY_AND_ASSIGN(WebViewInternalAddContentScriptsFunction); }; -class WebViewInternalRemoveContentScriptsFunction - : public UIThreadExtensionFunction { +class WebViewInternalRemoveContentScriptsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webViewInternal.removeContentScripts", WEBVIEWINTERNAL_REMOVECONTENTSCRIPTS) @@ -171,7 +169,7 @@ class WebViewInternalRemoveContentScriptsFunction protected: ~WebViewInternalRemoveContentScriptsFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -187,7 +185,7 @@ class WebViewInternalSetNameFunction : public WebViewInternalExtensionFunction { protected: ~WebViewInternalSetNameFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalSetNameFunction); @@ -204,7 +202,7 @@ class WebViewInternalSetAllowTransparencyFunction protected: ~WebViewInternalSetAllowTransparencyFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalSetAllowTransparencyFunction); @@ -221,7 +219,7 @@ class WebViewInternalSetAllowScalingFunction protected: ~WebViewInternalSetAllowScalingFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalSetAllowScalingFunction); @@ -236,7 +234,7 @@ class WebViewInternalSetZoomFunction : public WebViewInternalExtensionFunction { protected: ~WebViewInternalSetZoomFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalSetZoomFunction); @@ -251,7 +249,7 @@ class WebViewInternalGetZoomFunction : public WebViewInternalExtensionFunction { protected: ~WebViewInternalGetZoomFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalGetZoomFunction); @@ -268,7 +266,7 @@ class WebViewInternalSetZoomModeFunction protected: ~WebViewInternalSetZoomModeFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalSetZoomModeFunction); @@ -285,7 +283,7 @@ class WebViewInternalGetZoomModeFunction protected: ~WebViewInternalGetZoomModeFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalGetZoomModeFunction); @@ -304,7 +302,7 @@ class WebViewInternalFindFunction : public WebViewInternalExtensionFunction { ~WebViewInternalFindFunction() override; private: - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalFindFunction); @@ -321,7 +319,7 @@ class WebViewInternalStopFindingFunction protected: ~WebViewInternalStopFindingFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalStopFindingFunction); @@ -338,7 +336,7 @@ class WebViewInternalLoadDataWithBaseUrlFunction protected: ~WebViewInternalLoadDataWithBaseUrlFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalLoadDataWithBaseUrlFunction); @@ -353,7 +351,7 @@ class WebViewInternalGoFunction : public WebViewInternalExtensionFunction { protected: ~WebViewInternalGoFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalGoFunction); @@ -368,7 +366,7 @@ class WebViewInternalReloadFunction : public WebViewInternalExtensionFunction { protected: ~WebViewInternalReloadFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalReloadFunction); @@ -385,7 +383,7 @@ class WebViewInternalSetPermissionFunction protected: ~WebViewInternalSetPermissionFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalSetPermissionFunction); @@ -402,7 +400,7 @@ class WebViewInternalOverrideUserAgentFunction protected: ~WebViewInternalOverrideUserAgentFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalOverrideUserAgentFunction); @@ -417,7 +415,7 @@ class WebViewInternalStopFunction : public WebViewInternalExtensionFunction { protected: ~WebViewInternalStopFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalStopFunction); @@ -434,7 +432,7 @@ class WebViewInternalSetAudioMutedFunction protected: ~WebViewInternalSetAudioMutedFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalSetAudioMutedFunction); @@ -451,7 +449,7 @@ class WebViewInternalIsAudioMutedFunction protected: ~WebViewInternalIsAudioMutedFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalIsAudioMutedFunction); @@ -468,7 +466,7 @@ class WebViewInternalGetAudioStateFunction protected: ~WebViewInternalGetAudioStateFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalGetAudioStateFunction); @@ -485,7 +483,7 @@ class WebViewInternalTerminateFunction protected: ~WebViewInternalTerminateFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalTerminateFunction); @@ -502,7 +500,7 @@ class WebViewInternalClearDataFunction protected: ~WebViewInternalClearDataFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -530,7 +528,7 @@ class WebViewInternalSetSpatialNavigationEnabledFunction protected: ~WebViewInternalSetSpatialNavigationEnabledFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalSetSpatialNavigationEnabledFunction); @@ -547,7 +545,7 @@ class WebViewInternalIsSpatialNavigationEnabledFunction protected: ~WebViewInternalIsSpatialNavigationEnabledFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(WebViewInternalIsSpatialNavigationEnabledFunction); diff --git a/chromium/extensions/browser/api/hid/hid_api.h b/chromium/extensions/browser/api/hid/hid_api.h index 360564338f7..bd90473e4b2 100644 --- a/chromium/extensions/browser/api/hid/hid_api.h +++ b/chromium/extensions/browser/api/hid/hid_api.h @@ -23,7 +23,7 @@ namespace extensions { class DevicePermissionsPrompt; -class HidGetDevicesFunction : public UIThreadExtensionFunction { +class HidGetDevicesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hid.getDevices", HID_GETDEVICES) @@ -40,7 +40,7 @@ class HidGetDevicesFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(HidGetDevicesFunction); }; -class HidGetUserSelectedDevicesFunction : public UIThreadExtensionFunction { +class HidGetUserSelectedDevicesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hid.getUserSelectedDevices", HID_GETUSERSELECTEDDEVICES) @@ -60,7 +60,7 @@ class HidGetUserSelectedDevicesFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(HidGetUserSelectedDevicesFunction); }; -class HidConnectFunction : public UIThreadExtensionFunction { +class HidConnectFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hid.connect", HID_CONNECT) @@ -79,7 +79,7 @@ class HidConnectFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(HidConnectFunction); }; -class HidDisconnectFunction : public UIThreadExtensionFunction { +class HidDisconnectFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("hid.disconnect", HID_DISCONNECT) @@ -96,7 +96,7 @@ class HidDisconnectFunction : public UIThreadExtensionFunction { // Base class for extension functions that start some asynchronous work after // looking up a HidConnection. -class HidConnectionIoFunction : public UIThreadExtensionFunction { +class HidConnectionIoFunction : public ExtensionFunction { public: HidConnectionIoFunction(); diff --git a/chromium/extensions/browser/api/hid/hid_device_manager.cc b/chromium/extensions/browser/api/hid/hid_device_manager.cc index e5979e657cf..55e3f1f5847 100644 --- a/chromium/extensions/browser/api/hid/hid_device_manager.cc +++ b/chromium/extensions/browser/api/hid/hid_device_manager.cc @@ -24,9 +24,11 @@ #include "extensions/common/permissions/usb_device_permission.h" #include "mojo/public/cpp/bindings/callback_helpers.h" #include "mojo/public/cpp/bindings/interface_request.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "services/device/public/cpp/hid/hid_device_filter.h" #include "services/device/public/cpp/hid/hid_usage_and_page.h" #include "services/device/public/mojom/constants.mojom.h" +#include "services/device/public/mojom/hid.mojom.h" #include "services/service_manager/public/cpp/connector.h" namespace hid = extensions::api::hid; @@ -73,7 +75,8 @@ void PopulateHidDeviceInfo(hid::HidDeviceInfo* output, bool WillDispatchDeviceEvent(base::WeakPtr<HidDeviceManager> device_manager, const device::mojom::HidDeviceInfo& device_info, - content::BrowserContext* context, + content::BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { @@ -170,9 +173,10 @@ void HidDeviceManager::Connect(const std::string& device_guid, ConnectCallback callback) { DCHECK(initialized_); - hid_manager_->Connect(device_guid, /*connection_client=*/nullptr, - mojo::WrapCallbackWithDefaultInvokeIfNotRun( - std::move(callback), nullptr)); + hid_manager_->Connect( + device_guid, mojo::PendingRemote<device::mojom::HidConnectionClient>(), + mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(callback), + nullptr)); } bool HidDeviceManager::HasPermission( diff --git a/chromium/extensions/browser/api/idle/idle_api.h b/chromium/extensions/browser/api/idle/idle_api.h index 954cf4a1781..3562ddb3711 100644 --- a/chromium/extensions/browser/api/idle/idle_api.h +++ b/chromium/extensions/browser/api/idle/idle_api.h @@ -11,14 +11,14 @@ namespace extensions { // Implementation of the chrome.idle.queryState API. -class IdleQueryStateFunction : public UIThreadExtensionFunction { +class IdleQueryStateFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idle.queryState", IDLE_QUERYSTATE) protected: ~IdleQueryStateFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -26,7 +26,7 @@ class IdleQueryStateFunction : public UIThreadExtensionFunction { }; // Implementation of the chrome.idle.setDetectionInterval API. -class IdleSetDetectionIntervalFunction : public UIThreadExtensionFunction { +class IdleSetDetectionIntervalFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idle.setDetectionInterval", IDLE_SETDETECTIONINTERVAL) @@ -34,18 +34,18 @@ class IdleSetDetectionIntervalFunction : public UIThreadExtensionFunction { protected: ~IdleSetDetectionIntervalFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; -class IdleGetAutoLockDelayFunction : public UIThreadExtensionFunction { +class IdleGetAutoLockDelayFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idle.getAutoLockDelay", IDLE_GETAUTOLOCKDELAY) protected: ~IdleGetAutoLockDelayFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; diff --git a/chromium/extensions/browser/api/idle/idle_manager.cc b/chromium/extensions/browser/api/idle/idle_manager.cc index 8b82b48af80..df63f46f9da 100644 --- a/chromium/extensions/browser/api/idle/idle_manager.cc +++ b/chromium/extensions/browser/api/idle/idle_manager.cc @@ -10,7 +10,6 @@ #include "content/public/browser/browser_context.h" #include "extensions/browser/api/idle/idle_api_constants.h" #include "extensions/browser/event_router.h" -#include "extensions/browser/extension_registry.h" #include "extensions/common/api/idle.h" #include "extensions/common/extension.h" @@ -124,8 +123,7 @@ IdleManager::IdleManager(content::BrowserContext* context) : context_(context), last_state_(ui::IDLE_STATE_ACTIVE), idle_time_provider_(new DefaultIdleProvider()), - event_delegate_(new DefaultEventDelegate(context)), - extension_registry_observer_(this) {} + event_delegate_(new DefaultEventDelegate(context)) {} IdleManager::~IdleManager() { } diff --git a/chromium/extensions/browser/api/idle/idle_manager.h b/chromium/extensions/browser/api/idle/idle_manager.h index 766180c9a4b..9ab7de7ad71 100644 --- a/chromium/extensions/browser/api/idle/idle_manager.h +++ b/chromium/extensions/browser/api/idle/idle_manager.h @@ -16,6 +16,7 @@ #include "base/timer/timer.h" #include "components/keyed_service/core/keyed_service.h" #include "extensions/browser/event_router.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "ui/base/idle/idle.h" @@ -28,7 +29,6 @@ class BrowserContext; } // namespace content namespace extensions { -class ExtensionRegistry; struct IdleMonitor { explicit IdleMonitor(ui::IdleState initial_state); @@ -138,7 +138,7 @@ class IdleManager : public ExtensionRegistryObserver, // Listen to extension unloaded notification. ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; DISALLOW_COPY_AND_ASSIGN(IdleManager); }; diff --git a/chromium/extensions/browser/api/lock_screen_data/data_item.cc b/chromium/extensions/browser/api/lock_screen_data/data_item.cc index b74b012d009..0857514cc61 100644 --- a/chromium/extensions/browser/api/lock_screen_data/data_item.cc +++ b/chromium/extensions/browser/api/lock_screen_data/data_item.cc @@ -326,8 +326,7 @@ DataItem::DataItem(const std::string& id, context_(context), value_store_cache_(value_store_cache), task_runner_(task_runner), - crypto_key_(crypto_key), - weak_ptr_factory_(this) {} + crypto_key_(crypto_key) {} DataItem::~DataItem() = default; diff --git a/chromium/extensions/browser/api/lock_screen_data/data_item.h b/chromium/extensions/browser/api/lock_screen_data/data_item.h index eec82c91709..636f1613982 100644 --- a/chromium/extensions/browser/api/lock_screen_data/data_item.h +++ b/chromium/extensions/browser/api/lock_screen_data/data_item.h @@ -133,7 +133,7 @@ class DataItem { // when reading it from the storage. const std::string crypto_key_; - base::WeakPtrFactory<DataItem> weak_ptr_factory_; + base::WeakPtrFactory<DataItem> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DataItem); }; diff --git a/chromium/extensions/browser/api/lock_screen_data/data_item_unittest.cc b/chromium/extensions/browser/api/lock_screen_data/data_item_unittest.cc index 47cb9d50323..68844dba826 100644 --- a/chromium/extensions/browser/api/lock_screen_data/data_item_unittest.cc +++ b/chromium/extensions/browser/api/lock_screen_data/data_item_unittest.cc @@ -16,8 +16,8 @@ #include "base/sequenced_task_runner.h" #include "base/values.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "crypto/symmetric_key.h" #include "extensions/browser/api/lock_screen_data/operation_result.h" #include "extensions/browser/api/storage/backend_task_runner.h" @@ -291,7 +291,7 @@ class DataItemTest : public testing::Test { std::unique_ptr<content::TestBrowserContext> context_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; scoped_refptr<base::SequencedTaskRunner> task_runner_; std::unique_ptr<TestExtensionsBrowserClient> extensions_browser_client_; diff --git a/chromium/extensions/browser/api/lock_screen_data/lock_screen_data_api.h b/chromium/extensions/browser/api/lock_screen_data/lock_screen_data_api.h index 94d0a360108..521905c0200 100644 --- a/chromium/extensions/browser/api/lock_screen_data/lock_screen_data_api.h +++ b/chromium/extensions/browser/api/lock_screen_data/lock_screen_data_api.h @@ -18,7 +18,7 @@ enum class OperationResult; class DataItem; } // namespace lock_screen_data -class LockScreenDataCreateFunction : public UIThreadExtensionFunction { +class LockScreenDataCreateFunction : public ExtensionFunction { public: LockScreenDataCreateFunction(); @@ -34,7 +34,7 @@ class LockScreenDataCreateFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(LockScreenDataCreateFunction); }; -class LockScreenDataGetAllFunction : public UIThreadExtensionFunction { +class LockScreenDataGetAllFunction : public ExtensionFunction { public: LockScreenDataGetAllFunction(); @@ -49,7 +49,7 @@ class LockScreenDataGetAllFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(LockScreenDataGetAllFunction); }; -class LockScreenDataGetContentFunction : public UIThreadExtensionFunction { +class LockScreenDataGetContentFunction : public ExtensionFunction { public: LockScreenDataGetContentFunction(); @@ -66,7 +66,7 @@ class LockScreenDataGetContentFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(LockScreenDataGetContentFunction); }; -class LockScreenDataSetContentFunction : public UIThreadExtensionFunction { +class LockScreenDataSetContentFunction : public ExtensionFunction { public: LockScreenDataSetContentFunction(); @@ -82,7 +82,7 @@ class LockScreenDataSetContentFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(LockScreenDataSetContentFunction); }; -class LockScreenDataDeleteFunction : public UIThreadExtensionFunction { +class LockScreenDataDeleteFunction : public ExtensionFunction { public: LockScreenDataDeleteFunction(); diff --git a/chromium/extensions/browser/api/lock_screen_data/lock_screen_item_storage.cc b/chromium/extensions/browser/api/lock_screen_data/lock_screen_item_storage.cc index 7d061f8f4be..0df643e1851 100644 --- a/chromium/extensions/browser/api/lock_screen_data/lock_screen_item_storage.cc +++ b/chromium/extensions/browser/api/lock_screen_data/lock_screen_item_storage.cc @@ -22,7 +22,6 @@ #include "extensions/browser/api/storage/backend_task_runner.h" #include "extensions/browser/api/storage/local_value_store_cache.h" #include "extensions/browser/event_router.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/value_store/value_store.h" #include "extensions/browser/value_store/value_store_factory_impl.h" @@ -141,9 +140,7 @@ LockScreenItemStorage::LockScreenItemStorage( crypto_key_(crypto_key), local_state_(local_state), tick_clock_(base::DefaultTickClock::GetInstance()), - extension_registry_observer_(this), - value_store_cache_(CreateValueStoreCache(storage_root.Append(user_id_))), - weak_ptr_factory_(this) { + value_store_cache_(CreateValueStoreCache(storage_root.Append(user_id_))) { CHECK(!user_id_.empty()); extension_registry_observer_.Add(ExtensionRegistry::Get(context)); task_runner_ = GetBackendTaskRunner(); diff --git a/chromium/extensions/browser/api/lock_screen_data/lock_screen_item_storage.h b/chromium/extensions/browser/api/lock_screen_data/lock_screen_item_storage.h index e1c5361d26d..a5a4721b1a5 100644 --- a/chromium/extensions/browser/api/lock_screen_data/lock_screen_item_storage.h +++ b/chromium/extensions/browser/api/lock_screen_data/lock_screen_item_storage.h @@ -18,6 +18,7 @@ #include "base/scoped_observer.h" #include "base/sequenced_task_runner.h" #include "extensions/browser/api/lock_screen_data/data_item.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/common/extension_id.h" @@ -35,7 +36,6 @@ class BrowserContext; namespace extensions { class Extension; -class ExtensionRegistry; class LocalValueStoreCache; namespace lock_screen_data { @@ -310,7 +310,7 @@ class LockScreenItemStorage : public ExtensionRegistryObserver { SessionLockedState session_locked_state_ = SessionLockedState::kUnknown; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; // The deprecated (shared) lock screen data value store cache. Items in this // value store should be migrated to |value_store_cache_|. @@ -329,7 +329,7 @@ class LockScreenItemStorage : public ExtensionRegistryObserver { scoped_refptr<base::SequencedTaskRunner> task_runner_; - base::WeakPtrFactory<LockScreenItemStorage> weak_ptr_factory_; + base::WeakPtrFactory<LockScreenItemStorage> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(LockScreenItemStorage); }; diff --git a/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl.cc b/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl.cc index cf969b18da1..c6b5cc3c2ed 100644 --- a/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl.cc +++ b/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl.cc @@ -28,8 +28,7 @@ LockScreenValueStoreMigratorImpl::LockScreenValueStoreMigratorImpl( source_store_cache_(source_store_cache), target_store_cache_(target_store_cache), task_runner_(task_runner), - crypto_key_(crypto_key), - weak_ptr_factory_(this) {} + crypto_key_(crypto_key) {} LockScreenValueStoreMigratorImpl::~LockScreenValueStoreMigratorImpl() = default; diff --git a/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl.h b/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl.h index 51e106fbe99..aa62754212e 100644 --- a/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl.h +++ b/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl.h @@ -139,7 +139,8 @@ class LockScreenValueStoreMigratorImpl : public LockScreenValueStoreMigrator { // Maps extension ids to the extension's migration status. std::unordered_map<ExtensionId, MigrationData> migration_items_; - base::WeakPtrFactory<LockScreenValueStoreMigratorImpl> weak_ptr_factory_; + base::WeakPtrFactory<LockScreenValueStoreMigratorImpl> weak_ptr_factory_{ + this}; DISALLOW_COPY_AND_ASSIGN(LockScreenValueStoreMigratorImpl); }; diff --git a/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl_unittest.cc b/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl_unittest.cc index 6962eb2ebc9..aca11961983 100644 --- a/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl_unittest.cc +++ b/chromium/extensions/browser/api/lock_screen_data/lock_screen_value_store_migrator_impl_unittest.cc @@ -17,8 +17,8 @@ #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "crypto/symmetric_key.h" #include "extensions/browser/api/lock_screen_data/data_item.h" #include "extensions/browser/api/lock_screen_data/operation_result.h" @@ -360,7 +360,7 @@ class LockScreenValueStoreMigratorImplTest : public testing::Test { extension_waiters_[extension_id].Quit(); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; scoped_refptr<base::SequencedTaskRunner> task_runner_; std::unique_ptr<content::TestBrowserContext> context_; diff --git a/chromium/extensions/browser/api/management/management_api.cc b/chromium/extensions/browser/api/management/management_api.cc index c7a9648d978..4a47609a028 100644 --- a/chromium/extensions/browser/api/management/management_api.cc +++ b/chromium/extensions/browser/api/management/management_api.cc @@ -821,6 +821,106 @@ ExtensionFunction::ResponseAction ManagementGenerateAppForLinkFunction::Run() { return RespondLater(); } +ManagementCanInstallReplacementAndroidAppFunction:: + ManagementCanInstallReplacementAndroidAppFunction() {} + +ManagementCanInstallReplacementAndroidAppFunction:: + ~ManagementCanInstallReplacementAndroidAppFunction() {} + +ExtensionFunction::ResponseAction +ManagementCanInstallReplacementAndroidAppFunction::Run() { + if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) + return RespondNow(Error(keys::kNotAllowedInKioskError)); + + if (!extension()->from_webstore()) { + return RespondNow( + Error(keys::kInstallReplacementAndroidAppNotFromWebstoreError)); + } + + auto* api_delegate = ManagementAPI::GetFactoryInstance() + ->Get(browser_context()) + ->GetDelegate(); + + DCHECK(api_delegate); + + if (!api_delegate->CanContextInstallAndroidApps(browser_context())) { + return RespondNow(ArgumentList( + management::CanInstallReplacementAndroidApp::Results::Create(false))); + } + + DCHECK(ReplacementAppsInfo::HasReplacementAndroidApp(extension())); + + const std::string& package_name = + ReplacementAppsInfo::GetReplacementAndroidApp(extension()); + + api_delegate->CheckAndroidAppInstallStatus( + package_name, + base::BindOnce(&ManagementCanInstallReplacementAndroidAppFunction:: + OnFinishedAndroidAppCheck, + this)); + + // Response is sent async in FinishCheckAndroidApp(). + return RespondLater(); +} + +void ManagementCanInstallReplacementAndroidAppFunction:: + OnFinishedAndroidAppCheck(bool installable) { + Respond( + ArgumentList(management::CanInstallReplacementAndroidApp::Results::Create( + installable))); +} + +ManagementInstallReplacementAndroidAppFunction:: + ManagementInstallReplacementAndroidAppFunction() {} + +ManagementInstallReplacementAndroidAppFunction:: + ~ManagementInstallReplacementAndroidAppFunction() {} + +ExtensionFunction::ResponseAction +ManagementInstallReplacementAndroidAppFunction::Run() { + if (ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode()) + return RespondNow(Error(keys::kNotAllowedInKioskError)); + + if (!extension()->from_webstore()) { + return RespondNow( + Error(keys::kInstallReplacementAndroidAppNotFromWebstoreError)); + } + + if (!user_gesture()) { + return RespondNow( + Error(keys::kGestureNeededForInstallReplacementAndroidAppError)); + } + + auto* api_delegate = ManagementAPI::GetFactoryInstance() + ->Get(browser_context()) + ->GetDelegate(); + + DCHECK(api_delegate); + if (!api_delegate->CanContextInstallAndroidApps(browser_context())) { + return RespondNow( + Error(keys::kInstallReplacementAndroidAppInvalidContextError)); + } + + DCHECK(ReplacementAppsInfo::HasReplacementAndroidApp(extension())); + + api_delegate->InstallReplacementAndroidApp( + ReplacementAppsInfo::GetReplacementAndroidApp(extension()), + base::BindOnce(&ManagementInstallReplacementAndroidAppFunction:: + OnAppInstallInitiated, + this)); + + // Response is sent async in OnAppInstallInitiated(). + return RespondLater(); +} + +void ManagementInstallReplacementAndroidAppFunction::OnAppInstallInitiated( + bool initiated) { + if (!initiated) + return Respond(Error(keys::kInstallReplacementAndroidAppCannotInstallApp)); + + return Respond(NoArguments()); +} + ManagementInstallReplacementWebAppFunction:: ManagementInstallReplacementWebAppFunction() {} @@ -873,14 +973,6 @@ ManagementInstallReplacementWebAppFunction::Run() { return RespondLater(); } -ManagementEventRouter::ManagementEventRouter(content::BrowserContext* context) - : browser_context_(context), extension_registry_observer_(this) { - extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_)); -} - -ManagementEventRouter::~ManagementEventRouter() { -} - void ManagementInstallReplacementWebAppFunction::FinishCreateWebApp( ManagementAPIDelegate::InstallWebAppResult result) { ResponseValue response; @@ -897,6 +989,13 @@ void ManagementInstallReplacementWebAppFunction::FinishCreateWebApp( Respond(std::move(response)); } +ManagementEventRouter::ManagementEventRouter(content::BrowserContext* context) + : browser_context_(context) { + extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_)); +} + +ManagementEventRouter::~ManagementEventRouter() {} + void ManagementEventRouter::OnExtensionLoaded( content::BrowserContext* browser_context, const Extension* extension) { diff --git a/chromium/extensions/browser/api/management/management_api.h b/chromium/extensions/browser/api/management/management_api.h index 9648478de3c..16e66b90389 100644 --- a/chromium/extensions/browser/api/management/management_api.h +++ b/chromium/extensions/browser/api/management/management_api.h @@ -26,7 +26,7 @@ namespace extensions { class ExtensionRegistry; class RequirementsChecker; -class ManagementGetAllFunction : public UIThreadExtensionFunction { +class ManagementGetAllFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("management.getAll", MANAGEMENT_GETALL) @@ -37,7 +37,7 @@ class ManagementGetAllFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ManagementGetFunction : public UIThreadExtensionFunction { +class ManagementGetFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("management.get", MANAGEMENT_GET) @@ -48,7 +48,7 @@ class ManagementGetFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ManagementGetSelfFunction : public UIThreadExtensionFunction { +class ManagementGetSelfFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("management.getSelf", MANAGEMENT_GETSELF) @@ -59,8 +59,7 @@ class ManagementGetSelfFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ManagementGetPermissionWarningsByIdFunction - : public UIThreadExtensionFunction { +class ManagementGetPermissionWarningsByIdFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("management.getPermissionWarningsById", MANAGEMENT_GETPERMISSIONWARNINGSBYID) @@ -73,7 +72,7 @@ class ManagementGetPermissionWarningsByIdFunction }; class ManagementGetPermissionWarningsByManifestFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("management.getPermissionWarningsByManifest", MANAGEMENT_GETPERMISSIONWARNINGSBYMANIFEST) @@ -89,7 +88,7 @@ class ManagementGetPermissionWarningsByManifestFunction ResponseAction Run() override; }; -class ManagementLaunchAppFunction : public UIThreadExtensionFunction { +class ManagementLaunchAppFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("management.launchApp", MANAGEMENT_LAUNCHAPP) @@ -100,7 +99,7 @@ class ManagementLaunchAppFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ManagementSetEnabledFunction : public UIThreadExtensionFunction { +class ManagementSetEnabledFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("management.setEnabled", MANAGEMENT_SETENABLED) @@ -124,7 +123,7 @@ class ManagementSetEnabledFunction : public UIThreadExtensionFunction { std::unique_ptr<RequirementsChecker> requirements_checker_; }; -class ManagementUninstallFunctionBase : public UIThreadExtensionFunction { +class ManagementUninstallFunctionBase : public ExtensionFunction { public: ManagementUninstallFunctionBase(); @@ -169,7 +168,7 @@ class ManagementUninstallSelfFunction : public ManagementUninstallFunctionBase { ResponseAction Run() override; }; -class ManagementCreateAppShortcutFunction : public UIThreadExtensionFunction { +class ManagementCreateAppShortcutFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("management.createAppShortcut", MANAGEMENT_CREATEAPPSHORTCUT) @@ -186,7 +185,7 @@ class ManagementCreateAppShortcutFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ManagementSetLaunchTypeFunction : public UIThreadExtensionFunction { +class ManagementSetLaunchTypeFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("management.setLaunchType", MANAGEMENT_SETLAUNCHTYPE) @@ -197,7 +196,7 @@ class ManagementSetLaunchTypeFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ManagementGenerateAppForLinkFunction : public UIThreadExtensionFunction { +class ManagementGenerateAppForLinkFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("management.generateAppForLink", MANAGEMENT_GENERATEAPPFORLINK) @@ -215,8 +214,41 @@ class ManagementGenerateAppForLinkFunction : public UIThreadExtensionFunction { std::unique_ptr<AppForLinkDelegate> app_for_link_delegate_; }; -class ManagementInstallReplacementWebAppFunction - : public UIThreadExtensionFunction { +class ManagementCanInstallReplacementAndroidAppFunction + : public ExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("management.canInstallReplacementAndroidApp", + MANAGEMENT_CANINSTALLREPLACEMENTANDROIDAPP) + + ManagementCanInstallReplacementAndroidAppFunction(); + + protected: + ~ManagementCanInstallReplacementAndroidAppFunction() override; + + ResponseAction Run() override; + + private: + void OnFinishedAndroidAppCheck(bool result); +}; + +class ManagementInstallReplacementAndroidAppFunction + : public ExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("management.installReplacementAndroidApp", + MANAGEMENT_INSTALLREPLACEMENTANDROIDAPP) + + ManagementInstallReplacementAndroidAppFunction(); + + protected: + ~ManagementInstallReplacementAndroidAppFunction() override; + + ResponseAction Run() override; + + private: + void OnAppInstallInitiated(bool installable); +}; + +class ManagementInstallReplacementWebAppFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("management.installReplacementWebApp", MANAGEMENT_INSTALLREPLACEMENTWEBAPP) @@ -259,7 +291,7 @@ class ManagementEventRouter : public ExtensionRegistryObserver { content::BrowserContext* browser_context_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; DISALLOW_COPY_AND_ASSIGN(ManagementEventRouter); }; diff --git a/chromium/extensions/browser/api/management/management_api_constants.cc b/chromium/extensions/browser/api/management/management_api_constants.cc index 24136b38c01..873662d1489 100644 --- a/chromium/extensions/browser/api/management/management_api_constants.cc +++ b/chromium/extensions/browser/api/management/management_api_constants.cc @@ -57,5 +57,13 @@ const char kInstallReplacementWebAppNotFromWebstoreError[] = "Only extensions from the web store can install replacement web apps."; const char kGestureNeededForInstallReplacementWebAppError[] = "chrome.management.installReplacementWebApp requires a user gesture."; +const char kGestureNeededForInstallReplacementAndroidAppError[] = + "chrome.management.installReplacementAndroidApp requires a user gesture."; +const char kInstallReplacementAndroidAppInvalidContextError[] = + "Android apps can't be installed in the current user profile."; +const char kInstallReplacementAndroidAppNotFromWebstoreError[] = + "Only extensions from the web store can install replacement Android apps."; +const char kInstallReplacementAndroidAppCannotInstallApp[] = + "Could not install Android App."; } // namespace extension_management_api_constants diff --git a/chromium/extensions/browser/api/management/management_api_constants.h b/chromium/extensions/browser/api/management/management_api_constants.h index 643fd08efda..79a46da39b3 100644 --- a/chromium/extensions/browser/api/management/management_api_constants.h +++ b/chromium/extensions/browser/api/management/management_api_constants.h @@ -41,6 +41,10 @@ extern const char kInstallReplacementWebAppInvalidWebAppError[]; extern const char kInstallReplacementWebAppInvalidContextError[]; extern const char kInstallReplacementWebAppNotFromWebstoreError[]; extern const char kGestureNeededForInstallReplacementWebAppError[]; +extern const char kGestureNeededForInstallReplacementAndroidAppError[]; +extern const char kInstallReplacementAndroidAppCannotInstallApp[]; +extern const char kInstallReplacementAndroidAppInvalidContextError[]; +extern const char kInstallReplacementAndroidAppNotFromWebstoreError[]; } // namespace extension_management_api_constants diff --git a/chromium/extensions/browser/api/management/management_api_delegate.h b/chromium/extensions/browser/api/management/management_api_delegate.h index 0fce1782b0e..03eb0146eb6 100644 --- a/chromium/extensions/browser/api/management/management_api_delegate.h +++ b/chromium/extensions/browser/api/management/management_api_delegate.h @@ -49,6 +49,9 @@ class ManagementAPIDelegate { public: virtual ~ManagementAPIDelegate() {} + using AndroidAppInstallStatusCallback = base::OnceCallback<void(bool)>; + using InstallAndroidAppCallback = base::OnceCallback<void(bool)>; + enum class InstallWebAppResult { kSuccess, kInvalidWebApp, kUnknownError }; typedef base::OnceCallback<void(InstallWebAppResult)> InstallWebAppCallback; @@ -134,6 +137,20 @@ class ManagementAPIDelegate { const GURL& web_app_url, InstallWebAppCallback callback) const = 0; + // Returns whether arc apps can be installed in the given |context|. + virtual bool CanContextInstallAndroidApps( + content::BrowserContext* context) const = 0; + + // Checks the installation status of |package_name|. + virtual void CheckAndroidAppInstallStatus( + const std::string& package_name, + AndroidAppInstallStatusCallback callback) const = 0; + + // Installs an Arc app for |package_name|. + virtual void InstallReplacementAndroidApp( + const std::string& package_name, + InstallAndroidAppCallback callback) const = 0; + // Forwards the call to ExtensionIconSource::GetIconURL in chrome. virtual GURL GetIconURL(const Extension* extension, int icon_size, diff --git a/chromium/extensions/browser/api/media_perception_private/media_perception_api_delegate.h b/chromium/extensions/browser/api/media_perception_private/media_perception_api_delegate.h index 56e789f4329..6262612030c 100644 --- a/chromium/extensions/browser/api/media_perception_private/media_perception_api_delegate.h +++ b/chromium/extensions/browser/api/media_perception_private/media_perception_api_delegate.h @@ -11,8 +11,8 @@ #include "base/files/file_path.h" #include "chromeos/services/media_perception/public/mojom/media_perception_service.mojom.h" #include "extensions/common/api/media_perception_private.h" -#include "services/video_capture/public/mojom/device_factory.mojom.h" -#include "services/video_capture/public/mojom/device_factory_provider.mojom.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "services/video_capture/public/mojom/video_source_provider.mojom.h" namespace content { @@ -26,8 +26,10 @@ class MediaPerceptionAPIDelegate { public: // Callback for loading a CrOS component. |mount_point| will contain a path to // the loaded component, if |success| is true (installation succeeded). - using LoadCrOSComponentCallback = - base::OnceCallback<void(bool success, const base::FilePath& mount_point)>; + using LoadCrOSComponentCallback = base::OnceCallback<void( + const api::media_perception_private::ComponentInstallationError + installation_error, + const base::FilePath& mount_point)>; using MediaPerceptionRequestHandler = base::RepeatingCallback<void( chromeos::media_perception::mojom::MediaPerceptionRequest request)>; @@ -40,12 +42,12 @@ class MediaPerceptionAPIDelegate { const api::media_perception_private::ComponentType& type, LoadCrOSComponentCallback load_callback) = 0; - // Provides an interface to the VideoCaptureService (started lazily by the - // Chrome service manager) to connect the MediaPerceptionService to it and - // establish a direct Mojo IPC-based connection. - // |provider| is owned by the caller. - virtual void BindDeviceFactoryProviderToVideoCaptureService( - video_capture::mojom::DeviceFactoryProviderPtr* provider) = 0; + // Provides an interface to the Video Capture service (started lazily by the + // browser) to connect the MediaPerceptionService to it and establish a direct + // Mojo IPC-based connection. + virtual void BindVideoSourceProvider( + mojo::PendingReceiver<video_capture::mojom::VideoSourceProvider> + receiver) = 0; // Provides an interface to set a handler for an incoming // MediaPerceptionRequest. diff --git a/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager.cc b/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager.cc index e555a53d175..68bc3a52af5 100644 --- a/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager.cc +++ b/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager.cc @@ -14,7 +14,6 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/media_analytics/media_analytics_client.h" #include "chromeos/dbus/upstart/upstart_client.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/api/media_perception_private/conversion_utils.h" @@ -25,7 +24,6 @@ #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/invitation.h" -#include "services/video_capture/public/mojom/device_factory_provider.mojom.h" namespace extensions { @@ -101,9 +99,7 @@ class MediaPerceptionAPIManager::MediaPerceptionControllerClient void ConnectToVideoCaptureService( video_capture::mojom::VideoSourceProviderRequest request) override { DCHECK(delegate_) << "Delegate not set."; - delegate_->BindDeviceFactoryProviderToVideoCaptureService( - &device_factory_provider_); - device_factory_provider_->ConnectToVideoSourceProvider(std::move(request)); + delegate_->BindVideoSourceProvider(std::move(request)); } private: @@ -115,10 +111,6 @@ class MediaPerceptionAPIManager::MediaPerceptionControllerClient chromeos::media_perception::mojom::MediaPerceptionControllerClient> binding_; - // Bound to the VideoCaptureService to establish the connection to the - // media analytics process. - video_capture::mojom::DeviceFactoryProviderPtr device_factory_provider_; - DISALLOW_COPY_AND_ASSIGN(MediaPerceptionControllerClient); }; @@ -141,9 +133,7 @@ MediaPerceptionAPIManager::GetFactoryInstance() { MediaPerceptionAPIManager::MediaPerceptionAPIManager( content::BrowserContext* context) : browser_context_(context), - analytics_process_state_(AnalyticsProcessState::IDLE), - scoped_observer_(this), - weak_ptr_factory_(this) { + analytics_process_state_(AnalyticsProcessState::IDLE) { scoped_observer_.Add(chromeos::MediaAnalyticsClient::Get()); } @@ -204,10 +194,15 @@ void MediaPerceptionAPIManager::SetAnalyticsComponent( void MediaPerceptionAPIManager::LoadComponentCallback( APISetAnalyticsComponentCallback callback, - bool success, + const extensions::api::media_perception_private::ComponentInstallationError + installation_error, const base::FilePath& mount_point) { - if (!success) { - std::move(callback).Run(GetFailedToInstallComponentState()); + if (installation_error != extensions::api::media_perception_private:: + COMPONENT_INSTALLATION_ERROR_NONE) { + extensions::api::media_perception_private::ComponentState component_state = + GetFailedToInstallComponentState(); + component_state.installation_error_code = installation_error; + std::move(callback).Run(std::move(component_state)); return; } diff --git a/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager.h b/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager.h index 4d2a78fa570..db7ef030084 100644 --- a/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager.h +++ b/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager.h @@ -131,7 +131,8 @@ class MediaPerceptionAPIManager // Callback with the mount point for a loaded component. void LoadComponentCallback(APISetAnalyticsComponentCallback callback, - bool success, + const extensions::api::media_perception_private:: + ComponentInstallationError installation_error, const base::FilePath& mount_point); bool ComponentIsLoaded(); @@ -158,9 +159,10 @@ class MediaPerceptionAPIManager std::unique_ptr<MediaPerceptionControllerClient> media_perception_controller_client_; - ScopedObserver<chromeos::MediaAnalyticsClient, MediaPerceptionAPIManager> - scoped_observer_; - base::WeakPtrFactory<MediaPerceptionAPIManager> weak_ptr_factory_; + ScopedObserver<chromeos::MediaAnalyticsClient, + chromeos::MediaAnalyticsClient::Observer> + scoped_observer_{this}; + base::WeakPtrFactory<MediaPerceptionAPIManager> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MediaPerceptionAPIManager); }; diff --git a/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager_unittest.cc b/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager_unittest.cc index d43af6f737c..c516a5d61e9 100644 --- a/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager_unittest.cc +++ b/chromium/extensions/browser/api/media_perception_private/media_perception_api_manager_unittest.cc @@ -12,8 +12,8 @@ #include "chromeos/dbus/media_analytics/fake_media_analytics_client.h" #include "chromeos/dbus/media_analytics/media_analytics_client.h" #include "chromeos/dbus/upstart/fake_upstart_client.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" namespace media_perception = extensions::api::media_perception_private; @@ -181,7 +181,7 @@ class MediaPerceptionAPIManagerTest : public testing::Test { TestUpstartClient* upstart_client() { return upstart_client_.get(); } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; content::TestBrowserContext browser_context_; std::unique_ptr<TestUpstartClient> upstart_client_; diff --git a/chromium/extensions/browser/api/media_perception_private/media_perception_private_api.h b/chromium/extensions/browser/api/media_perception_private/media_perception_private_api.h index bb11a4a9d19..a2bc396963a 100644 --- a/chromium/extensions/browser/api/media_perception_private/media_perception_private_api.h +++ b/chromium/extensions/browser/api/media_perception_private/media_perception_private_api.h @@ -11,8 +11,7 @@ namespace extensions { -class MediaPerceptionPrivateGetStateFunction - : public UIThreadExtensionFunction { +class MediaPerceptionPrivateGetStateFunction : public ExtensionFunction { public: MediaPerceptionPrivateGetStateFunction(); DECLARE_EXTENSION_FUNCTION("mediaPerceptionPrivate.getState", @@ -29,8 +28,7 @@ class MediaPerceptionPrivateGetStateFunction DISALLOW_COPY_AND_ASSIGN(MediaPerceptionPrivateGetStateFunction); }; -class MediaPerceptionPrivateSetStateFunction - : public UIThreadExtensionFunction { +class MediaPerceptionPrivateSetStateFunction : public ExtensionFunction { public: MediaPerceptionPrivateSetStateFunction(); DECLARE_EXTENSION_FUNCTION("mediaPerceptionPrivate.setState", @@ -47,8 +45,7 @@ class MediaPerceptionPrivateSetStateFunction DISALLOW_COPY_AND_ASSIGN(MediaPerceptionPrivateSetStateFunction); }; -class MediaPerceptionPrivateGetDiagnosticsFunction - : public UIThreadExtensionFunction { +class MediaPerceptionPrivateGetDiagnosticsFunction : public ExtensionFunction { public: MediaPerceptionPrivateGetDiagnosticsFunction(); DECLARE_EXTENSION_FUNCTION("mediaPerceptionPrivate.getDiagnostics", @@ -67,7 +64,7 @@ class MediaPerceptionPrivateGetDiagnosticsFunction }; class MediaPerceptionPrivateSetAnalyticsComponentFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: MediaPerceptionPrivateSetAnalyticsComponentFunction(); DECLARE_EXTENSION_FUNCTION("mediaPerceptionPrivate.setAnalyticsComponent", @@ -87,7 +84,7 @@ class MediaPerceptionPrivateSetAnalyticsComponentFunction }; class MediaPerceptionPrivateSetComponentProcessStateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: MediaPerceptionPrivateSetComponentProcessStateFunction(); DECLARE_EXTENSION_FUNCTION("mediaPerceptionPrivate.setComponentProcessState", diff --git a/chromium/extensions/browser/api/media_perception_private/media_perception_private_apitest.cc b/chromium/extensions/browser/api/media_perception_private/media_perception_private_apitest.cc index 51c3644bc63..a029f4faf91 100644 --- a/chromium/extensions/browser/api/media_perception_private/media_perception_private_apitest.cc +++ b/chromium/extensions/browser/api/media_perception_private/media_perception_private_apitest.cc @@ -36,20 +36,22 @@ class TestMediaPerceptionAPIDelegate : public MediaPerceptionAPIDelegate { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( - std::move(load_callback), true, + std::move(load_callback), + media_perception::COMPONENT_INSTALLATION_ERROR_NONE, base::FilePath("/run/imageloader/rtanalytics-light/1.0"))); return; } - // Firing callback with false indicates that the installation of the - // component failed. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, - base::BindOnce(std::move(load_callback), false, base::FilePath())); + base::BindOnce(std::move(load_callback), + media_perception::COMPONENT_INSTALLATION_ERROR_NOT_FOUND, + base::FilePath())); } - void BindDeviceFactoryProviderToVideoCaptureService( - video_capture::mojom::DeviceFactoryProviderPtr* provider) override { + void BindVideoSourceProvider( + mojo::PendingReceiver<video_capture::mojom::VideoSourceProvider> receiver) + override { NOTIMPLEMENTED(); } diff --git a/chromium/extensions/browser/api/metrics_private/metrics_private_api.h b/chromium/extensions/browser/api/metrics_private/metrics_private_api.h index d0d51a7643f..afe87fa84df 100644 --- a/chromium/extensions/browser/api/metrics_private/metrics_private_api.h +++ b/chromium/extensions/browser/api/metrics_private/metrics_private_api.h @@ -15,7 +15,7 @@ namespace extensions { class MetricsPrivateGetIsCrashReportingEnabledFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("metricsPrivate.getIsCrashReportingEnabled", METRICSPRIVATE_GETISCRASHRECORDINGENABLED) @@ -27,7 +27,7 @@ class MetricsPrivateGetIsCrashReportingEnabledFunction ResponseAction Run() override; }; -class MetricsPrivateGetFieldTrialFunction : public UIThreadExtensionFunction { +class MetricsPrivateGetFieldTrialFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("metricsPrivate.getFieldTrial", METRICSPRIVATE_GETFIELDTRIAL) @@ -39,8 +39,7 @@ class MetricsPrivateGetFieldTrialFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class MetricsPrivateGetVariationParamsFunction - : public UIThreadExtensionFunction { +class MetricsPrivateGetVariationParamsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("metricsPrivate.getVariationParams", METRICSPRIVATE_GETVARIATIONPARAMS) @@ -52,8 +51,7 @@ class MetricsPrivateGetVariationParamsFunction ResponseAction Run() override; }; -class MetricsPrivateRecordUserActionFunction - : public UIThreadExtensionFunction { +class MetricsPrivateRecordUserActionFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("metricsPrivate.recordUserAction", METRICSPRIVATE_RECORDUSERACTION) @@ -65,7 +63,7 @@ class MetricsPrivateRecordUserActionFunction ResponseAction Run() override; }; -class MetricsHistogramHelperFunction : public UIThreadExtensionFunction { +class MetricsHistogramHelperFunction : public ExtensionFunction { protected: ~MetricsHistogramHelperFunction() override {} void RecordValue(const std::string& name, diff --git a/chromium/extensions/browser/api/networking_config/networking_config_api.h b/chromium/extensions/browser/api/networking_config/networking_config_api.h index 3ba980516b4..eb4c4eb4dc6 100644 --- a/chromium/extensions/browser/api/networking_config/networking_config_api.h +++ b/chromium/extensions/browser/api/networking_config/networking_config_api.h @@ -11,8 +11,7 @@ namespace extensions { -class NetworkingConfigSetNetworkFilterFunction - : public UIThreadExtensionFunction { +class NetworkingConfigSetNetworkFilterFunction : public ExtensionFunction { public: NetworkingConfigSetNetworkFilterFunction(); @@ -30,8 +29,7 @@ class NetworkingConfigSetNetworkFilterFunction DISALLOW_COPY_AND_ASSIGN(NetworkingConfigSetNetworkFilterFunction); }; -class NetworkingConfigFinishAuthenticationFunction - : public UIThreadExtensionFunction { +class NetworkingConfigFinishAuthenticationFunction : public ExtensionFunction { public: NetworkingConfigFinishAuthenticationFunction(); diff --git a/chromium/extensions/browser/api/networking_config/networking_config_service.cc b/chromium/extensions/browser/api/networking_config/networking_config_service.cc index f14ba953351..c5a36b0925e 100644 --- a/chromium/extensions/browser/api/networking_config/networking_config_service.cc +++ b/chromium/extensions/browser/api/networking_config/networking_config_service.cc @@ -67,14 +67,11 @@ NetworkingConfigService::NetworkingConfigService( std::unique_ptr<EventDelegate> event_delegate, ExtensionRegistry* extension_registry) : browser_context_(browser_context), - registry_observer_(this), - event_delegate_(std::move(event_delegate)), - weak_factory_(this) { + event_delegate_(std::move(event_delegate)) { registry_observer_.Add(extension_registry); } -NetworkingConfigService::~NetworkingConfigService() { -} +NetworkingConfigService::~NetworkingConfigService() = default; void NetworkingConfigService::OnExtensionUnloaded( content::BrowserContext* browser_context, diff --git a/chromium/extensions/browser/api/networking_config/networking_config_service.h b/chromium/extensions/browser/api/networking_config/networking_config_service.h index e7ccfad9f84..bb579a99904 100644 --- a/chromium/extensions/browser/api/networking_config/networking_config_service.h +++ b/chromium/extensions/browser/api/networking_config/networking_config_service.h @@ -133,14 +133,14 @@ class NetworkingConfigService : public ExtensionRegistryObserver, base::Closure authentication_callback_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - registry_observer_; + registry_observer_{this}; std::unique_ptr<EventDelegate> event_delegate_; // This map associates a given hex encoded SSID to an extension entry. std::map<std::string, std::string> hex_ssid_to_extension_id_; - base::WeakPtrFactory<NetworkingConfigService> weak_factory_; + base::WeakPtrFactory<NetworkingConfigService> weak_factory_{this}; }; } // namespace extensions diff --git a/chromium/extensions/browser/api/networking_private/networking_private_api.cc b/chromium/extensions/browser/api/networking_private/networking_private_api.cc index b2d03fa7940..3a703397d32 100644 --- a/chromium/extensions/browser/api/networking_private/networking_private_api.cc +++ b/chromium/extensions/browser/api/networking_private/networking_private_api.cc @@ -486,9 +486,6 @@ NetworkingPrivateGetEnabledNetworkTypesFunction::Run() { } else if (type == ::onc::network_type::kWiFi) { enabled_networks_list->AppendString( private_api::ToString(private_api::NETWORK_TYPE_WIFI)); - } else if (type == ::onc::network_type::kWimax) { - enabled_networks_list->AppendString( - private_api::ToString(private_api::NETWORK_TYPE_WIMAX)); } else if (type == ::onc::network_type::kCellular) { enabled_networks_list->AppendString( private_api::ToString(private_api::NETWORK_TYPE_CELLULAR)); diff --git a/chromium/extensions/browser/api/networking_private/networking_private_api.h b/chromium/extensions/browser/api/networking_private/networking_private_api.h index 0d473c76beb..591c8ec6f5a 100644 --- a/chromium/extensions/browser/api/networking_private/networking_private_api.h +++ b/chromium/extensions/browser/api/networking_private/networking_private_api.h @@ -30,8 +30,7 @@ extern const char kErrorUnconfiguredNetwork[]; } // namespace networking_private // Implements the chrome.networkingPrivate.getProperties method. -class NetworkingPrivateGetPropertiesFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateGetPropertiesFunction : public ExtensionFunction { public: NetworkingPrivateGetPropertiesFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.getProperties", @@ -51,8 +50,7 @@ class NetworkingPrivateGetPropertiesFunction }; // Implements the chrome.networkingPrivate.getManagedProperties method. -class NetworkingPrivateGetManagedPropertiesFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateGetManagedPropertiesFunction : public ExtensionFunction { public: NetworkingPrivateGetManagedPropertiesFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.getManagedProperties", @@ -72,7 +70,7 @@ class NetworkingPrivateGetManagedPropertiesFunction }; // Implements the chrome.networkingPrivate.getState method. -class NetworkingPrivateGetStateFunction : public UIThreadExtensionFunction { +class NetworkingPrivateGetStateFunction : public ExtensionFunction { public: NetworkingPrivateGetStateFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.getState", @@ -92,8 +90,7 @@ class NetworkingPrivateGetStateFunction : public UIThreadExtensionFunction { }; // Implements the chrome.networkingPrivate.setProperties method. -class NetworkingPrivateSetPropertiesFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateSetPropertiesFunction : public ExtensionFunction { public: NetworkingPrivateSetPropertiesFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.setProperties", @@ -113,8 +110,7 @@ class NetworkingPrivateSetPropertiesFunction }; // Implements the chrome.networkingPrivate.createNetwork method. -class NetworkingPrivateCreateNetworkFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateCreateNetworkFunction : public ExtensionFunction { public: NetworkingPrivateCreateNetworkFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.createNetwork", @@ -134,8 +130,7 @@ class NetworkingPrivateCreateNetworkFunction }; // Implements the chrome.networkingPrivate.createNetwork method. -class NetworkingPrivateForgetNetworkFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateForgetNetworkFunction : public ExtensionFunction { public: NetworkingPrivateForgetNetworkFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.forgetNetwork", @@ -155,7 +150,7 @@ class NetworkingPrivateForgetNetworkFunction }; // Implements the chrome.networkingPrivate.getNetworks method. -class NetworkingPrivateGetNetworksFunction : public UIThreadExtensionFunction { +class NetworkingPrivateGetNetworksFunction : public ExtensionFunction { public: NetworkingPrivateGetNetworksFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.getNetworks", @@ -175,8 +170,7 @@ class NetworkingPrivateGetNetworksFunction : public UIThreadExtensionFunction { }; // Implements the chrome.networkingPrivate.getVisibleNetworks method. -class NetworkingPrivateGetVisibleNetworksFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateGetVisibleNetworksFunction : public ExtensionFunction { public: NetworkingPrivateGetVisibleNetworksFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.getVisibleNetworks", @@ -197,7 +191,7 @@ class NetworkingPrivateGetVisibleNetworksFunction // Implements the chrome.networkingPrivate.getEnabledNetworkTypes method. class NetworkingPrivateGetEnabledNetworkTypesFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingPrivateGetEnabledNetworkTypesFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.getEnabledNetworkTypes", @@ -214,8 +208,7 @@ class NetworkingPrivateGetEnabledNetworkTypesFunction }; // Implements the chrome.networkingPrivate.getDeviceStates method. -class NetworkingPrivateGetDeviceStatesFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateGetDeviceStatesFunction : public ExtensionFunction { public: NetworkingPrivateGetDeviceStatesFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.getDeviceStates", @@ -232,8 +225,7 @@ class NetworkingPrivateGetDeviceStatesFunction }; // Implements the chrome.networkingPrivate.enableNetworkType method. -class NetworkingPrivateEnableNetworkTypeFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateEnableNetworkTypeFunction : public ExtensionFunction { public: NetworkingPrivateEnableNetworkTypeFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.enableNetworkType", @@ -250,8 +242,7 @@ class NetworkingPrivateEnableNetworkTypeFunction }; // Implements the chrome.networkingPrivate.disableNetworkType method. -class NetworkingPrivateDisableNetworkTypeFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateDisableNetworkTypeFunction : public ExtensionFunction { public: NetworkingPrivateDisableNetworkTypeFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.disableNetworkType", @@ -268,8 +259,7 @@ class NetworkingPrivateDisableNetworkTypeFunction }; // Implements the chrome.networkingPrivate.requestNetworkScan method. -class NetworkingPrivateRequestNetworkScanFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateRequestNetworkScanFunction : public ExtensionFunction { public: NetworkingPrivateRequestNetworkScanFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.requestNetworkScan", @@ -286,7 +276,7 @@ class NetworkingPrivateRequestNetworkScanFunction }; // Implements the chrome.networkingPrivate.startConnect method. -class NetworkingPrivateStartConnectFunction : public UIThreadExtensionFunction { +class NetworkingPrivateStartConnectFunction : public ExtensionFunction { public: NetworkingPrivateStartConnectFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.startConnect", @@ -306,8 +296,7 @@ class NetworkingPrivateStartConnectFunction : public UIThreadExtensionFunction { }; // Implements the chrome.networkingPrivate.startDisconnect method. -class NetworkingPrivateStartDisconnectFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateStartDisconnectFunction : public ExtensionFunction { public: NetworkingPrivateStartDisconnectFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.startDisconnect", @@ -327,8 +316,7 @@ class NetworkingPrivateStartDisconnectFunction }; // Implements the chrome.networkingPrivate.startActivate method. -class NetworkingPrivateStartActivateFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateStartActivateFunction : public ExtensionFunction { public: NetworkingPrivateStartActivateFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.startActivate", @@ -348,8 +336,7 @@ class NetworkingPrivateStartActivateFunction }; // Implements the chrome.networkingPrivate.verifyDestination method. -class NetworkingPrivateVerifyDestinationFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateVerifyDestinationFunction : public ExtensionFunction { public: NetworkingPrivateVerifyDestinationFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.verifyDestination", @@ -369,8 +356,7 @@ class NetworkingPrivateVerifyDestinationFunction }; // Implements the chrome.networkingPrivate.verifyAndEncryptData method. -class NetworkingPrivateVerifyAndEncryptDataFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateVerifyAndEncryptDataFunction : public ExtensionFunction { public: NetworkingPrivateVerifyAndEncryptDataFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.verifyAndEncryptData", @@ -391,7 +377,7 @@ class NetworkingPrivateVerifyAndEncryptDataFunction // Implements the chrome.networkingPrivate.setWifiTDLSEnabledState method. class NetworkingPrivateSetWifiTDLSEnabledStateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingPrivateSetWifiTDLSEnabledStateFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.setWifiTDLSEnabledState", @@ -411,8 +397,7 @@ class NetworkingPrivateSetWifiTDLSEnabledStateFunction }; // Implements the chrome.networkingPrivate.getWifiTDLSStatus method. -class NetworkingPrivateGetWifiTDLSStatusFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateGetWifiTDLSStatusFunction : public ExtensionFunction { public: NetworkingPrivateGetWifiTDLSStatusFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.getWifiTDLSStatus", @@ -432,7 +417,7 @@ class NetworkingPrivateGetWifiTDLSStatusFunction }; class NetworkingPrivateGetCaptivePortalStatusFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingPrivateGetCaptivePortalStatusFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.getCaptivePortalStatus", @@ -451,8 +436,7 @@ class NetworkingPrivateGetCaptivePortalStatusFunction DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateGetCaptivePortalStatusFunction); }; -class NetworkingPrivateUnlockCellularSimFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateUnlockCellularSimFunction : public ExtensionFunction { public: NetworkingPrivateUnlockCellularSimFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.unlockCellularSim", @@ -471,8 +455,7 @@ class NetworkingPrivateUnlockCellularSimFunction DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateUnlockCellularSimFunction); }; -class NetworkingPrivateSetCellularSimStateFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateSetCellularSimStateFunction : public ExtensionFunction { public: NetworkingPrivateSetCellularSimStateFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.setCellularSimState", @@ -492,7 +475,7 @@ class NetworkingPrivateSetCellularSimStateFunction }; class NetworkingPrivateSelectCellularMobileNetworkFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingPrivateSelectCellularMobileNetworkFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.selectCellularMobileNetwork", @@ -512,8 +495,7 @@ class NetworkingPrivateSelectCellularMobileNetworkFunction NetworkingPrivateSelectCellularMobileNetworkFunction); }; -class NetworkingPrivateGetGlobalPolicyFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateGetGlobalPolicyFunction : public ExtensionFunction { public: NetworkingPrivateGetGlobalPolicyFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.getGlobalPolicy", @@ -529,8 +511,7 @@ class NetworkingPrivateGetGlobalPolicyFunction DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateGetGlobalPolicyFunction); }; -class NetworkingPrivateGetCertificateListsFunction - : public UIThreadExtensionFunction { +class NetworkingPrivateGetCertificateListsFunction : public ExtensionFunction { public: NetworkingPrivateGetCertificateListsFunction() {} DECLARE_EXTENSION_FUNCTION("networkingPrivate.getCertificateLists", diff --git a/chromium/extensions/browser/api/networking_private/networking_private_chromeos.cc b/chromium/extensions/browser/api/networking_private/networking_private_chromeos.cc index a3f086468fd..0e235b564f0 100644 --- a/chromium/extensions/browser/api/networking_private/networking_private_chromeos.cc +++ b/chromium/extensions/browser/api/networking_private/networking_private_chromeos.cc @@ -124,6 +124,9 @@ void AppendDeviceState( case NetworkStateHandler::TECHNOLOGY_AVAILABLE: state = private_api::DEVICE_STATE_TYPE_DISABLED; break; + case NetworkStateHandler::TECHNOLOGY_DISABLING: + state = private_api::DEVICE_STATE_TYPE_DISABLED; + break; case NetworkStateHandler::TECHNOLOGY_UNINITIALIZED: state = private_api::DEVICE_STATE_TYPE_UNINITIALIZED; break; @@ -242,7 +245,7 @@ namespace extensions { NetworkingPrivateChromeOS::NetworkingPrivateChromeOS( content::BrowserContext* browser_context) - : browser_context_(browser_context), weak_ptr_factory_(this) {} + : browser_context_(browser_context) {} NetworkingPrivateChromeOS::~NetworkingPrivateChromeOS() {} @@ -654,8 +657,6 @@ NetworkingPrivateChromeOS::GetEnabledNetworkTypes() { network_list->AppendString(::onc::network_type::kEthernet); if (state_handler->IsTechnologyEnabled(NetworkTypePattern::WiFi())) network_list->AppendString(::onc::network_type::kWiFi); - if (state_handler->IsTechnologyEnabled(NetworkTypePattern::Wimax())) - network_list->AppendString(::onc::network_type::kWimax); if (state_handler->IsTechnologyEnabled(NetworkTypePattern::Cellular())) network_list->AppendString(::onc::network_type::kCellular); @@ -678,9 +679,9 @@ NetworkingPrivateChromeOS::GetDeviceStateList() { // For any technologies that we do not have a DeviceState entry for, append // an entry if the technology is available. - const char* technology_types[] = { - ::onc::network_type::kEthernet, ::onc::network_type::kWiFi, - ::onc::network_type::kWimax, ::onc::network_type::kCellular}; + const char* technology_types[] = {::onc::network_type::kEthernet, + ::onc::network_type::kWiFi, + ::onc::network_type::kCellular}; for (const char* technology : technology_types) { if (base::Contains(technologies_found, technology)) continue; diff --git a/chromium/extensions/browser/api/networking_private/networking_private_chromeos.h b/chromium/extensions/browser/api/networking_private/networking_private_chromeos.h index 9750a604e35..a9aea32e576 100644 --- a/chromium/extensions/browser/api/networking_private/networking_private_chromeos.h +++ b/chromium/extensions/browser/api/networking_private/networking_private_chromeos.h @@ -124,7 +124,7 @@ class NetworkingPrivateChromeOS : public NetworkingPrivateDelegate { base::DictionaryValue* dictionary); content::BrowserContext* browser_context_; - base::WeakPtrFactory<NetworkingPrivateChromeOS> weak_ptr_factory_; + base::WeakPtrFactory<NetworkingPrivateChromeOS> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateChromeOS); }; diff --git a/chromium/extensions/browser/api/networking_private/networking_private_linux.cc b/chromium/extensions/browser/api/networking_private/networking_private_linux.cc index b13bdc75bf5..37ca2849b78 100644 --- a/chromium/extensions/browser/api/networking_private/networking_private_linux.cc +++ b/chromium/extensions/browser/api/networking_private/networking_private_linux.cc @@ -9,7 +9,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" -#include "base/message_loop/message_loop.h" +#include "base/memory/scoped_refptr.h" #include "base/strings/string16.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" @@ -138,7 +138,7 @@ void GetCachedNetworkPropertiesCallback( NetworkingPrivateLinux::NetworkingPrivateLinux() : dbus_thread_("Networking Private DBus"), network_manager_proxy_(NULL) { - base::Thread::Options thread_options(base::MessageLoop::Type::IO, 0); + base::Thread::Options thread_options(base::MessagePumpType::IO, 0); dbus_thread_.StartWithOptions(thread_options); dbus_thread_.task_runner()->PostTask( @@ -169,7 +169,7 @@ void NetworkingPrivateLinux::Initialize() { dbus_options.connection_type = dbus::Bus::PRIVATE; dbus_options.dbus_task_runner = dbus_task_runner_; - dbus_ = new dbus::Bus(dbus_options); + dbus_ = base::MakeRefCounted<dbus::Bus>(dbus_options); network_manager_proxy_ = dbus_->GetObjectProxy( networking_private::kNetworkManagerNamespace, dbus::ObjectPath(networking_private::kNetworkManagerPath)); @@ -1222,7 +1222,7 @@ void NetworkingPrivateLinux::PostOnNetworksChangedToUIThread( std::unique_ptr<GuidList> guid_list) { AssertOnDBusThread(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&NetworkingPrivateLinux::OnNetworksChangedEventTask, base::Unretained(this), std::move(guid_list))); diff --git a/chromium/extensions/browser/api/networking_private/networking_private_service_client.cc b/chromium/extensions/browser/api/networking_private/networking_private_service_client.cc index 242a70e5e6d..18b69cb7a4e 100644 --- a/chromium/extensions/browser/api/networking_private/networking_private_service_client.cc +++ b/chromium/extensions/browser/api/networking_private/networking_private_service_client.cc @@ -51,8 +51,7 @@ NetworkingPrivateServiceClient::ServiceCallbacks::~ServiceCallbacks() { NetworkingPrivateServiceClient::NetworkingPrivateServiceClient( std::unique_ptr<WiFiService> wifi_service) : wifi_service_(std::move(wifi_service)), - task_runner_(g_sequenced_task_runner.Get()), - weak_factory_(this) { + task_runner_(g_sequenced_task_runner.Get()) { task_runner_->PostTask( FROM_HERE, base::BindOnce(&WiFiService::Initialize, diff --git a/chromium/extensions/browser/api/networking_private/networking_private_service_client.h b/chromium/extensions/browser/api/networking_private/networking_private_service_client.h index fe99000a5db..3c918f39129 100644 --- a/chromium/extensions/browser/api/networking_private/networking_private_service_client.h +++ b/chromium/extensions/browser/api/networking_private/networking_private_service_client.h @@ -180,7 +180,7 @@ class NetworkingPrivateServiceClient // Task runner for worker tasks. scoped_refptr<base::SequencedTaskRunner> task_runner_; // Use WeakPtrs for callbacks from |wifi_service_|. - base::WeakPtrFactory<NetworkingPrivateServiceClient> weak_factory_; + base::WeakPtrFactory<NetworkingPrivateServiceClient> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateServiceClient); }; diff --git a/chromium/extensions/browser/api/power/power_api.cc b/chromium/extensions/browser/api/power/power_api.cc index 6e1e888e27e..9865c7a0656 100644 --- a/chromium/extensions/browser/api/power/power_api.cc +++ b/chromium/extensions/browser/api/power/power_api.cc @@ -12,7 +12,6 @@ #include "extensions/browser/extension_registry.h" #include "extensions/common/api/power.h" #include "extensions/common/extension.h" -#include "mojo/public/cpp/bindings/interface_request.h" #include "services/device/public/mojom/constants.mojom.h" #include "services/device/public/mojom/wake_lock_provider.mojom.h" #include "services/service_manager/public/cpp/connector.h" @@ -155,17 +154,15 @@ device::mojom::WakeLock* PowerAPI::GetWakeLock() { if (wake_lock_) return wake_lock_.get(); - device::mojom::WakeLockRequest request = mojo::MakeRequest(&wake_lock_); - auto* connector = content::GetSystemConnector(); DCHECK(connector); - device::mojom::WakeLockProviderPtr wake_lock_provider; - connector->BindInterface(device::mojom::kServiceName, - mojo::MakeRequest(&wake_lock_provider)); + mojo::Remote<device::mojom::WakeLockProvider> wake_lock_provider; + connector->Connect(device::mojom::kServiceName, + wake_lock_provider.BindNewPipeAndPassReceiver()); wake_lock_provider->GetWakeLockWithoutContext( LevelToWakeLockType(current_level_), device::mojom::WakeLockReason::kOther, kWakeLockDescription, - std::move(request)); + wake_lock_.BindNewPipeAndPassReceiver()); return wake_lock_.get(); } diff --git a/chromium/extensions/browser/api/power/power_api.h b/chromium/extensions/browser/api/power/power_api.h index 3acfe4218a8..54dcbd3ce79 100644 --- a/chromium/extensions/browser/api/power/power_api.h +++ b/chromium/extensions/browser/api/power/power_api.h @@ -16,6 +16,7 @@ #include "extensions/browser/extension_function.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/common/api/power.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/wake_lock.mojom.h" namespace content { @@ -25,7 +26,7 @@ class BrowserContext; namespace extensions { // Implementation of the chrome.power.requestKeepAwake API. -class PowerRequestKeepAwakeFunction : public UIThreadExtensionFunction { +class PowerRequestKeepAwakeFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("power.requestKeepAwake", POWER_REQUESTKEEPAWAKE) @@ -37,7 +38,7 @@ class PowerRequestKeepAwakeFunction : public UIThreadExtensionFunction { }; // Implementation of the chrome.power.releaseKeepAwake API. -class PowerReleaseKeepAwakeFunction : public UIThreadExtensionFunction { +class PowerReleaseKeepAwakeFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("power.releaseKeepAwake", POWER_RELEASEKEEPAWAKE) @@ -126,7 +127,7 @@ class PowerAPI : public BrowserContextKeyedAPI, ActivateWakeLockFunction activate_wake_lock_function_; CancelWakeLockFunction cancel_wake_lock_function_; - device::mojom::WakeLockPtr wake_lock_; + mojo::Remote<device::mojom::WakeLock> wake_lock_; bool is_wake_lock_active_; // Current level used by wake lock. diff --git a/chromium/extensions/browser/api/power/power_api_unittest.cc b/chromium/extensions/browser/api/power/power_api_unittest.cc index f371bbaa058..8a74267c857 100644 --- a/chromium/extensions/browser/api/power/power_api_unittest.cc +++ b/chromium/extensions/browser/api/power/power_api_unittest.cc @@ -171,12 +171,11 @@ class PowerAPITest : public ApiUnitTest { bool CallFunction(FunctionType type, const std::string& args, const extensions::Extension* extension) { - scoped_refptr<UIThreadExtensionFunction> function( - type == REQUEST ? - static_cast<UIThreadExtensionFunction*>( - new PowerRequestKeepAwakeFunction) : - static_cast<UIThreadExtensionFunction*>( - new PowerReleaseKeepAwakeFunction)); + scoped_refptr<ExtensionFunction> function( + type == REQUEST + ? static_cast<ExtensionFunction*>(new PowerRequestKeepAwakeFunction) + : static_cast<ExtensionFunction*>( + new PowerReleaseKeepAwakeFunction)); function->set_extension(extension); return api_test_utils::RunFunction(function.get(), args, browser_context()); } diff --git a/chromium/extensions/browser/api/printer_provider/printer_provider_api.cc b/chromium/extensions/browser/api/printer_provider/printer_provider_api.cc index a4079186289..2c748ea8283 100644 --- a/chromium/extensions/browser/api/printer_provider/printer_provider_api.cc +++ b/chromium/extensions/browser/api/printer_provider/printer_provider_api.cc @@ -284,6 +284,7 @@ class PrinterProviderAPIImpl : public PrinterProviderAPI, // with the event. bool WillRequestPrinters(int request_id, content::BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter); @@ -301,10 +302,10 @@ class PrinterProviderAPIImpl : public PrinterProviderAPI, pending_usb_printer_info_requests_; ScopedObserver<PrinterProviderInternalAPI, PrinterProviderInternalAPIObserver> - internal_api_observer_; + internal_api_observer_{this}; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; DISALLOW_COPY_AND_ASSIGN(PrinterProviderAPIImpl); }; @@ -502,9 +503,7 @@ void PendingUsbPrinterInfoRequests::FailAll() { PrinterProviderAPIImpl::PrinterProviderAPIImpl( content::BrowserContext* browser_context) - : browser_context_(browser_context), - internal_api_observer_(this), - extension_registry_observer_(this) { + : browser_context_(browser_context) { internal_api_observer_.Add( PrinterProviderInternalAPI::GetFactoryInstance()->Get(browser_context)); extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context)); @@ -736,6 +735,7 @@ void PrinterProviderAPIImpl::OnExtensionUnloaded( bool PrinterProviderAPIImpl::WillRequestPrinters( int request_id, content::BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { diff --git a/chromium/extensions/browser/api/printer_provider_internal/printer_provider_internal_api.h b/chromium/extensions/browser/api/printer_provider_internal/printer_provider_internal_api.h index 12540ff0a9a..dc1aef5d265 100644 --- a/chromium/extensions/browser/api/printer_provider_internal/printer_provider_internal_api.h +++ b/chromium/extensions/browser/api/printer_provider_internal/printer_provider_internal_api.h @@ -90,7 +90,7 @@ class PrinterProviderInternalAPI : public BrowserContextKeyedAPI { }; class PrinterProviderInternalReportPrintResultFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: PrinterProviderInternalReportPrintResultFunction(); @@ -107,7 +107,7 @@ class PrinterProviderInternalReportPrintResultFunction }; class PrinterProviderInternalReportPrinterCapabilityFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: PrinterProviderInternalReportPrinterCapabilityFunction(); @@ -124,8 +124,7 @@ class PrinterProviderInternalReportPrinterCapabilityFunction PrinterProviderInternalReportPrinterCapabilityFunction); }; -class PrinterProviderInternalReportPrintersFunction - : public UIThreadExtensionFunction { +class PrinterProviderInternalReportPrintersFunction : public ExtensionFunction { public: PrinterProviderInternalReportPrintersFunction(); @@ -140,8 +139,7 @@ class PrinterProviderInternalReportPrintersFunction DISALLOW_COPY_AND_ASSIGN(PrinterProviderInternalReportPrintersFunction); }; -class PrinterProviderInternalGetPrintDataFunction - : public UIThreadExtensionFunction { +class PrinterProviderInternalGetPrintDataFunction : public ExtensionFunction { public: PrinterProviderInternalGetPrintDataFunction(); @@ -161,7 +159,7 @@ class PrinterProviderInternalGetPrintDataFunction }; class PrinterProviderInternalReportUsbPrinterInfoFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: PrinterProviderInternalReportUsbPrinterInfoFunction(); diff --git a/chromium/extensions/browser/api/runtime/restart_after_delay_api_unittest.cc b/chromium/extensions/browser/api/runtime/restart_after_delay_api_unittest.cc index a963b450919..030edb0c2c1 100644 --- a/chromium/extensions/browser/api/runtime/restart_after_delay_api_unittest.cc +++ b/chromium/extensions/browser/api/runtime/restart_after_delay_api_unittest.cc @@ -166,7 +166,7 @@ class RestartAfterDelayApiTest : public ApiUnitTest { } private: - std::string RunFunctionGetError(UIThreadExtensionFunction* function, + std::string RunFunctionGetError(ExtensionFunction* function, const Extension* extension, const std::string& args) { scoped_refptr<ExtensionFunction> function_owner(function); diff --git a/chromium/extensions/browser/api/runtime/runtime_api.cc b/chromium/extensions/browser/api/runtime/runtime_api.cc index 78ba73c769f..d8f9d8ff0df 100644 --- a/chromium/extensions/browser/api/runtime/runtime_api.cc +++ b/chromium/extensions/browser/api/runtime/runtime_api.cc @@ -27,7 +27,6 @@ #include "extensions/browser/events/lazy_event_dispatch_util.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_prefs.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extension_util.h" #include "extensions/browser/extensions_browser_client.h" @@ -179,8 +178,6 @@ void BrowserContextKeyedAPIFactory<RuntimeAPI>::DeclareFactoryDependencies() { RuntimeAPI::RuntimeAPI(content::BrowserContext* context) : browser_context_(context), - extension_registry_observer_(this), - process_manager_observer_(this), minimum_duration_between_restarts_(base::TimeDelta::FromHours( kMinDurationBetweenSuccessiveRestartsHours)), dispatch_chrome_updated_event_(false), diff --git a/chromium/extensions/browser/api/runtime/runtime_api.h b/chromium/extensions/browser/api/runtime/runtime_api.h index eba7145dc2f..bb06f6211e3 100644 --- a/chromium/extensions/browser/api/runtime/runtime_api.h +++ b/chromium/extensions/browser/api/runtime/runtime_api.h @@ -16,6 +16,7 @@ #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/events/lazy_event_dispatch_util.h" #include "extensions/browser/extension_function.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/browser/lazy_context_task_queue.h" #include "extensions/browser/process_manager.h" @@ -149,9 +150,9 @@ class RuntimeAPI : public BrowserContextKeyedAPI, // Listen to extension notifications. ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; ScopedObserver<ProcessManager, ProcessManagerObserver> - process_manager_observer_; + process_manager_observer_{this}; // The ID of the first extension to call the restartAfterDelay API. Any other // extensions to call this API after that will fail. @@ -217,7 +218,7 @@ class RuntimeEventRouter { UninstallReason reason); }; -class RuntimeGetBackgroundPageFunction : public UIThreadExtensionFunction { +class RuntimeGetBackgroundPageFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("runtime.getBackgroundPage", RUNTIME_GETBACKGROUNDPAGE) @@ -231,7 +232,7 @@ class RuntimeGetBackgroundPageFunction : public UIThreadExtensionFunction { std::unique_ptr<LazyContextTaskQueue::ContextInfo> context_info); }; -class RuntimeOpenOptionsPageFunction : public UIThreadExtensionFunction { +class RuntimeOpenOptionsPageFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("runtime.openOptionsPage", RUNTIME_OPENOPTIONSPAGE) @@ -240,7 +241,7 @@ class RuntimeOpenOptionsPageFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class RuntimeSetUninstallURLFunction : public UIThreadExtensionFunction { +class RuntimeSetUninstallURLFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("runtime.setUninstallURL", RUNTIME_SETUNINSTALLURL) @@ -249,7 +250,7 @@ class RuntimeSetUninstallURLFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class RuntimeReloadFunction : public UIThreadExtensionFunction { +class RuntimeReloadFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("runtime.reload", RUNTIME_RELOAD) @@ -258,7 +259,7 @@ class RuntimeReloadFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class RuntimeRequestUpdateCheckFunction : public UIThreadExtensionFunction { +class RuntimeRequestUpdateCheckFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("runtime.requestUpdateCheck", RUNTIME_REQUESTUPDATECHECK) @@ -271,7 +272,7 @@ class RuntimeRequestUpdateCheckFunction : public UIThreadExtensionFunction { void CheckComplete(const RuntimeAPIDelegate::UpdateCheckResult& result); }; -class RuntimeRestartFunction : public UIThreadExtensionFunction { +class RuntimeRestartFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("runtime.restart", RUNTIME_RESTART) @@ -280,7 +281,7 @@ class RuntimeRestartFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class RuntimeRestartAfterDelayFunction : public UIThreadExtensionFunction { +class RuntimeRestartAfterDelayFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("runtime.restartAfterDelay", RUNTIME_RESTARTAFTERDELAY) @@ -290,7 +291,7 @@ class RuntimeRestartAfterDelayFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class RuntimeGetPlatformInfoFunction : public UIThreadExtensionFunction { +class RuntimeGetPlatformInfoFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("runtime.getPlatformInfo", RUNTIME_GETPLATFORMINFO) @@ -299,8 +300,7 @@ class RuntimeGetPlatformInfoFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class RuntimeGetPackageDirectoryEntryFunction - : public UIThreadExtensionFunction { +class RuntimeGetPackageDirectoryEntryFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("runtime.getPackageDirectoryEntry", RUNTIME_GETPACKAGEDIRECTORYENTRY) diff --git a/chromium/extensions/browser/api/serial/serial_api.cc b/chromium/extensions/browser/api/serial/serial_api.cc index bc329234795..1526c333b03 100644 --- a/chromium/extensions/browser/api/serial/serial_api.cc +++ b/chromium/extensions/browser/api/serial/serial_api.cc @@ -473,7 +473,7 @@ void SerialSetControlSignalsFunction::AsyncWorkStart() { } connection->SetControlSignals( - params_->signals, + device::mojom::SerialHostControlSignals::From(params_->signals), base::BindOnce(&SerialSetControlSignalsFunction::OnSetControlSignals, this)); } @@ -503,7 +503,11 @@ void SerialSetBreakFunction::AsyncWorkStart() { AsyncWorkCompleted(); return; } - connection->SetBreak( + auto signals = device::mojom::SerialHostControlSignals::New(); + signals->has_brk = true; + signals->brk = true; + connection->SetControlSignals( + std::move(signals), base::BindOnce(&SerialSetBreakFunction::OnSetBreak, this)); } @@ -532,7 +536,11 @@ void SerialClearBreakFunction::AsyncWorkStart() { AsyncWorkCompleted(); return; } - connection->ClearBreak( + auto signals = device::mojom::SerialHostControlSignals::New(); + signals->has_brk = true; + signals->brk = false; + connection->SetControlSignals( + std::move(signals), base::BindOnce(&SerialClearBreakFunction::OnClearBreak, this)); } diff --git a/chromium/extensions/browser/api/serial/serial_api.h b/chromium/extensions/browser/api/serial/serial_api.h index d38d7ee70cc..1551c60f721 100644 --- a/chromium/extensions/browser/api/serial/serial_api.h +++ b/chromium/extensions/browser/api/serial/serial_api.h @@ -39,7 +39,7 @@ class SerialAsyncApiFunction : public AsyncApiFunction { ApiResourceManager<SerialConnection>* manager_; }; -class SerialGetDevicesFunction : public UIThreadExtensionFunction { +class SerialGetDevicesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("serial.getDevices", SERIAL_GETDEVICES) diff --git a/chromium/extensions/browser/api/serial/serial_apitest.cc b/chromium/extensions/browser/api/serial/serial_apitest.cc index 91f49aeb0d6..1990b235f20 100644 --- a/chromium/extensions/browser/api/serial/serial_apitest.cc +++ b/chromium/extensions/browser/api/serial/serial_apitest.cc @@ -138,12 +138,6 @@ class FakeSerialPort : public device::mojom::SerialPort { info->cts_flow_control = options_.cts_flow_control; std::move(callback).Run(std::move(info)); } - void SetBreak(SetBreakCallback callback) override { - std::move(callback).Run(true); - } - void ClearBreak(ClearBreakCallback callback) override { - std::move(callback).Run(true); - } void Close(CloseCallback callback) override { in_stream_watcher_.Cancel(); diff --git a/chromium/extensions/browser/api/serial/serial_connection.cc b/chromium/extensions/browser/api/serial/serial_connection.cc index 3dfd12581d9..9233060e955 100644 --- a/chromium/extensions/browser/api/serial/serial_connection.cc +++ b/chromium/extensions/browser/api/serial/serial_connection.cc @@ -525,23 +525,11 @@ void SerialConnection::GetControlSignals( } void SerialConnection::SetControlSignals( - const api::serial::HostControlSignals& control_signals, + device::mojom::SerialHostControlSignalsPtr signals, SetControlSignalsCompleteCallback callback) { DCHECK(serial_port_); serial_port_->SetControlSignals( - device::mojom::SerialHostControlSignals::From(control_signals), - mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(callback), false)); -} - -void SerialConnection::SetBreak(SetBreakCompleteCallback callback) { - DCHECK(serial_port_); - serial_port_->SetBreak( - mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(callback), false)); -} - -void SerialConnection::ClearBreak(ClearBreakCompleteCallback callback) { - DCHECK(serial_port_); - serial_port_->ClearBreak( + std::move(signals), mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(callback), false)); } diff --git a/chromium/extensions/browser/api/serial/serial_connection.h b/chromium/extensions/browser/api/serial/serial_connection.h index 3a2f172f9f7..a2565bdbf31 100644 --- a/chromium/extensions/browser/api/serial/serial_connection.h +++ b/chromium/extensions/browser/api/serial/serial_connection.h @@ -64,11 +64,6 @@ class SerialConnection : public ApiResource, using SetControlSignalsCompleteCallback = device::mojom::SerialPort::SetControlSignalsCallback; - using SetBreakCompleteCallback = device::mojom::SerialPort::SetBreakCallback; - - using ClearBreakCompleteCallback = - device::mojom::SerialPort::ClearBreakCallback; - SerialConnection(const std::string& owner_extension_id, device::mojom::SerialPortPtrInfo serial_port_info); ~SerialConnection() override; @@ -129,20 +124,11 @@ class SerialConnection : public ApiResource, // Returns nullptr if we failed in getting values. void GetControlSignals(GetControlSignalsCompleteCallback callback) const; - // Sets one or more control signals (DTR and/or RTS). Returns result success - // or not via |callback|. Unininitialized flags in the HostControlSignals - // structure are left unchanged. - void SetControlSignals(const api::serial::HostControlSignals& control_signals, + // Sets one or more control signals (DTR, RTS, Break). Returns result success + // or not via |callback|. + void SetControlSignals(device::mojom::SerialHostControlSignalsPtr signals, SetControlSignalsCompleteCallback callback); - // Suspend character transmission. Known as setting/sending 'Break' signal. - // Returns result success or not via |callback|. - void SetBreak(SetBreakCompleteCallback callback); - - // Restore character transmission. Known as clear/stop sending 'Break' signal. - // Returns result success or not via |callback|. - void ClearBreak(ClearBreakCompleteCallback callback); - // Initiates an asynchronous close of the device. void Close(base::OnceClosure callback); diff --git a/chromium/extensions/browser/api/serial/serial_port_manager.cc b/chromium/extensions/browser/api/serial/serial_port_manager.cc index 1432626b149..d69c55ae8c5 100644 --- a/chromium/extensions/browser/api/serial/serial_port_manager.cc +++ b/chromium/extensions/browser/api/serial/serial_port_manager.cc @@ -145,10 +145,9 @@ void SerialPortManager::PostEvent(const ReceiveParams& params, std::unique_ptr<extensions::Event> event) { DCHECK_CURRENTLY_ON(params.thread_id); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&DispatchEvent, params.browser_context_id, - params.extension_id, std::move(event))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&DispatchEvent, params.browser_context_id, + params.extension_id, std::move(event))); } // static diff --git a/chromium/extensions/browser/api/socket/app_firewall_hole_manager.cc b/chromium/extensions/browser/api/socket/app_firewall_hole_manager.cc index bf6a2c48256..2498ba53004 100644 --- a/chromium/extensions/browser/api/socket/app_firewall_hole_manager.cc +++ b/chromium/extensions/browser/api/socket/app_firewall_hole_manager.cc @@ -80,8 +80,7 @@ AppFirewallHole::AppFirewallHole( : type_(type), port_(port), extension_id_(extension_id), - manager_(manager), - weak_factory_(this) {} + manager_(manager) {} void AppFirewallHole::SetVisible(bool app_visible) { app_visible_ = app_visible; @@ -105,7 +104,7 @@ void AppFirewallHole::OnFirewallHoleOpened( } AppFirewallHoleManager::AppFirewallHoleManager(BrowserContext* context) - : context_(context), observer_(this), weak_factory_(this) { + : context_(context), observer_(this) { observer_.Add(AppWindowRegistry::Get(context)); } diff --git a/chromium/extensions/browser/api/socket/app_firewall_hole_manager.h b/chromium/extensions/browser/api/socket/app_firewall_hole_manager.h index 5beff081339..081005e8415 100644 --- a/chromium/extensions/browser/api/socket/app_firewall_hole_manager.h +++ b/chromium/extensions/browser/api/socket/app_firewall_hole_manager.h @@ -57,7 +57,7 @@ class AppFirewallHole { // This will hold the FirewallHole object if one is opened. std::unique_ptr<chromeos::FirewallHole> firewall_hole_; - base::WeakPtrFactory<AppFirewallHole> weak_factory_; + base::WeakPtrFactory<AppFirewallHole> weak_factory_{this}; }; // Tracks ports in the system firewall opened by an application so that they @@ -92,7 +92,7 @@ class AppFirewallHoleManager : public KeyedService, ScopedObserver<AppWindowRegistry, AppWindowRegistry::Observer> observer_; std::multimap<std::string, AppFirewallHole*> tracked_holes_; - base::WeakPtrFactory<AppFirewallHoleManager> weak_factory_; + base::WeakPtrFactory<AppFirewallHoleManager> weak_factory_{this}; }; } // namespace extensions diff --git a/chromium/extensions/browser/api/socket/mojo_data_pump_unittest.cc b/chromium/extensions/browser/api/socket/mojo_data_pump_unittest.cc index 5ee5ea9121c..1eda573165a 100644 --- a/chromium/extensions/browser/api/socket/mojo_data_pump_unittest.cc +++ b/chromium/extensions/browser/api/socket/mojo_data_pump_unittest.cc @@ -5,12 +5,12 @@ #include "extensions/browser/api/socket/mojo_data_pump.h" #include <memory> -#include <utility> #include <string> +#include <utility> #include "base/run_loop.h" #include "base/test/bind_test_util.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "mojo/public/cpp/system/data_pipe.h" #include "net/base/test_completion_callback.h" #include "testing/gtest/include/gtest/gtest.h" @@ -20,7 +20,7 @@ namespace extensions { // Tests that if |MojoDataPump::receive_stream_| is not ready, MojoDataPump will // wait and not error out. TEST(MojoDataPumpTest, ReceiveStreamNotReady) { - base::test::ScopedTaskEnvironment scoped_task_environment; + base::test::TaskEnvironment task_environment; mojo::DataPipe receive_pipe; mojo::DataPipe send_pipe; auto pump = @@ -63,7 +63,7 @@ TEST(MojoDataPumpTest, ReceiveStreamNotReady) { // Tests that if |MojoDataPump::receive_stream_| is closed, an error is // propagated. TEST(MojoDataPumpTest, ReceiveStreamClosed) { - base::test::ScopedTaskEnvironment scoped_task_environment; + base::test::TaskEnvironment task_environment; mojo::DataPipe receive_pipe; mojo::DataPipe send_pipe; auto pump = @@ -88,7 +88,7 @@ TEST(MojoDataPumpTest, ReceiveStreamClosed) { // Tests that if |MojoDataPump::send_stream_| is closed, Write() will fail. TEST(MojoDataPumpTest, SendStreamClosed) { - base::test::ScopedTaskEnvironment scoped_task_environment; + base::test::TaskEnvironment task_environment; mojo::DataPipe receive_pipe; mojo::DataPipe send_pipe; auto pump = diff --git a/chromium/extensions/browser/api/socket/socket_api.cc b/chromium/extensions/browser/api/socket/socket_api.cc index c1a68371673..25afd6917c5 100644 --- a/chromium/extensions/browser/api/socket/socket_api.cc +++ b/chromium/extensions/browser/api/socket/socket_api.cc @@ -125,7 +125,7 @@ void SocketAsyncApiFunction::OpenFirewallHole(const std::string& address, ? AppFirewallHole::PortType::TCP : AppFirewallHole::PortType::UDP; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&SocketAsyncApiFunction::OpenFirewallHoleOnUIThread, this, type, local_address.port(), socket_id)); @@ -146,10 +146,9 @@ void SocketAsyncApiFunction::OpenFirewallHoleOnUIThread( AppFirewallHoleManager::Get(browser_context()); std::unique_ptr<AppFirewallHole, BrowserThread::DeleteOnUIThread> hole( manager->Open(type, port, extension_id()).release()); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&SocketAsyncApiFunction::OnFirewallHoleOpened, this, - socket_id, std::move(hole))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&SocketAsyncApiFunction::OnFirewallHoleOpened, + this, socket_id, std::move(hole))); } void SocketAsyncApiFunction::OnFirewallHoleOpened( @@ -242,12 +241,12 @@ bool SocketCreateFunction::Prepare() { case extensions::api::socket::SOCKET_TYPE_UDP: { socket_type_ = kSocketTypeUDP; - network::mojom::UDPSocketReceiverPtr receiver_ptr; - socket_receiver_request_ = mojo::MakeRequest(&receiver_ptr); + network::mojom::UDPSocketListenerPtr listener_ptr; + socket_listener_request_ = mojo::MakeRequest(&listener_ptr); content::BrowserContext::GetDefaultStoragePartition(browser_context()) ->GetNetworkContext() ->CreateUDPSocket(mojo::MakeRequest(&socket_), - std::move(receiver_ptr)); + std::move(listener_ptr)); break; } case extensions::api::socket::SOCKET_TYPE_NONE: @@ -264,7 +263,7 @@ void SocketCreateFunction::Work() { socket = new TCPSocket(browser_context(), extension_->id()); } else if (socket_type_ == kSocketTypeUDP) { socket = - new UDPSocket(std::move(socket_), std::move(socket_receiver_request_), + new UDPSocket(std::move(socket_), std::move(socket_listener_request_), extension_->id()); } DCHECK(socket); diff --git a/chromium/extensions/browser/api/socket/socket_api.h b/chromium/extensions/browser/api/socket/socket_api.h index c37ecd11c4f..79abac3c38d 100644 --- a/chromium/extensions/browser/api/socket/socket_api.h +++ b/chromium/extensions/browser/api/socket/socket_api.h @@ -196,7 +196,7 @@ class SocketCreateFunction : public SocketAsyncApiFunction { // These two fields are only applicable if |socket_type_| is UDP. network::mojom::UDPSocketPtrInfo socket_; - network::mojom::UDPSocketReceiverRequest socket_receiver_request_; + network::mojom::UDPSocketListenerRequest socket_listener_request_; std::unique_ptr<api::socket::Create::Params> params_; SocketType socket_type_; @@ -461,14 +461,14 @@ class SocketGetInfoFunction : public SocketAsyncApiFunction { std::unique_ptr<api::socket::GetInfo::Params> params_; }; -class SocketGetNetworkListFunction : public UIThreadExtensionFunction { +class SocketGetNetworkListFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("socket.getNetworkList", SOCKET_GETNETWORKLIST) protected: ~SocketGetNetworkListFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: diff --git a/chromium/extensions/browser/api/socket/tcp_socket.cc b/chromium/extensions/browser/api/socket/tcp_socket.cc index ea16f7b9b76..e5824e3a584 100644 --- a/chromium/extensions/browser/api/socket/tcp_socket.cc +++ b/chromium/extensions/browser/api/socket/tcp_socket.cc @@ -137,12 +137,11 @@ void TCPSocket::Connect(const net::AddressList& address, base::BindOnce(&TCPSocket::OnConnectCompleteOnUIThread, task_runner_, std::move(completion_callback)); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&TCPSocket::ConnectOnUIThread, storage_partition_, - browser_context_, address, - mojo::MakeRequest(&client_socket_), - std::move(completion_callback_ui))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&TCPSocket::ConnectOnUIThread, + storage_partition_, browser_context_, address, + mojo::MakeRequest(&client_socket_), + std::move(completion_callback_ui))); } void TCPSocket::Disconnect(bool socket_destroying) { @@ -262,7 +261,7 @@ void TCPSocket::Listen(const std::string& address, base::BindOnce(&TCPSocket::OnListenCompleteOnUIThread, task_runner_, std::move(completion_callback)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&TCPSocket::ListenOnUIThread, storage_partition_, browser_context_, ip_end_point, backlog, diff --git a/chromium/extensions/browser/api/socket/udp_socket.cc b/chromium/extensions/browser/api/socket/udp_socket.cc index 7d63bee3ddc..8103ff6655e 100644 --- a/chromium/extensions/browser/api/socket/udp_socket.cc +++ b/chromium/extensions/browser/api/socket/udp_socket.cc @@ -32,14 +32,14 @@ ApiResourceManager<ResumableUDPSocket>::GetFactoryInstance() { } UDPSocket::UDPSocket(network::mojom::UDPSocketPtrInfo socket, - network::mojom::UDPSocketReceiverRequest receiver_request, + network::mojom::UDPSocketListenerRequest listener_request, const std::string& owner_extension_id) : Socket(owner_extension_id), socket_(std::move(socket)), socket_options_(network::mojom::UDPSocketOptions::New()), is_bound_(false), - receiver_binding_(this) { - receiver_binding_.Bind(std::move(receiver_request)); + listener_binding_(this) { + listener_binding_.Bind(std::move(listener_request)); } UDPSocket::~UDPSocket() { @@ -387,10 +387,10 @@ const std::vector<std::string>& UDPSocket::GetJoinedGroups() const { ResumableUDPSocket::ResumableUDPSocket( network::mojom::UDPSocketPtrInfo socket, - network::mojom::UDPSocketReceiverRequest receiver_request, + network::mojom::UDPSocketListenerRequest listener_request, const std::string& owner_extension_id) : UDPSocket(std::move(socket), - std::move(receiver_request), + std::move(listener_request), owner_extension_id), persistent_(false), buffer_size_(0), diff --git a/chromium/extensions/browser/api/socket/udp_socket.h b/chromium/extensions/browser/api/socket/udp_socket.h index ab6f9305feb..270409f5b21 100644 --- a/chromium/extensions/browser/api/socket/udp_socket.h +++ b/chromium/extensions/browser/api/socket/udp_socket.h @@ -19,10 +19,10 @@ namespace extensions { -class UDPSocket : public Socket, public network::mojom::UDPSocketReceiver { +class UDPSocket : public Socket, public network::mojom::UDPSocketListener { public: UDPSocket(network::mojom::UDPSocketPtrInfo socket, - network::mojom::UDPSocketReceiverRequest receiver_request, + network::mojom::UDPSocketListenerRequest listener_request, const std::string& owner_extension_id); ~UDPSocket() override; @@ -71,7 +71,7 @@ class UDPSocket : public Socket, public network::mojom::UDPSocketReceiver { bool IsConnectedOrBound() const; - // network::mojom::UDPSocketReceiver implementation. + // network::mojom::UDPSocketListener implementation. void OnReceived(int32_t result, const base::Optional<net::IPEndPoint>& src_addr, base::Optional<base::span<const uint8_t>> data) override; @@ -100,7 +100,7 @@ class UDPSocket : public Socket, public network::mojom::UDPSocketReceiver { network::mojom::UDPSocketOptionsPtr socket_options_; bool is_bound_; - mojo::Binding<network::mojom::UDPSocketReceiver> receiver_binding_; + mojo::Binding<network::mojom::UDPSocketListener> listener_binding_; base::Optional<net::IPEndPoint> local_addr_; base::Optional<net::IPEndPoint> peer_addr_; @@ -117,7 +117,7 @@ class UDPSocket : public Socket, public network::mojom::UDPSocketReceiver { class ResumableUDPSocket : public UDPSocket { public: ResumableUDPSocket(network::mojom::UDPSocketPtrInfo socket, - network::mojom::UDPSocketReceiverRequest receiver_request, + network::mojom::UDPSocketListenerRequest listener_request, const std::string& owner_extension_id); // Overriden from ApiResource diff --git a/chromium/extensions/browser/api/sockets_tcp/tcp_socket_event_dispatcher.cc b/chromium/extensions/browser/api/sockets_tcp/tcp_socket_event_dispatcher.cc index 76fbfcb4f68..69f7e9c1be8 100644 --- a/chromium/extensions/browser/api/sockets_tcp/tcp_socket_event_dispatcher.cc +++ b/chromium/extensions/browser/api/sockets_tcp/tcp_socket_event_dispatcher.cc @@ -147,7 +147,7 @@ void TCPSocketEventDispatcher::ReadCallback( // Post a task to delay the read until the socket is available, as // calling StartReceive at this point would error with ERR_IO_PENDING. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {params.thread_id}, base::BindOnce(&TCPSocketEventDispatcher::StartRead, params)); } else if (bytes_read == net::ERR_IO_PENDING) { @@ -183,10 +183,9 @@ void TCPSocketEventDispatcher::PostEvent(const ReadParams& params, std::unique_ptr<Event> event) { DCHECK_CURRENTLY_ON(params.thread_id); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&DispatchEvent, params.browser_context_id, - params.extension_id, std::move(event))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&DispatchEvent, params.browser_context_id, + params.extension_id, std::move(event))); } // static diff --git a/chromium/extensions/browser/api/sockets_tcp_server/tcp_server_socket_event_dispatcher.cc b/chromium/extensions/browser/api/sockets_tcp_server/tcp_server_socket_event_dispatcher.cc index e28831d9b20..6edc5a75e05 100644 --- a/chromium/extensions/browser/api/sockets_tcp_server/tcp_server_socket_event_dispatcher.cc +++ b/chromium/extensions/browser/api/sockets_tcp_server/tcp_server_socket_event_dispatcher.cc @@ -154,7 +154,7 @@ void TCPServerSocketEventDispatcher::AcceptCallback( // Post a task to delay the "accept" until the socket is available, as // calling StartAccept at this point would error with ERR_IO_PENDING. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {params.thread_id}, base::BindOnce(&TCPServerSocketEventDispatcher::StartAccept, params)); } else { @@ -185,10 +185,9 @@ void TCPServerSocketEventDispatcher::PostEvent(const AcceptParams& params, std::unique_ptr<Event> event) { DCHECK_CURRENTLY_ON(params.thread_id); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&DispatchEvent, params.browser_context_id, - params.extension_id, std::move(event))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&DispatchEvent, params.browser_context_id, + params.extension_id, std::move(event))); } // static diff --git a/chromium/extensions/browser/api/sockets_udp/sockets_udp_api.cc b/chromium/extensions/browser/api/sockets_udp/sockets_udp_api.cc index 7b23e937d15..3c766fb09b2 100644 --- a/chromium/extensions/browser/api/sockets_udp/sockets_udp_api.cc +++ b/chromium/extensions/browser/api/sockets_udp/sockets_udp_api.cc @@ -96,17 +96,17 @@ bool SocketsUdpCreateFunction::Prepare() { params_ = sockets_udp::Create::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params_.get()); - network::mojom::UDPSocketReceiverPtr receiver_ptr; - socket_receiver_request_ = mojo::MakeRequest(&receiver_ptr); + network::mojom::UDPSocketListenerPtr listener_ptr; + socket_listener_request_ = mojo::MakeRequest(&listener_ptr); content::BrowserContext::GetDefaultStoragePartition(browser_context()) ->GetNetworkContext() - ->CreateUDPSocket(mojo::MakeRequest(&socket_), std::move(receiver_ptr)); + ->CreateUDPSocket(mojo::MakeRequest(&socket_), std::move(listener_ptr)); return true; } void SocketsUdpCreateFunction::Work() { ResumableUDPSocket* socket = new ResumableUDPSocket( - std::move(socket_), std::move(socket_receiver_request_), + std::move(socket_), std::move(socket_listener_request_), extension_->id()); sockets_udp::SocketProperties* properties = params_->properties.get(); diff --git a/chromium/extensions/browser/api/sockets_udp/sockets_udp_api.h b/chromium/extensions/browser/api/sockets_udp/sockets_udp_api.h index ee5ddacf29b..d9c6a2a8841 100644 --- a/chromium/extensions/browser/api/sockets_udp/sockets_udp_api.h +++ b/chromium/extensions/browser/api/sockets_udp/sockets_udp_api.h @@ -58,7 +58,7 @@ class SocketsUdpCreateFunction : public UDPSocketAsyncApiFunction { FRIEND_TEST_ALL_PREFIXES(SocketsUdpUnitTest, Create); network::mojom::UDPSocketPtrInfo socket_; - network::mojom::UDPSocketReceiverRequest socket_receiver_request_; + network::mojom::UDPSocketListenerRequest socket_listener_request_; std::unique_ptr<sockets_udp::Create::Params> params_; }; diff --git a/chromium/extensions/browser/api/sockets_udp/udp_socket_event_dispatcher.cc b/chromium/extensions/browser/api/sockets_udp/udp_socket_event_dispatcher.cc index e4c2ef3b1da..14774d2cf85 100644 --- a/chromium/extensions/browser/api/sockets_udp/udp_socket_event_dispatcher.cc +++ b/chromium/extensions/browser/api/sockets_udp/udp_socket_event_dispatcher.cc @@ -132,7 +132,7 @@ void UDPSocketEventDispatcher::ReceiveCallback( // Post a task to delay the read until the socket is available, as // calling StartReceive at this point would error with ERR_IO_PENDING. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {params.thread_id}, base::BindOnce(&UDPSocketEventDispatcher::StartReceive, params)); } else if (bytes_read == net::ERR_IO_PENDING) { @@ -171,10 +171,9 @@ void UDPSocketEventDispatcher::PostEvent(const ReceiveParams& params, std::unique_ptr<Event> event) { DCHECK_CURRENTLY_ON(params.thread_id); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&DispatchEvent, params.browser_context_id, - params.extension_id, std::move(event))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&DispatchEvent, params.browser_context_id, + params.extension_id, std::move(event))); } /*static*/ diff --git a/chromium/extensions/browser/api/storage/storage_api.cc b/chromium/extensions/browser/api/storage/storage_api.cc index 11b396b8967..adad9208a08 100644 --- a/chromium/extensions/browser/api/storage/storage_api.cc +++ b/chromium/extensions/browser/api/storage/storage_api.cc @@ -77,7 +77,7 @@ ExtensionFunction::ResponseAction SettingsFunction::Run() { void SettingsFunction::AsyncRunWithStorage(ValueStore* storage) { ResponseValue response = RunWithStorage(storage); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&SettingsFunction::Respond, this, std::move(response))); } diff --git a/chromium/extensions/browser/api/storage/storage_api.h b/chromium/extensions/browser/api/storage/storage_api.h index e6b532c135b..b30de8f9ab8 100644 --- a/chromium/extensions/browser/api/storage/storage_api.h +++ b/chromium/extensions/browser/api/storage/storage_api.h @@ -17,7 +17,7 @@ namespace extensions { // Superclass of all settings functions. -class SettingsFunction : public UIThreadExtensionFunction { +class SettingsFunction : public ExtensionFunction { protected: SettingsFunction(); ~SettingsFunction() override; diff --git a/chromium/extensions/browser/api/system_cpu/system_cpu_api.h b/chromium/extensions/browser/api/system_cpu/system_cpu_api.h index 3890edc6666..849b0a6c543 100644 --- a/chromium/extensions/browser/api/system_cpu/system_cpu_api.h +++ b/chromium/extensions/browser/api/system_cpu/system_cpu_api.h @@ -9,7 +9,7 @@ namespace extensions { -class SystemCpuGetInfoFunction : public UIThreadExtensionFunction { +class SystemCpuGetInfoFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("system.cpu.getInfo", SYSTEM_CPU_GETINFO) SystemCpuGetInfoFunction(); @@ -17,7 +17,7 @@ class SystemCpuGetInfoFunction : public UIThreadExtensionFunction { private: ~SystemCpuGetInfoFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; void OnGetCpuInfoCompleted(bool success); diff --git a/chromium/extensions/browser/api/system_display/display_info_provider.cc b/chromium/extensions/browser/api/system_display/display_info_provider.cc index 00abc24e598..d57b0d6a312 100644 --- a/chromium/extensions/browser/api/system_display/display_info_provider.cc +++ b/chromium/extensions/browser/api/system_display/display_info_provider.cc @@ -188,10 +188,16 @@ void DisplayInfoProvider::SetMirrorMode( } void DisplayInfoProvider::DispatchOnDisplayChangedEvent() { + // This function will dispatch the OnDisplayChangedEvent to both on-the-record + // and off-the-record profiles. This allows extensions running in incognito + // to be notified mirroring is enabled / disabled, which allows the Virtual + // keyboard on ChromeOS to correctly disable key highlighting when typing + // passwords on the login page (crbug/824656) + constexpr bool dispatch_to_off_the_record_profiles = true; ExtensionsBrowserClient::Get()->BroadcastEventToRenderers( events::SYSTEM_DISPLAY_ON_DISPLAY_CHANGED, extensions::api::system_display::OnDisplayChanged::kEventName, - std::make_unique<base::ListValue>()); + std::make_unique<base::ListValue>(), dispatch_to_off_the_record_profiles); } void DisplayInfoProvider::UpdateDisplayUnitInfoForPlatform( diff --git a/chromium/extensions/browser/api/system_display/system_display_api.cc b/chromium/extensions/browser/api/system_display/system_display_api.cc index 9857cb4dd21..982906b6426 100644 --- a/chromium/extensions/browser/api/system_display/system_display_api.cc +++ b/chromium/extensions/browser/api/system_display/system_display_api.cc @@ -148,7 +148,7 @@ bool OverscanTracker::RemoveObserverImpl(content::WebContents* web_contents) { return observers_.empty(); } -bool HasAutotestPrivate(const UIThreadExtensionFunction& function) { +bool HasAutotestPrivate(const ExtensionFunction& function) { return function.extension() && function.extension()->permissions_data()->HasAPIPermission( APIPermission::kAutoTestPrivate); @@ -156,7 +156,7 @@ bool HasAutotestPrivate(const UIThreadExtensionFunction& function) { #if defined(OS_CHROMEOS) // |edid| is available only to Chrome OS kiosk mode applications. -bool ShouldRestrictEdidInformation(const UIThreadExtensionFunction& function) { +bool ShouldRestrictEdidInformation(const ExtensionFunction& function) { if (function.extension()) { return !(HasAutotestPrivate(function) || KioskModeInfo::IsKioskEnabled(function.extension())); @@ -169,7 +169,7 @@ bool ShouldRestrictEdidInformation(const UIThreadExtensionFunction& function) { } // namespace bool SystemDisplayCrOSRestrictedFunction::PreRunValidation(std::string* error) { - if (!UIThreadExtensionFunction::PreRunValidation(error)) + if (!ExtensionFunction::PreRunValidation(error)) return false; #if !defined(OS_CHROMEOS) diff --git a/chromium/extensions/browser/api/system_display/system_display_api.h b/chromium/extensions/browser/api/system_display/system_display_api.h index ccbea3473dc..3949aaa0cf5 100644 --- a/chromium/extensions/browser/api/system_display/system_display_api.h +++ b/chromium/extensions/browser/api/system_display/system_display_api.h @@ -12,7 +12,7 @@ namespace extensions { -class SystemDisplayCrOSRestrictedFunction : public UIThreadExtensionFunction { +class SystemDisplayCrOSRestrictedFunction : public ExtensionFunction { public: static const char kCrosOnlyError[]; static const char kKioskOnlyError[]; @@ -26,9 +26,9 @@ class SystemDisplayCrOSRestrictedFunction : public UIThreadExtensionFunction { virtual bool ShouldRestrictToKioskAndWebUI(); }; -// This function inherits from UIThreadExtensionFunction because, unlike the +// This function inherits from ExtensionFunction because, unlike the // rest of this API, it's available on all platforms. -class SystemDisplayGetInfoFunction : public UIThreadExtensionFunction { +class SystemDisplayGetInfoFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("system.display.getInfo", SYSTEM_DISPLAY_GETINFO) diff --git a/chromium/extensions/browser/api/system_info/system_info_api.cc b/chromium/extensions/browser/api/system_info/system_info_api.cc index 59acbc36588..02e4ea2d490 100644 --- a/chromium/extensions/browser/api/system_info/system_info_api.cc +++ b/chromium/extensions/browser/api/system_info/system_info_api.cc @@ -177,7 +177,7 @@ void SystemInfoEventRouter::DispatchEvent( const std::string& event_name, std::unique_ptr<base::ListValue> args) { ExtensionsBrowserClient::Get()->BroadcastEventToRenderers( - histogram_value, event_name, std::move(args)); + histogram_value, event_name, std::move(args), false); } void SystemInfoEventRouter::AddEventListenerInternal( diff --git a/chromium/extensions/browser/api/system_info/system_info_provider.cc b/chromium/extensions/browser/api/system_info/system_info_provider.cc index 4d00a4978fa..7184b367ca7 100644 --- a/chromium/extensions/browser/api/system_info/system_info_provider.cc +++ b/chromium/extensions/browser/api/system_info/system_info_provider.cc @@ -14,8 +14,8 @@ namespace extensions { SystemInfoProvider::SystemInfoProvider() : is_waiting_for_completion_(false), - task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), + task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), /* default priority, */ base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) {} diff --git a/chromium/extensions/browser/api/system_memory/system_memory_api.h b/chromium/extensions/browser/api/system_memory/system_memory_api.h index 00866d983f6..fe307cab7e7 100644 --- a/chromium/extensions/browser/api/system_memory/system_memory_api.h +++ b/chromium/extensions/browser/api/system_memory/system_memory_api.h @@ -10,7 +10,7 @@ namespace extensions { -class SystemMemoryGetInfoFunction : public UIThreadExtensionFunction { +class SystemMemoryGetInfoFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("system.memory.getInfo", SYSTEM_MEMORY_GETINFO) SystemMemoryGetInfoFunction(); @@ -18,7 +18,7 @@ class SystemMemoryGetInfoFunction : public UIThreadExtensionFunction { private: ~SystemMemoryGetInfoFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; void OnGetMemoryInfoCompleted(bool success); diff --git a/chromium/extensions/browser/api/system_network/system_network_api.h b/chromium/extensions/browser/api/system_network/system_network_api.h index 15ddabb677f..22d030e7afb 100644 --- a/chromium/extensions/browser/api/system_network/system_network_api.h +++ b/chromium/extensions/browser/api/system_network/system_network_api.h @@ -14,8 +14,7 @@ namespace extensions { namespace api { -class SystemNetworkGetNetworkInterfacesFunction - : public UIThreadExtensionFunction { +class SystemNetworkGetNetworkInterfacesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("system.network.getNetworkInterfaces", SYSTEM_NETWORK_GETNETWORKINTERFACES) diff --git a/chromium/extensions/browser/api/system_power_source/system_power_source_api.h b/chromium/extensions/browser/api/system_power_source/system_power_source_api.h index 523e9a00254..0ea34745788 100644 --- a/chromium/extensions/browser/api/system_power_source/system_power_source_api.h +++ b/chromium/extensions/browser/api/system_power_source/system_power_source_api.h @@ -41,8 +41,7 @@ class SystemPowerSourceAPI : public BrowserContextKeyedAPI, DISALLOW_COPY_AND_ASSIGN(SystemPowerSourceAPI); }; -class SystemPowerSourceGetPowerSourceInfoFunction - : public UIThreadExtensionFunction { +class SystemPowerSourceGetPowerSourceInfoFunction : public ExtensionFunction { public: SystemPowerSourceGetPowerSourceInfoFunction(); @@ -58,8 +57,7 @@ class SystemPowerSourceGetPowerSourceInfoFunction DISALLOW_COPY_AND_ASSIGN(SystemPowerSourceGetPowerSourceInfoFunction); }; -class SystemPowerSourceRequestStatusUpdateFunction - : public UIThreadExtensionFunction { +class SystemPowerSourceRequestStatusUpdateFunction : public ExtensionFunction { public: SystemPowerSourceRequestStatusUpdateFunction(); diff --git a/chromium/extensions/browser/api/system_storage/system_storage_api.cc b/chromium/extensions/browser/api/system_storage/system_storage_api.cc index e57952f426f..3fac6bb2637 100644 --- a/chromium/extensions/browser/api/system_storage/system_storage_api.cc +++ b/chromium/extensions/browser/api/system_storage/system_storage_api.cc @@ -98,8 +98,9 @@ void SystemStorageEjectDeviceFunction::HandleResponse( SystemStorageGetAvailableCapacityFunction:: SystemStorageGetAvailableCapacityFunction() - : query_runner_(base::CreateSequencedTaskRunnerWithTraits( - base::TaskTraits(base::TaskPriority::BEST_EFFORT, + : query_runner_(base::CreateSequencedTaskRunner( + base::TaskTraits(base::ThreadPool(), + base::TaskPriority::BEST_EFFORT, base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN))) {} diff --git a/chromium/extensions/browser/api/system_storage/system_storage_api.h b/chromium/extensions/browser/api/system_storage/system_storage_api.h index 23d5dde2a86..fa0338aa532 100644 --- a/chromium/extensions/browser/api/system_storage/system_storage_api.h +++ b/chromium/extensions/browser/api/system_storage/system_storage_api.h @@ -14,7 +14,7 @@ namespace extensions { // Implementation of the systeminfo.storage.get API. It is an asynchronous // call relative to browser UI thread. -class SystemStorageGetInfoFunction : public UIThreadExtensionFunction { +class SystemStorageGetInfoFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("system.storage.getInfo", SYSTEM_STORAGE_GETINFO) SystemStorageGetInfoFunction(); @@ -28,7 +28,7 @@ class SystemStorageGetInfoFunction : public UIThreadExtensionFunction { void OnGetStorageInfoCompleted(bool success); }; -class SystemStorageEjectDeviceFunction : public UIThreadExtensionFunction { +class SystemStorageEjectDeviceFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("system.storage.ejectDevice", SYSTEM_STORAGE_EJECTDEVICE) @@ -46,8 +46,7 @@ class SystemStorageEjectDeviceFunction : public UIThreadExtensionFunction { void HandleResponse(storage_monitor::StorageMonitor::EjectStatus status); }; -class SystemStorageGetAvailableCapacityFunction - : public UIThreadExtensionFunction { +class SystemStorageGetAvailableCapacityFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("system.storage.getAvailableCapacity", SYSTEM_STORAGE_GETAVAILABLECAPACITY) diff --git a/chromium/extensions/browser/api/test/test_api.cc b/chromium/extensions/browser/api/test/test_api.cc index de1295a7f7e..01e9d167057 100644 --- a/chromium/extensions/browser/api/test/test_api.cc +++ b/chromium/extensions/browser/api/test/test_api.cc @@ -38,7 +38,7 @@ namespace WaitForRoundTrip = api::test::WaitForRoundTrip; TestExtensionFunction::~TestExtensionFunction() {} bool TestExtensionFunction::PreRunValidation(std::string* error) { - if (!UIThreadExtensionFunction::PreRunValidation(error)) + if (!ExtensionFunction::PreRunValidation(error)) return false; if (!base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType)) { *error = kNotTestProcessError; diff --git a/chromium/extensions/browser/api/test/test_api.h b/chromium/extensions/browser/api/test/test_api.h index 3fc88cd0576..c8ba5b82db2 100644 --- a/chromium/extensions/browser/api/test/test_api.h +++ b/chromium/extensions/browser/api/test/test_api.h @@ -20,7 +20,7 @@ namespace extensions { // A function that is only available in tests. // Prior to running, checks that we are in a testing process. -class TestExtensionFunction : public UIThreadExtensionFunction { +class TestExtensionFunction : public ExtensionFunction { protected: ~TestExtensionFunction() override; @@ -61,7 +61,7 @@ class TestLogFunction : public TestExtensionFunction { ResponseAction Run() override; }; -class TestSendMessageFunction : public UIThreadExtensionFunction { +class TestSendMessageFunction : public ExtensionFunction { public: TestSendMessageFunction(); DECLARE_EXTENSION_FUNCTION("test.sendMessage", UNKNOWN) diff --git a/chromium/extensions/browser/api/usb/usb_api.cc b/chromium/extensions/browser/api/usb/usb_api.cc index 07780624e34..160d1048c35 100644 --- a/chromium/extensions/browser/api/usb/usb_api.cc +++ b/chromium/extensions/browser/api/usb/usb_api.cc @@ -633,13 +633,13 @@ void UsbFindDevicesFunction::OnGetDevicesComplete( APIPermission::kUsbDevice, param.get())) { barrier_.Run(); } else { - device::mojom::UsbDevicePtr device_ptr; + mojo::Remote<device::mojom::UsbDevice> device; usb_device_manager()->GetDevice(device_info->guid, - mojo::MakeRequest(&device_ptr)); - auto* device = device_ptr.get(); - device->Open(mojo::WrapCallbackWithDropHandler( + device.BindNewPipeAndPassReceiver()); + auto* device_raw = device.get(); + device_raw->Open(mojo::WrapCallbackWithDropHandler( base::BindOnce(&UsbFindDevicesFunction::OnDeviceOpened, this, - device_info->guid, std::move(device_ptr)), + device_info->guid, std::move(device)), base::BindOnce(&UsbFindDevicesFunction::OnDisconnect, this))); } } @@ -647,13 +647,13 @@ void UsbFindDevicesFunction::OnGetDevicesComplete( void UsbFindDevicesFunction::OnDeviceOpened( const std::string& guid, - device::mojom::UsbDevicePtr device_ptr, + mojo::Remote<device::mojom::UsbDevice> device, device::mojom::UsbOpenDeviceError error) { - if (error == device::mojom::UsbOpenDeviceError::OK && device_ptr) { + if (error == device::mojom::UsbOpenDeviceError::OK && device) { ApiResourceManager<UsbDeviceResource>* manager = ApiResourceManager<UsbDeviceResource>::Get(browser_context()); UsbDeviceResource* resource = - new UsbDeviceResource(extension_id(), guid, std::move(device_ptr)); + new UsbDeviceResource(extension_id(), guid, std::move(device)); result_->Append(PopulateConnectionHandle(manager->Add(resource), vendor_id_, product_id_)); } @@ -859,21 +859,22 @@ ExtensionFunction::ResponseAction UsbOpenDeviceFunction::Run() { return RespondNow(Error(kErrorNoDevice)); } - device::mojom::UsbDevicePtr device_ptr; - device_manager->GetDevice(device_info->guid, mojo::MakeRequest(&device_ptr)); - auto* device = device_ptr.get(); - device->Open(mojo::WrapCallbackWithDropHandler( + mojo::Remote<device::mojom::UsbDevice> device; + device_manager->GetDevice(device_info->guid, + device.BindNewPipeAndPassReceiver()); + auto* device_raw = device.get(); + device_raw->Open(mojo::WrapCallbackWithDropHandler( base::BindOnce(&UsbOpenDeviceFunction::OnDeviceOpened, this, - device_info->guid, std::move(device_ptr)), + device_info->guid, std::move(device)), base::BindOnce(&UsbOpenDeviceFunction::OnDisconnect, this))); return RespondLater(); } void UsbOpenDeviceFunction::OnDeviceOpened( std::string guid, - device::mojom::UsbDevicePtr device_ptr, + mojo::Remote<device::mojom::UsbDevice> device, device::mojom::UsbOpenDeviceError error) { - if (error != device::mojom::UsbOpenDeviceError::OK || !device_ptr) { + if (error != device::mojom::UsbOpenDeviceError::OK || !device) { Respond(Error(kErrorOpen)); return; } @@ -886,7 +887,7 @@ void UsbOpenDeviceFunction::OnDeviceOpened( usb_device_manager()->GetDeviceInfo(guid); DCHECK(device_info); UsbDeviceResource* resource = new UsbDeviceResource( - extension_id(), device_info->guid, std::move(device_ptr)); + extension_id(), device_info->guid, std::move(device)); Respond(OneArgument(PopulateConnectionHandle(manager->Add(resource), device_info->vendor_id, device_info->product_id))); diff --git a/chromium/extensions/browser/api/usb/usb_api.h b/chromium/extensions/browser/api/usb/usb_api.h index d73c3f973c7..9c3eed7a7c3 100644 --- a/chromium/extensions/browser/api/usb/usb_api.h +++ b/chromium/extensions/browser/api/usb/usb_api.h @@ -18,6 +18,7 @@ #include "extensions/browser/api/usb/usb_device_manager.h" #include "extensions/browser/extension_function.h" #include "extensions/common/api/usb.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/usb_device.mojom.h" namespace extensions { @@ -27,7 +28,7 @@ class DevicePermissionsPrompt; class DevicePermissionsManager; class UsbDeviceResource; -class UsbExtensionFunction : public UIThreadExtensionFunction { +class UsbExtensionFunction : public ExtensionFunction { protected: UsbExtensionFunction(); ~UsbExtensionFunction() override; @@ -103,7 +104,7 @@ class UsbFindDevicesFunction : public UsbExtensionFunction { void OnGetDevicesComplete( std::vector<device::mojom::UsbDeviceInfoPtr> devices); void OnDeviceOpened(const std::string& guid, - device::mojom::UsbDevicePtr device_ptr, + mojo::Remote<device::mojom::UsbDevice> device_ptr, device::mojom::UsbOpenDeviceError error); void OpenComplete(); void OnDisconnect(); @@ -171,7 +172,7 @@ class UsbGetConfigurationsFunction : public UsbPermissionCheckingFunction { DISALLOW_COPY_AND_ASSIGN(UsbGetConfigurationsFunction); }; -class UsbRequestAccessFunction : public UIThreadExtensionFunction { +class UsbRequestAccessFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("usb.requestAccess", USB_REQUESTACCESS) @@ -199,7 +200,7 @@ class UsbOpenDeviceFunction : public UsbPermissionCheckingFunction { ResponseAction Run() override; void OnDeviceOpened(std::string guid, - device::mojom::UsbDevicePtr device_ptr, + mojo::Remote<device::mojom::UsbDevice> device, device::mojom::UsbOpenDeviceError error); void OnDisconnect(); diff --git a/chromium/extensions/browser/api/usb/usb_apitest.cc b/chromium/extensions/browser/api/usb/usb_apitest.cc index 1a62273747a..0872b2d7ffa 100644 --- a/chromium/extensions/browser/api/usb/usb_apitest.cc +++ b/chromium/extensions/browser/api/usb/usb_apitest.cc @@ -14,6 +14,7 @@ #include "extensions/shell/browser/shell_extensions_api_client.h" #include "extensions/shell/test/shell_apitest.h" #include "extensions/test/extension_test_message_listener.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "services/device/public/cpp/test/fake_usb_device_info.h" #include "services/device/public/cpp/test/fake_usb_device_manager.h" #include "services/device/public/cpp/test/mock_usb_mojo_device.h" @@ -123,10 +124,10 @@ class UsbApiTest : public ShellApiTest { ShellApiTest::SetUpOnMainThread(); // Set fake USB device manager for extensions::UsbDeviceManager. - device::mojom::UsbDeviceManagerPtr usb_manager_ptr; - fake_usb_manager_.AddBinding(mojo::MakeRequest(&usb_manager_ptr)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> usb_manager; + fake_usb_manager_.AddReceiver(usb_manager.InitWithNewPipeAndPassReceiver()); UsbDeviceManager::Get(browser_context()) - ->SetDeviceManagerForTesting(std::move(usb_manager_ptr)); + ->SetDeviceManagerForTesting(std::move(usb_manager)); base::RunLoop().RunUntilIdle(); std::vector<device::mojom::UsbConfigurationInfoPtr> configs; diff --git a/chromium/extensions/browser/api/usb/usb_device_manager.cc b/chromium/extensions/browser/api/usb/usb_device_manager.cc index ada9e58ebc0..b60037db5b3 100644 --- a/chromium/extensions/browser/api/usb/usb_device_manager.cc +++ b/chromium/extensions/browser/api/usb/usb_device_manager.cc @@ -17,6 +17,7 @@ #include "extensions/common/api/usb.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/common/permissions/usb_device_permission.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "services/device/public/mojom/constants.mojom.h" #include "services/device/public/mojom/usb_enumeration_options.mojom.h" #include "services/service_manager/public/cpp/connector.h" @@ -33,6 +34,7 @@ namespace { // regarding this device. bool WillDispatchDeviceEvent(const device::mojom::UsbDeviceInfo& device_info, content::BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { @@ -81,7 +83,7 @@ void UsbDeviceManager::Observer::OnDeviceRemoved( void UsbDeviceManager::Observer::OnDeviceManagerConnectionError() {} UsbDeviceManager::UsbDeviceManager(content::BrowserContext* browser_context) - : browser_context_(browser_context), client_binding_(this) { + : browser_context_(browser_context) { EventRouter* event_router = EventRouter::Get(browser_context_); if (event_router) { event_router->RegisterObserver(this, usb::OnDeviceAdded::kEventName); @@ -153,10 +155,10 @@ void UsbDeviceManager::GetDevices( void UsbDeviceManager::GetDevice( const std::string& guid, - device::mojom::UsbDeviceRequest device_request) { + mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver) { EnsureConnectionWithDeviceManager(); - device_manager_->GetDevice(guid, std::move(device_request), - /*device_client=*/nullptr); + device_manager_->GetDevice(guid, std::move(device_receiver), + /*device_client=*/mojo::NullRemote()); } const device::mojom::UsbDeviceInfo* UsbDeviceManager::GetDeviceInfo( @@ -190,19 +192,20 @@ void UsbDeviceManager::EnsureConnectionWithDeviceManager() { if (device_manager_) return; - // Request UsbDeviceManagerPtr from DeviceService. + // Receive mojo::Remote<UsbDeviceManager> from DeviceService. DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - content::GetSystemConnector()->BindInterface( - device::mojom::kServiceName, mojo::MakeRequest(&device_manager_)); + content::GetSystemConnector()->Connect( + device::mojom::kServiceName, + device_manager_.BindNewPipeAndPassReceiver()); SetUpDeviceManagerConnection(); } void UsbDeviceManager::SetDeviceManagerForTesting( - device::mojom::UsbDeviceManagerPtr fake_device_manager) { + mojo::PendingRemote<device::mojom::UsbDeviceManager> fake_device_manager) { DCHECK(!device_manager_); DCHECK(fake_device_manager); - device_manager_ = std::move(fake_device_manager); + device_manager_.Bind(std::move(fake_device_manager)); SetUpDeviceManagerConnection(); } @@ -264,17 +267,16 @@ void UsbDeviceManager::OnDeviceRemoved( void UsbDeviceManager::SetUpDeviceManagerConnection() { DCHECK(device_manager_); - device_manager_.set_connection_error_handler( + device_manager_.set_disconnect_handler( base::BindOnce(&UsbDeviceManager::OnDeviceManagerConnectionError, base::Unretained(this))); // Listen for added/removed device events. - DCHECK(!client_binding_); - device::mojom::UsbDeviceManagerClientAssociatedPtrInfo client; - client_binding_.Bind(mojo::MakeRequest(&client)); + DCHECK(!client_receiver_.is_bound()); device_manager_->EnumerateDevicesAndSetClient( - std::move(client), base::BindOnce(&UsbDeviceManager::InitDeviceList, - weak_factory_.GetWeakPtr())); + client_receiver_.BindNewEndpointAndPassRemote(), + base::BindOnce(&UsbDeviceManager::InitDeviceList, + weak_factory_.GetWeakPtr())); } void UsbDeviceManager::InitDeviceList( @@ -299,7 +301,7 @@ void UsbDeviceManager::InitDeviceList( void UsbDeviceManager::OnDeviceManagerConnectionError() { device_manager_.reset(); - client_binding_.Close(); + client_receiver_.reset(); devices_.clear(); is_initialized_ = false; diff --git a/chromium/extensions/browser/api/usb/usb_device_manager.h b/chromium/extensions/browser/api/usb/usb_device_manager.h index 5e15444fbee..ec07ecea78b 100644 --- a/chromium/extensions/browser/api/usb/usb_device_manager.h +++ b/chromium/extensions/browser/api/usb/usb_device_manager.h @@ -14,7 +14,10 @@ #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h" #include "extensions/common/api/usb.h" -#include "mojo/public/cpp/bindings/associated_binding.h" +#include "mojo/public/cpp/bindings/associated_receiver.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/usb_manager.mojom.h" #include "services/device/public/mojom/usb_manager_client.mojom.h" @@ -58,8 +61,9 @@ class UsbDeviceManager : public BrowserContextKeyedAPI, // Forward UsbDeviceManager methods. void GetDevices(device::mojom::UsbDeviceManager::GetDevicesCallback callback); - void GetDevice(const std::string& guid, - device::mojom::UsbDeviceRequest device_request); + void GetDevice( + const std::string& guid, + mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver); const device::mojom::UsbDeviceInfo* GetDeviceInfo(const std::string& guid); bool UpdateActiveConfig(const std::string& guid, uint8_t config_value); @@ -73,7 +77,7 @@ class UsbDeviceManager : public BrowserContextKeyedAPI, void EnsureConnectionWithDeviceManager(); void SetDeviceManagerForTesting( - device::mojom::UsbDeviceManagerPtr fake_device_manager); + mojo::PendingRemote<device::mojom::UsbDeviceManager> fake_device_manager); private: friend class BrowserContextKeyedAPIFactory<UsbDeviceManager>; @@ -116,9 +120,9 @@ class UsbDeviceManager : public BrowserContextKeyedAPI, std::map<std::string, device::mojom::UsbDeviceInfoPtr> devices_; // Connection to |device_manager_instance_|. - device::mojom::UsbDeviceManagerPtr device_manager_; - mojo::AssociatedBinding<device::mojom::UsbDeviceManagerClient> - client_binding_; + mojo::Remote<device::mojom::UsbDeviceManager> device_manager_; + mojo::AssociatedReceiver<device::mojom::UsbDeviceManagerClient> + client_receiver_{this}; base::ObserverList<Observer> observer_list_; diff --git a/chromium/extensions/browser/api/usb/usb_device_resource.cc b/chromium/extensions/browser/api/usb/usb_device_resource.cc index fd6d6227f63..936bc16b872 100644 --- a/chromium/extensions/browser/api/usb/usb_device_resource.cc +++ b/chromium/extensions/browser/api/usb/usb_device_resource.cc @@ -31,11 +31,12 @@ ApiResourceManager<UsbDeviceResource>::GetFactoryInstance() { return g_factory.Pointer(); } -UsbDeviceResource::UsbDeviceResource(const std::string& owner_extension_id, - const std::string& guid, - device::mojom::UsbDevicePtr device) +UsbDeviceResource::UsbDeviceResource( + const std::string& owner_extension_id, + const std::string& guid, + mojo::Remote<device::mojom::UsbDevice> device) : ApiResource(owner_extension_id), guid_(guid), device_(std::move(device)) { - device_.set_connection_error_handler(base::BindOnce( + device_.set_disconnect_handler(base::BindOnce( &UsbDeviceResource::OnConnectionError, base::Unretained(this))); } diff --git a/chromium/extensions/browser/api/usb/usb_device_resource.h b/chromium/extensions/browser/api/usb/usb_device_resource.h index e9b9036b9a4..81f0d931163 100644 --- a/chromium/extensions/browser/api/usb/usb_device_resource.h +++ b/chromium/extensions/browser/api/usb/usb_device_resource.h @@ -13,12 +13,13 @@ #include "content/public/browser/browser_thread.h" #include "extensions/browser/api/api_resource.h" #include "extensions/browser/api/api_resource_manager.h" +#include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/usb_device.mojom.h" namespace extensions { // A UsbDeviceResource is an ApiResource wrapper for a -// device::mojom::UsbDevicePtr and its guid. +// mojo::Remote<device::mojom::UsbDevice> and its guid. class UsbDeviceResource : public ApiResource { public: static const content::BrowserThread::ID kThreadId = @@ -26,10 +27,12 @@ class UsbDeviceResource : public ApiResource { UsbDeviceResource(const std::string& owner_extension_id, const std::string& guid, - device::mojom::UsbDevicePtr device); + mojo::Remote<device::mojom::UsbDevice> device); ~UsbDeviceResource() override; - device::mojom::UsbDevice* device() const { return device_.get(); } + device::mojom::UsbDevice* device() const { + return device_ ? device_.get() : nullptr; + } const std::string& guid() const { return guid_; } bool IsPersistent() const override; @@ -41,7 +44,7 @@ class UsbDeviceResource : public ApiResource { void OnConnectionError(); const std::string guid_; - device::mojom::UsbDevicePtr device_; + mojo::Remote<device::mojom::UsbDevice> device_; DISALLOW_COPY_AND_ASSIGN(UsbDeviceResource); }; diff --git a/chromium/extensions/browser/api/virtual_keyboard/virtual_keyboard_api.h b/chromium/extensions/browser/api/virtual_keyboard/virtual_keyboard_api.h index 74e3ee0cd75..3bff3ac8aec 100644 --- a/chromium/extensions/browser/api/virtual_keyboard/virtual_keyboard_api.h +++ b/chromium/extensions/browser/api/virtual_keyboard/virtual_keyboard_api.h @@ -11,8 +11,7 @@ namespace extensions { -class VirtualKeyboardRestrictFeaturesFunction - : public UIThreadExtensionFunction { +class VirtualKeyboardRestrictFeaturesFunction : public ExtensionFunction { public: VirtualKeyboardRestrictFeaturesFunction(); @@ -21,7 +20,7 @@ class VirtualKeyboardRestrictFeaturesFunction protected: ~VirtualKeyboardRestrictFeaturesFunction() override = default; - // UIThreadExtensionFunction override: + // ExtensionFunction override: ResponseAction Run() override; private: diff --git a/chromium/extensions/browser/api/virtual_keyboard_private/virtual_keyboard_private_api.cc b/chromium/extensions/browser/api/virtual_keyboard_private/virtual_keyboard_private_api.cc index efa172aeda1..9366a568995 100644 --- a/chromium/extensions/browser/api/virtual_keyboard_private/virtual_keyboard_private_api.cc +++ b/chromium/extensions/browser/api/virtual_keyboard_private/virtual_keyboard_private_api.cc @@ -38,7 +38,7 @@ gfx::Rect KeyboardBoundsToRect(const keyboard::Bounds& bounds) { } // namespace bool VirtualKeyboardPrivateFunction::PreRunValidation(std::string* error) { - if (!UIThreadExtensionFunction::PreRunValidation(error)) + if (!ExtensionFunction::PreRunValidation(error)) return false; VirtualKeyboardAPI* api = diff --git a/chromium/extensions/browser/api/virtual_keyboard_private/virtual_keyboard_private_api.h b/chromium/extensions/browser/api/virtual_keyboard_private/virtual_keyboard_private_api.h index 5227d3be66b..d9eda1b28f4 100644 --- a/chromium/extensions/browser/api/virtual_keyboard_private/virtual_keyboard_private_api.h +++ b/chromium/extensions/browser/api/virtual_keyboard_private/virtual_keyboard_private_api.h @@ -21,7 +21,7 @@ namespace extensions { class VirtualKeyboardDelegate; -class VirtualKeyboardPrivateFunction : public UIThreadExtensionFunction { +class VirtualKeyboardPrivateFunction : public ExtensionFunction { public: bool PreRunValidation(std::string* error) override; diff --git a/chromium/extensions/browser/api/vpn_provider/vpn_provider_api.h b/chromium/extensions/browser/api/vpn_provider/vpn_provider_api.h index 0a3b4bf2e9a..3f73331a72c 100644 --- a/chromium/extensions/browser/api/vpn_provider/vpn_provider_api.h +++ b/chromium/extensions/browser/api/vpn_provider/vpn_provider_api.h @@ -11,7 +11,7 @@ namespace extensions { -class VpnThreadExtensionFunction : public UIThreadExtensionFunction { +class VpnThreadExtensionFunction : public ExtensionFunction { public: void SignalCallCompletionSuccess(); void SignalCallCompletionSuccessWithId(const std::string& configuration_id); diff --git a/chromium/extensions/browser/api/vpn_provider/vpn_service.cc b/chromium/extensions/browser/api/vpn_provider/vpn_service.cc index d8689238c4b..c7aadc6df41 100644 --- a/chromium/extensions/browser/api/vpn_provider/vpn_service.cc +++ b/chromium/extensions/browser/api/vpn_provider/vpn_service.cc @@ -229,8 +229,7 @@ VpnService::VpnService( network_configuration_handler_(network_configuration_handler), network_profile_handler_(network_profile_handler), network_state_handler_(network_state_handler), - active_configuration_(nullptr), - weak_factory_(this) { + active_configuration_(nullptr) { extension_registry_->AddObserver(this); network_state_handler_->AddObserver(this, FROM_HERE); network_configuration_handler_->AddObserver(this); diff --git a/chromium/extensions/browser/api/vpn_provider/vpn_service.h b/chromium/extensions/browser/api/vpn_provider/vpn_service.h index 833d692a55a..965636cf155 100644 --- a/chromium/extensions/browser/api/vpn_provider/vpn_service.h +++ b/chromium/extensions/browser/api/vpn_provider/vpn_service.h @@ -251,7 +251,7 @@ class VpnService : public KeyedService, // Service path does not own the VpnConfigurations. StringToConfigurationMap service_path_to_configuration_map_; - base::WeakPtrFactory<VpnService> weak_factory_; + base::WeakPtrFactory<VpnService> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VpnService); }; diff --git a/chromium/extensions/browser/api/web_request/web_request_api.cc b/chromium/extensions/browser/api/web_request/web_request_api.cc index b83d047e7fd..b6928889604 100644 --- a/chromium/extensions/browser/api/web_request/web_request_api.cc +++ b/chromium/extensions/browser/api/web_request/web_request_api.cc @@ -30,7 +30,6 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" -#include "content/public/browser/resource_request_info.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/child_process_host.h" @@ -69,6 +68,7 @@ #include "extensions/browser/warning_service.h" #include "extensions/browser/warning_set.h" #include "extensions/common/api/web_request.h" +#include "extensions/common/constants.h" #include "extensions/common/error_utils.h" #include "extensions/common/event_filtering_info.h" #include "extensions/common/extension.h" @@ -89,12 +89,13 @@ #endif // defined(OS_CHROMEOS) using content::BrowserThread; -using content::ResourceRequestInfo; using extension_web_request_api_helpers::ExtraInfoSpec; namespace activity_log = activity_log_web_request_constants; namespace helpers = extension_web_request_api_helpers; namespace keys = extension_web_request_api_constants; +using URLLoaderFactoryType = + content::ContentBrowserClient::URLLoaderFactoryType; namespace extensions { @@ -273,7 +274,6 @@ void SendOnMessageEventOnUI( return; std::unique_ptr<base::ListValue> event_args(new base::ListValue); - event_details->DetermineFrameDataOnUI(); event_args->Append(event_details->GetAndClearDict()); EventRouter* event_router = EventRouter::Get(browser_context); @@ -479,6 +479,19 @@ scoped_refptr<const net::HttpResponseHeaders> FilterResponseHeaders( return *headers_filtered ? result : response_headers; } +// Helper to record a matched DNR action in RulesetManager's ActionTracker. +void OnDNRActionMatched(content::BrowserContext* browser_context, + const WebRequestInfo& request) { + DCHECK(request.dnr_action.has_value()); + + declarative_net_request::ActionTracker& action_tracker = + declarative_net_request::RulesMonitorService::Get(browser_context) + ->ruleset_manager() + ->action_tracker(); + action_tracker.OnRuleMatched(request.dnr_action->extension_ids, + request.frame_data.tab_id); +} + } // namespace void WebRequestAPI::Proxy::HandleAuthRequest( @@ -640,10 +653,10 @@ bool WebRequestAPI::MaybeProxyURLLoaderFactory( content::BrowserContext* browser_context, content::RenderFrameHost* frame, int render_process_id, - bool is_navigation, - bool is_download, + URLLoaderFactoryType type, mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver, - network::mojom::TrustedURLLoaderHeaderClientPtrInfo* header_client) { + mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* + header_client) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!MayHaveProxies()) { bool skip_proxy = true; @@ -674,6 +687,7 @@ bool WebRequestAPI::MaybeProxyURLLoaderFactory( *factory_receiver = mojo::MakeRequest(&target_factory_info); std::unique_ptr<ExtensionNavigationUIData> navigation_ui_data; + const bool is_navigation = (type == URLLoaderFactoryType::kNavigation); if (is_navigation) { DCHECK(frame); int tab_id; @@ -684,9 +698,10 @@ bool WebRequestAPI::MaybeProxyURLLoaderFactory( std::make_unique<ExtensionNavigationUIData>(frame, tab_id, window_id); } - network::mojom::TrustedURLLoaderHeaderClientRequest header_client_request; + mojo::PendingReceiver<network::mojom::TrustedURLLoaderHeaderClient> + header_client_receiver; if (header_client) - header_client_request = mojo::MakeRequest(header_client); + header_client_receiver = header_client->InitWithNewPipeAndPassReceiver(); // NOTE: This request may be proxied on behalf of an incognito frame, but // |this| will always be bound to a regular profile (see @@ -696,13 +711,10 @@ bool WebRequestAPI::MaybeProxyURLLoaderFactory( ExtensionsBrowserClient::Get()->GetOriginalContext(browser_context) == browser_context_)); WebRequestProxyingURLLoaderFactory::StartProxying( - browser_context, - // Match the behavior of the WebRequestInfo constructor - // which takes a net::URLRequest*. - is_navigation ? -1 : render_process_id, is_download, + browser_context, is_navigation ? -1 : render_process_id, request_id_generator_, std::move(navigation_ui_data), std::move(proxied_receiver), std::move(target_factory_info), - std::move(header_client_request), proxies_.get()); + std::move(header_client_receiver), proxies_.get(), type); return true; } @@ -738,7 +750,8 @@ void WebRequestAPI::ProxyWebSocket( const GURL& url, const GURL& site_for_cookies, const base::Optional<std::string>& user_agent, - network::mojom::WebSocketHandshakeClientPtr handshake_client) { + mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> + handshake_client) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(MayHaveProxies()); @@ -748,7 +761,7 @@ void WebRequestAPI::ProxyWebSocket( WebRequestProxyingWebSocket::StartProxying( std::move(factory), url, site_for_cookies, user_agent, - handshake_client.PassInterface(), has_extra_headers, + std::move(handshake_client), has_extra_headers, frame->GetProcess()->GetID(), frame->GetRoutingID(), request_id_generator_, frame->GetLastCommittedOrigin(), frame->GetProcess()->GetBrowserContext(), proxies_.get()); @@ -1016,12 +1029,15 @@ int ExtensionWebRequestEventRouter::OnBeforeRequest( case Action::Type::NONE: break; case Action::Type::BLOCK: + OnDNRActionMatched(browser_context, *request); return net::ERR_BLOCKED_BY_CLIENT; case Action::Type::COLLAPSE: + OnDNRActionMatched(browser_context, *request); *should_collapse_initiator = true; return net::ERR_BLOCKED_BY_CLIENT; case Action::Type::REDIRECT: DCHECK(action.redirect_url); + OnDNRActionMatched(browser_context, *request); *new_url = action.redirect_url.value(); return net::OK; case Action::Type::REMOVE_HEADERS: @@ -1094,6 +1110,11 @@ int ExtensionWebRequestEventRouter::OnBeforeSendHeaders( } while (headers->HasHeader(header)); } + // TODO(crbug.com/991420): This does not properly associate which headers are + // removed by which extensions. + if (!removed_headers.empty()) + OnDNRActionMatched(browser_context, *request); + bool initialize_blocked_requests = false; initialize_blocked_requests |= @@ -1187,6 +1208,10 @@ int ExtensionWebRequestEventRouter::OnHeadersReceived( // |override_response_headers| don't point to the same object. *override_response_headers = base::MakeRefCounted<net::HttpResponseHeaders>( filtered_response_headers->raw_headers()); + + // TODO(crbug.com/991420): This does not properly associate which headers + // are removed by which extensions. + OnDNRActionMatched(browser_context, *request); } bool initialize_blocked_requests = false; @@ -1460,12 +1485,6 @@ bool ExtensionWebRequestEventRouter::DispatchEvent( } } - // TODO(http://crbug.com/980774): Investigate if this is necessary. - if (!request->frame_data) { - request->frame_data = ExtensionApiFrameIdMap::Get()->GetFrameData( - request->render_process_id, request->frame_id); - } - event_details->SetFrameData(request->frame_data.value()); DispatchEventToListeners(browser_context, std::move(listeners_to_dispatch), std::move(event_details)); @@ -1882,10 +1901,10 @@ void ExtensionWebRequestEventRouter::GetMatchingListenersImpl( // Check if the tab id and window id match, if they were set in the // listener params. - if ((listener->filter.tab_id != -1 && request->frame_data && - request->frame_data->tab_id != listener->filter.tab_id) || - (listener->filter.window_id != -1 && request->frame_data && - request->frame_data->window_id != listener->filter.window_id)) { + if ((listener->filter.tab_id != -1 && + request->frame_data.tab_id != listener->filter.tab_id) || + (listener->filter.window_id != -1 && + request->frame_data.window_id != listener->filter.window_id)) { continue; } @@ -1898,9 +1917,7 @@ void ExtensionWebRequestEventRouter::GetMatchingListenersImpl( PermissionsData::PageAccess access = WebRequestPermissions::CanExtensionAccessURL( PermissionHelper::Get(browser_context), listener->id.extension_id, - request->url, - request->frame_data ? request->frame_data->tab_id : -1, - crosses_incognito, + request->url, request->frame_data.tab_id, crosses_incognito, WebRequestPermissions:: REQUIRE_HOST_PERMISSION_FOR_URL_AND_INITIATOR, request->initiator, request->type); diff --git a/chromium/extensions/browser/api/web_request/web_request_api.h b/chromium/extensions/browser/api/web_request/web_request_api.h index a8ff7188323..5dbf1c9a3d3 100644 --- a/chromium/extensions/browser/api/web_request/web_request_api.h +++ b/chromium/extensions/browser/api/web_request/web_request_api.h @@ -190,10 +190,10 @@ class WebRequestAPI : public BrowserContextKeyedAPI, content::BrowserContext* browser_context, content::RenderFrameHost* frame, int render_process_id, - bool is_navigation, - bool is_download, + content::ContentBrowserClient::URLLoaderFactoryType type, mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver, - network::mojom::TrustedURLLoaderHeaderClientPtrInfo* header_client); + mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* + header_client); // Any request which requires authentication to complete will be bounced // through this method. @@ -216,7 +216,8 @@ class WebRequestAPI : public BrowserContextKeyedAPI, const GURL& url, const GURL& site_for_cookies, const base::Optional<std::string>& user_agent, - network::mojom::WebSocketHandshakeClientPtr handshake_client); + mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> + handshake_client); void ForceProxyForTesting(); @@ -750,7 +751,7 @@ class ExtensionWebRequestEventRouter { DISALLOW_COPY_AND_ASSIGN(ExtensionWebRequestEventRouter); }; -class WebRequestInternalFunction : public UIThreadExtensionFunction { +class WebRequestInternalFunction : public ExtensionFunction { public: WebRequestInternalFunction() {} diff --git a/chromium/extensions/browser/api/web_request/web_request_api_helpers.cc b/chromium/extensions/browser/api/web_request/web_request_api_helpers.cc index 9d9001c56d6..e5280641dd0 100644 --- a/chromium/extensions/browser/api/web_request/web_request_api_helpers.cc +++ b/chromium/extensions/browser/api/web_request/web_request_api_helpers.cc @@ -16,6 +16,7 @@ #include "base/containers/adapters.h" #include "base/containers/flat_map.h" #include "base/macros.h" +#include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_macros.h" #include "base/no_destructor.h" #include "base/stl_util.h" @@ -36,12 +37,14 @@ #include "extensions/browser/extension_system.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/runtime_data.h" +#include "extensions/common/extension_features.h" #include "extensions/common/extension_messages.h" #include "net/cookies/cookie_util.h" #include "net/cookies/parsed_cookie.h" #include "net/http/http_request_headers.h" #include "net/http/http_util.h" #include "net/log/net_log_event_type.h" +#include "services/network/public/cpp/features.h" #include "url/url_constants.h" // TODO(battre): move all static functions into an anonymous namespace at the @@ -88,6 +91,16 @@ bool ParseCookieLifetime(const net::ParsedCookie& cookie, return false; } +std::set<std::string> GetExtraHeaderRequestHeaders() { + std::set<std::string> headers( + {"accept-encoding", "accept-language", "cookie", "referer"}); + + if (network::features::ShouldEnableOutOfBlinkCors()) + headers.insert("origin"); + + return headers; +} + void RecordRequestHeaderRemoved(RequestHeaderType type) { UMA_HISTOGRAM_ENUMERATION("Extensions.WebRequest.RequestHeaderRemoved", type); } @@ -322,7 +335,10 @@ IgnoredAction::IgnoredAction(IgnoredAction&& rhs) = default; bool ExtraInfoSpec::InitFromValue(const base::ListValue& value, int* extra_info_spec) { - *extra_info_spec = 0; + *extra_info_spec = base::FeatureList::IsEnabled( + extensions_features::kForceWebRequestExtraHeaders) + ? EXTRA_HEADERS + : 0; for (size_t i = 0; i < value.GetSize(); ++i) { std::string str; if (!value.GetString(i, &str)) @@ -1227,7 +1243,7 @@ void MergeCookiesInOnHeadersReceivedResponses( // Only create a copy if we really want to modify the response headers. if (override_response_headers->get() == NULL) { - *override_response_headers = new net::HttpResponseHeaders( + *override_response_headers = base::MakeRefCounted<net::HttpResponseHeaders>( original_response_headers->raw_headers()); } @@ -1353,8 +1369,9 @@ void MergeOnHeadersReceivedResponses( if (new_url.is_valid()) { // Only create a copy if we really want to modify the response headers. if (override_response_headers->get() == NULL) { - *override_response_headers = new net::HttpResponseHeaders( - original_response_headers->raw_headers()); + *override_response_headers = + base::MakeRefCounted<net::HttpResponseHeaders>( + original_response_headers->raw_headers()); } (*override_response_headers)->ReplaceStatusLine("HTTP/1.1 302 Found"); (*override_response_headers)->RemoveHeader("location"); @@ -1442,8 +1459,8 @@ void ClearCacheOnNavigation() { if (content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { ClearCacheOnNavigationOnUI(); } else { - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ClearCacheOnNavigationOnUI)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ClearCacheOnNavigationOnUI)); } } @@ -1464,12 +1481,8 @@ std::unique_ptr<base::DictionaryValue> CreateHeaderDictionary( } bool ShouldHideRequestHeader(int extra_info_spec, const std::string& name) { - static const std::set<std::string> kRequestHeaders{ - "accept-encoding", - "accept-language", - "cookie", - "referer", - }; + static const std::set<std::string> kRequestHeaders = + GetExtraHeaderRequestHeaders(); return !(extra_info_spec & ExtraInfoSpec::EXTRA_HEADERS) && kRequestHeaders.find(base::ToLowerASCII(name)) != kRequestHeaders.end(); diff --git a/chromium/extensions/browser/api/web_request/web_request_event_details.cc b/chromium/extensions/browser/api/web_request/web_request_event_details.cc index 36683336036..3518af0e545 100644 --- a/chromium/extensions/browser/api/web_request/web_request_event_details.cc +++ b/chromium/extensions/browser/api/web_request/web_request_event_details.cc @@ -12,7 +12,6 @@ #include "base/strings/string_number_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" -#include "content/public/browser/resource_request_info.h" #include "content/public/common/child_process_host.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/api/web_request/upload_data_presenter.h" @@ -58,6 +57,9 @@ WebRequestEventDetails::WebRequestEventDetails(const WebRequestInfo& request, dict_.SetString(keys::kTypeKey, WebRequestResourceTypeToString(request.web_request_type)); dict_.SetString(keys::kUrlKey, request.url.spec()); + dict_.SetInteger(keys::kTabIdKey, request.frame_data.tab_id); + dict_.SetInteger(keys::kFrameIdKey, request.frame_data.frame_id); + dict_.SetInteger(keys::kParentFrameIdKey, request.frame_data.parent_frame_id); initiator_ = request.initiator; render_process_id_ = request.render_process_id; render_frame_id_ = request.frame_id; @@ -132,21 +134,6 @@ void WebRequestEventDetails::SetResponseSource(const WebRequestInfo& request) { dict_.SetString(keys::kIpKey, request.response_ip); } -void WebRequestEventDetails::SetFrameData( - const ExtensionApiFrameIdMap::FrameData& frame_data) { - dict_.SetInteger(keys::kTabIdKey, frame_data.tab_id); - dict_.SetInteger(keys::kFrameIdKey, frame_data.frame_id); - dict_.SetInteger(keys::kParentFrameIdKey, frame_data.parent_frame_id); -} - -void WebRequestEventDetails::DetermineFrameDataOnUI() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - ExtensionApiFrameIdMap::FrameData frame_data = - ExtensionApiFrameIdMap::Get()->GetFrameData(render_process_id_, - render_frame_id_); - SetFrameData(frame_data); -} - std::unique_ptr<base::DictionaryValue> WebRequestEventDetails::GetFilteredDict( int extra_info_spec, PermissionHelper* permission_helper, diff --git a/chromium/extensions/browser/api/web_request/web_request_event_details.h b/chromium/extensions/browser/api/web_request/web_request_event_details.h index bac180eedf1..2bbd918a38f 100644 --- a/chromium/extensions/browser/api/web_request/web_request_event_details.h +++ b/chromium/extensions/browser/api/web_request/web_request_event_details.h @@ -95,19 +95,6 @@ class WebRequestEventDetails { dict_.SetString(key, value); } - // Sets the following keys using the value provided. - // - tabId - // - frameId - // - parentFrameId - void SetFrameData(const ExtensionApiFrameIdMap::FrameData& frame_data); - - // Sets the following keys using information from constructor. - // - tabId - // - frameId - // - parentFrameId - // This must be called from the UI thread. - void DetermineFrameDataOnUI(); - // Create an event dictionary that contains all required keys, and also the // extra keys as specified by the |extra_info_spec| filter. If the listener // this event will be dispatched to doesn't have permission for the initiator diff --git a/chromium/extensions/browser/api/web_request/web_request_info.cc b/chromium/extensions/browser/api/web_request/web_request_info.cc index f2af091a3b0..3e84b22dd07 100644 --- a/chromium/extensions/browser/api/web_request/web_request_info.cc +++ b/chromium/extensions/browser/api/web_request/web_request_info.cc @@ -12,7 +12,6 @@ #include "base/stl_util.h" #include "base/values.h" #include "content/public/browser/render_frame_host.h" -#include "content/public/browser/resource_request_info.h" #include "content/public/browser/websocket_handshake_request_info.h" #include "extensions/browser/api/web_request/upload_data_presenter.h" #include "extensions/browser/api/web_request/web_request_api_constants.h" @@ -162,7 +161,8 @@ WebRequestInfoInitParams::WebRequestInfoInitParams( int32_t routing_id, const network::ResourceRequest& request, bool is_download, - bool is_async) + bool is_async, + bool is_service_worker_script) : id(request_id), url(request.url), site_for_cookies(request.site_for_cookies), @@ -174,13 +174,14 @@ WebRequestInfoInitParams::WebRequestInfoInitParams( initiator(request.request_initiator), type(static_cast<content::ResourceType>(request.resource_type)), is_async(is_async), - extra_request_headers(request.headers) { + extra_request_headers(request.headers), + is_service_worker_script(is_service_worker_script) { if (url.SchemeIsWSOrWSS()) web_request_type = WebRequestResourceType::WEB_SOCKET; else if (is_download) web_request_type = WebRequestResourceType::OTHER; else - web_request_type = ToWebRequestResourceType(type.value()); + web_request_type = ToWebRequestResourceType(type); InitializeWebViewAndFrameData(navigation_ui_data.get()); @@ -237,7 +238,8 @@ WebRequestInfo::WebRequestInfo(WebRequestInfoInitParams params) is_web_view(params.is_web_view), web_view_instance_id(params.web_view_instance_id), web_view_rules_registry_id(params.web_view_rules_registry_id), - web_view_embedder_process_id(params.web_view_embedder_process_id) {} + web_view_embedder_process_id(params.web_view_embedder_process_id), + is_service_worker_script(params.is_service_worker_script) {} WebRequestInfo::~WebRequestInfo() = default; diff --git a/chromium/extensions/browser/api/web_request/web_request_info.h b/chromium/extensions/browser/api/web_request/web_request_info.h index 7688e9b3a36..ac265b03ae3 100644 --- a/chromium/extensions/browser/api/web_request/web_request_info.h +++ b/chromium/extensions/browser/api/web_request/web_request_info.h @@ -49,7 +49,8 @@ struct WebRequestInfoInitParams { int32_t routing_id, const network::ResourceRequest& request, bool is_download, - bool is_async); + bool is_async, + bool is_service_worker_script); ~WebRequestInfoInitParams(); @@ -62,7 +63,7 @@ struct WebRequestInfoInitParams { std::string method; bool is_navigation_request = false; base::Optional<url::Origin> initiator; - base::Optional<content::ResourceType> type; + content::ResourceType type = content::ResourceType::kSubResource; WebRequestResourceType web_request_type = WebRequestResourceType::OTHER; bool is_async = false; net::HttpRequestHeaders extra_request_headers; @@ -71,7 +72,8 @@ struct WebRequestInfoInitParams { int web_view_instance_id = -1; int web_view_rules_registry_id = -1; int web_view_embedder_process_id = -1; - base::Optional<ExtensionApiFrameIdMap::FrameData> frame_data; + ExtensionApiFrameIdMap::FrameData frame_data; + bool is_service_worker_script = false; private: void InitializeWebViewAndFrameData( @@ -120,14 +122,11 @@ struct WebRequestInfo { const base::Optional<url::Origin> initiator; // Extension API frame data corresponding to details of the frame which - // initiate this request. May be null for renderer-initiated requests where - // some frame details are not known at WebRequestInfo construction time. - // Mutable since this is lazily computed. - mutable base::Optional<ExtensionApiFrameIdMap::FrameData> frame_data; + // initiate this request. + ExtensionApiFrameIdMap::FrameData frame_data; - // The type of the request (e.g. main frame, subresource, XHR, etc). May have - // no value if the request did not originate from a ResourceDispatcher. - const base::Optional<content::ResourceType> type; + // The type of the request (e.g. main frame, subresource, XHR, etc). + const content::ResourceType type; // A partially mirrored copy of |type| which is slightly less granular and // which also identifies WebSocket requests separately from other types. @@ -172,6 +171,8 @@ struct WebRequestInfo { mutable base::Optional<declarative_net_request::RulesetManager::Action> dnr_action; + const bool is_service_worker_script; + private: DISALLOW_COPY_AND_ASSIGN(WebRequestInfo); }; diff --git a/chromium/extensions/browser/api/web_request/web_request_info_unittest.cc b/chromium/extensions/browser/api/web_request/web_request_info_unittest.cc index 22c9305ef36..1cafa254aa0 100644 --- a/chromium/extensions/browser/api/web_request/web_request_info_unittest.cc +++ b/chromium/extensions/browser/api/web_request/web_request_info_unittest.cc @@ -6,7 +6,7 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/web_request/web_request_api_constants.h" #include "extensions/browser/extension_navigation_ui_data.h" #include "services/network/public/cpp/resource_request_body.h" @@ -20,7 +20,7 @@ constexpr base::FilePath::CharType kFilePath[] = FILE_PATH_LITERAL("some_path"); } TEST(WebRequestInfoTest, CreateRequestBodyDataFromFile) { - content::TestBrowserThreadBundle test_bundle; + content::BrowserTaskEnvironment task_environment_; network::ResourceRequest request; request.method = "POST"; @@ -28,8 +28,8 @@ TEST(WebRequestInfoTest, CreateRequestBodyDataFromFile) { request.request_body->AppendFileRange(base::FilePath(kFilePath), 0, std::numeric_limits<uint64_t>::max(), base::Time()); - WebRequestInfo info( - WebRequestInfoInitParams(0, 0, 0, nullptr, 0, request, false, false)); + WebRequestInfo info(WebRequestInfoInitParams(0, 0, 0, nullptr, 0, request, + false, false, false)); ASSERT_TRUE(info.request_body_data); auto* value = info.request_body_data->FindKey( extension_web_request_api_constants::kRequestBodyRawKey); diff --git a/chromium/extensions/browser/api/web_request/web_request_permissions.cc b/chromium/extensions/browser/api/web_request/web_request_permissions.cc index 5611c8004b5..e675476537f 100644 --- a/chromium/extensions/browser/api/web_request/web_request_permissions.cc +++ b/chromium/extensions/browser/api/web_request/web_request_permissions.cc @@ -10,7 +10,6 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "content/public/browser/child_process_security_policy.h" -#include "content/public/browser/resource_request_info.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/api/web_request/permission_helper.h" #include "extensions/browser/api/web_request/web_request_api_constants.h" @@ -30,7 +29,6 @@ #include "chromeos/login/login_state/login_state.h" #endif // defined(OS_CHROMEOS) -using content::ResourceRequestInfo; using extensions::PermissionsData; namespace { @@ -248,6 +246,14 @@ bool WebRequestPermissions::HideRequest( bool is_request_from_browser = request.render_process_id == -1; if (is_request_from_browser) { + // Browser initiated service worker script requests (e.g., for update check) + // are not hidden. + if (request.is_service_worker_script) { + DCHECK(request.type == content::ResourceType::kServiceWorker || + request.type == content::ResourceType::kScript); + return false; + } + // Hide all non-navigation requests made by the browser. crbug.com/884932. if (!request.is_navigation_request) return true; @@ -338,7 +344,7 @@ PermissionsData::PageAccess WebRequestPermissions::CanExtensionAccessURL( bool crosses_incognito, HostPermissionsCheck host_permissions_check, const base::Optional<url::Origin>& initiator, - const base::Optional<content::ResourceType>& resource_type) { + content::ResourceType resource_type) { return CanExtensionAccessURLInternal( permission_helper, extension_id, url, tab_id, crosses_incognito, host_permissions_check, initiator, resource_type); diff --git a/chromium/extensions/browser/api/web_request/web_request_permissions.h b/chromium/extensions/browser/api/web_request/web_request_permissions.h index e8dc9926837..6b7b17246cf 100644 --- a/chromium/extensions/browser/api/web_request/web_request_permissions.h +++ b/chromium/extensions/browser/api/web_request/web_request_permissions.h @@ -56,7 +56,7 @@ class WebRequestPermissions { bool crosses_incognito, HostPermissionsCheck host_permissions_check, const base::Optional<url::Origin>& initiator, - const base::Optional<content::ResourceType>& resource_type); + content::ResourceType resource_type); static bool CanExtensionAccessInitiator( extensions::PermissionHelper* permission_helper, diff --git a/chromium/extensions/browser/api/web_request/web_request_permissions_unittest.cc b/chromium/extensions/browser/api/web_request/web_request_permissions_unittest.cc index 04e2cd26f94..9907feca7c8 100644 --- a/chromium/extensions/browser/api/web_request/web_request_permissions_unittest.cc +++ b/chromium/extensions/browser/api/web_request/web_request_permissions_unittest.cc @@ -6,7 +6,7 @@ #include "base/memory/scoped_refptr.h" #include "base/strings/stringprintf.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/extensions_api_client.h" #include "extensions/browser/api/web_request/permission_helper.h" #include "extensions/browser/api/web_request/web_request_info.h" @@ -193,6 +193,7 @@ TEST_F(ExtensionWebRequestPermissionsTest, TestHideRequestForURL) { TEST_F(ExtensionWebRequestPermissionsTest, CanExtensionAccessURLWithWithheldPermissions) { + ExtensionsAPIClient api_client; scoped_refptr<const Extension> extension = ExtensionBuilder("ext").AddPermission("<all_urls>").Build(); URLPatternSet all_urls( @@ -209,8 +210,7 @@ TEST_F(ExtensionWebRequestPermissionsTest, auto get_access = [extension, this]( const GURL& url, const base::Optional<url::Origin>& initiator, - const base::Optional<content::ResourceType>& - resource_type) { + const content::ResourceType resource_type) { constexpr int kTabId = 42; constexpr WebRequestPermissions::HostPermissionsCheck kPermissionsCheck = WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL; @@ -228,9 +228,8 @@ TEST_F(ExtensionWebRequestPermissionsTest, GURL urls[] = {example_com, chromium_org}; base::Optional<url::Origin> initiators[] = {base::nullopt, example_com_origin, chromium_org_origin}; - base::Optional<content::ResourceType> resource_types[] = { - base::nullopt, content::ResourceType::kSubResource, - content::ResourceType::kMainFrame}; + content::ResourceType resource_types[] = {content::ResourceType::kSubResource, + content::ResourceType::kMainFrame}; // With all permissions withheld, the result of any request should be // kWithheld. @@ -270,8 +269,6 @@ TEST_F(ExtensionWebRequestPermissionsTest, EXPECT_EQ(PermissionsData::PageAccess::kAllowed, get_access(example_com, chromium_org_origin, content::ResourceType::kSubResource)); - EXPECT_EQ(PermissionsData::PageAccess::kAllowed, - get_access(example_com, chromium_org_origin, base::nullopt)); EXPECT_EQ(PermissionsData::PageAccess::kWithheld, get_access(example_com, chromium_org_origin, content::ResourceType::kSubFrame)); @@ -322,8 +319,7 @@ TEST_F(ExtensionWebRequestPermissionsTest, auto get_access = [extension, this]( const GURL& url, const base::Optional<url::Origin>& initiator, - const base::Optional<content::ResourceType>& - resource_type) { + content::ResourceType resource_type) { constexpr int kTabId = 42; constexpr WebRequestPermissions::HostPermissionsCheck kPermissionsCheck = WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL_AND_INITIATOR; @@ -380,8 +376,6 @@ TEST_F(ExtensionWebRequestPermissionsTest, EXPECT_EQ(get_access(test_case.url, test_case.initiator, content::ResourceType::kSubResource), test_case.expected_access_subresource); - EXPECT_EQ(get_access(test_case.url, test_case.initiator, base::nullopt), - test_case.expected_access_subresource); EXPECT_EQ(get_access(test_case.url, test_case.initiator, content::ResourceType::kSubFrame), test_case.expected_access_navigation); diff --git a/chromium/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.cc b/chromium/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.cc index 95d47c3e070..cf7cd1bdb20 100644 --- a/chromium/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.cc +++ b/chromium/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.cc @@ -68,14 +68,12 @@ WebRequestProxyingURLLoaderFactory::InProgressRequest::InProgressRequest( int32_t routing_id, uint32_t options, const network::ResourceRequest& request, - bool is_download, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, network::mojom::URLLoaderRequest loader_request, network::mojom::URLLoaderClientPtr client) : factory_(factory), request_(request), original_initiator_(request.request_initiator), - is_download_(is_download), request_id_(request_id), network_service_request_id_(network_service_request_id), routing_id_(routing_id), @@ -87,13 +85,16 @@ WebRequestProxyingURLLoaderFactory::InProgressRequest::InProgressRequest( has_any_extra_headers_listeners_( network_service_request_id_ != 0 && ExtensionWebRequestEventRouter::GetInstance() - ->HasAnyExtraHeadersListener(factory_->browser_context_)), - header_client_binding_(this) { + ->HasAnyExtraHeadersListener(factory_->browser_context_)) { // If there is a client error, clean up the request. target_client_.set_connection_error_handler(base::BindOnce( &WebRequestProxyingURLLoaderFactory::InProgressRequest::OnRequestError, weak_factory_.GetWeakPtr(), network::URLLoaderCompletionStatus(net::ERR_ABORTED))); + proxied_loader_binding_.set_connection_error_handler(base::BindOnce( + &WebRequestProxyingURLLoaderFactory::InProgressRequest::OnRequestError, + weak_factory_.GetWeakPtr(), + network::URLLoaderCompletionStatus(net::ERR_ABORTED))); } WebRequestProxyingURLLoaderFactory::InProgressRequest::~InProgressRequest() { @@ -131,11 +132,12 @@ void WebRequestProxyingURLLoaderFactory::InProgressRequest:: request_id_, factory_->render_process_id_, request_.render_frame_id, factory_->navigation_ui_data_ ? factory_->navigation_ui_data_->DeepCopy() : nullptr, - routing_id_, request_for_info, is_download_, - !(options_ & network::mojom::kURLLoadOptionSynchronous))); + routing_id_, request_for_info, factory_->IsForDownload(), + !(options_ & network::mojom::kURLLoadOptionSynchronous), + factory_->IsForServiceWorkerScript())); current_request_uses_header_client_ = - factory_->url_loader_header_client_binding_ && + factory_->url_loader_header_client_receiver_.is_bound() && request_.url.SchemeIsHTTPOrHTTPS() && network_service_request_id_ != 0 && ExtensionWebRequestEventRouter::GetInstance() ->HasExtraHeadersListenerForRequest(factory_->browser_context_, @@ -187,8 +189,8 @@ void WebRequestProxyingURLLoaderFactory::InProgressRequest::RestartInternal() { // Pause the header client, since we want to wait until OnBeforeRequest has // finished before processing any future events. - if (header_client_binding_) - header_client_binding_.PauseIncomingMethodCallProcessing(); + if (header_client_receiver_.is_bound()) + header_client_receiver_.Pause(); return; } DCHECK_EQ(net::OK, result); @@ -232,12 +234,6 @@ void WebRequestProxyingURLLoaderFactory::InProgressRequest::FollowRedirect( RestartInternal(); } -void WebRequestProxyingURLLoaderFactory::InProgressRequest:: - ProceedWithResponse() { - if (target_loader_.is_bound()) - target_loader_->ProceedWithResponse(); -} - void WebRequestProxyingURLLoaderFactory::InProgressRequest::SetPriority( net::RequestPriority priority, int32_t intra_priority_value) { @@ -258,7 +254,7 @@ void WebRequestProxyingURLLoaderFactory::InProgressRequest:: } void WebRequestProxyingURLLoaderFactory::InProgressRequest::OnReceiveResponse( - const network::ResourceResponseHead& head) { + network::mojom::URLResponseHeadPtr head) { if (current_request_uses_header_client_) { // Use the headers we got from OnHeadersReceived as that'll contain // Set-Cookie if it existed. @@ -276,7 +272,7 @@ void WebRequestProxyingURLLoaderFactory::InProgressRequest::OnReceiveResponse( void WebRequestProxyingURLLoaderFactory::InProgressRequest::OnReceiveRedirect( const net::RedirectInfo& redirect_info, - const network::ResourceResponseHead& head) { + network::mojom::URLResponseHeadPtr head) { if (redirect_url_ != redirect_info.new_url && !IsRedirectSafe(request_.url, redirect_info.new_url)) { OnRequestError( @@ -363,9 +359,19 @@ void WebRequestProxyingURLLoaderFactory::InProgressRequest::HandleAuthRequest( auth_info, std::move(callback))); } +bool WebRequestProxyingURLLoaderFactory::IsForServiceWorkerScript() const { + return loader_factory_type_ == content::ContentBrowserClient:: + URLLoaderFactoryType::kServiceWorkerScript; +} + +bool WebRequestProxyingURLLoaderFactory::IsForDownload() const { + return loader_factory_type_ == + content::ContentBrowserClient::URLLoaderFactoryType::kDownload; +} + void WebRequestProxyingURLLoaderFactory::InProgressRequest::OnLoaderCreated( - network::mojom::TrustedHeaderClientRequest request) { - header_client_binding_.Bind(std::move(request)); + mojo::PendingReceiver<network::mojom::TrustedHeaderClient> receiver) { + header_client_receiver_.Bind(std::move(receiver)); } void WebRequestProxyingURLLoaderFactory::InProgressRequest::OnBeforeSendHeaders( @@ -409,7 +415,7 @@ void WebRequestProxyingURLLoaderFactory::InProgressRequest:: // the load with it gives unexpected results. See // https://crbug.com/882661#c72. proxied_client_binding_.Close(); - header_client_binding_.Close(); + header_client_receiver_.reset(); target_loader_.reset(); constexpr int kInternalRedirectStatusCode = 307; @@ -532,8 +538,8 @@ void WebRequestProxyingURLLoaderFactory::InProgressRequest:: if (proxied_client_binding_.is_bound()) proxied_client_binding_.ResumeIncomingMethodCallProcessing(); - if (header_client_binding_) - header_client_binding_.ResumeIncomingMethodCallProcessing(); + if (header_client_receiver_.is_bound()) + header_client_receiver_.Resume(); if (!target_loader_.is_bound() && factory_->target_factory_.is_bound()) { // No extensions have cancelled us up to this point, so it's now OK to @@ -553,7 +559,7 @@ void WebRequestProxyingURLLoaderFactory::InProgressRequest:: // From here the lifecycle of this request is driven by subsequent events on // either |proxy_loader_binding_|, |proxy_client_binding_|, or - // |header_client_binding_|. + // |header_client_receiver_|. } void WebRequestProxyingURLLoaderFactory::InProgressRequest:: @@ -733,7 +739,7 @@ void WebRequestProxyingURLLoaderFactory::InProgressRequest:: // These will get re-bound if a new request is initiated by // |FollowRedirect()|. proxied_client_binding_.Close(); - header_client_binding_.Close(); + header_client_receiver_.reset(); target_loader_.reset(); ContinueToBeforeRedirect(redirect_info, net::OK); @@ -846,20 +852,20 @@ bool WebRequestProxyingURLLoaderFactory::InProgressRequest::IsRedirectSafe( WebRequestProxyingURLLoaderFactory::WebRequestProxyingURLLoaderFactory( content::BrowserContext* browser_context, int render_process_id, - bool is_download, scoped_refptr<WebRequestAPI::RequestIDGenerator> request_id_generator, std::unique_ptr<ExtensionNavigationUIData> navigation_ui_data, network::mojom::URLLoaderFactoryRequest loader_request, network::mojom::URLLoaderFactoryPtrInfo target_factory_info, - network::mojom::TrustedURLLoaderHeaderClientRequest header_client_request, - WebRequestAPI::ProxySet* proxies) + mojo::PendingReceiver<network::mojom::TrustedURLLoaderHeaderClient> + header_client_receiver, + WebRequestAPI::ProxySet* proxies, + content::ContentBrowserClient::URLLoaderFactoryType loader_factory_type) : browser_context_(browser_context), render_process_id_(render_process_id), - is_download_(is_download), request_id_generator_(std::move(request_id_generator)), navigation_ui_data_(std::move(navigation_ui_data)), - url_loader_header_client_binding_(this), - proxies_(proxies) { + proxies_(proxies), + loader_factory_type_(loader_factory_type) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // base::Unretained is safe here because the callback will be canceled when // |shutdown_notifier_| is destroyed, and |proxies_| owns this. @@ -878,27 +884,28 @@ WebRequestProxyingURLLoaderFactory::WebRequestProxyingURLLoaderFactory( &WebRequestProxyingURLLoaderFactory::OnProxyBindingError, base::Unretained(this))); - if (header_client_request) - url_loader_header_client_binding_.Bind(std::move(header_client_request)); + if (header_client_receiver) + url_loader_header_client_receiver_.Bind(std::move(header_client_receiver)); } void WebRequestProxyingURLLoaderFactory::StartProxying( content::BrowserContext* browser_context, int render_process_id, - bool is_download, scoped_refptr<WebRequestAPI::RequestIDGenerator> request_id_generator, std::unique_ptr<ExtensionNavigationUIData> navigation_ui_data, network::mojom::URLLoaderFactoryRequest loader_request, network::mojom::URLLoaderFactoryPtrInfo target_factory_info, - network::mojom::TrustedURLLoaderHeaderClientRequest header_client_request, - WebRequestAPI::ProxySet* proxies) { + mojo::PendingReceiver<network::mojom::TrustedURLLoaderHeaderClient> + header_client_receiver, + WebRequestAPI::ProxySet* proxies, + content::ContentBrowserClient::URLLoaderFactoryType loader_factory_type) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto proxy = std::make_unique<WebRequestProxyingURLLoaderFactory>( - browser_context, render_process_id, is_download, - std::move(request_id_generator), std::move(navigation_ui_data), - std::move(loader_request), std::move(target_factory_info), - std::move(header_client_request), proxies); + browser_context, render_process_id, std::move(request_id_generator), + std::move(navigation_ui_data), std::move(loader_request), + std::move(target_factory_info), std::move(header_client_receiver), + proxies, loader_factory_type); proxies->AddProxy(std::move(proxy)); } @@ -913,8 +920,10 @@ void WebRequestProxyingURLLoaderFactory::CreateLoaderAndStart( const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - // Make sure we are not proxying a browser initiated non-navigation request. - DCHECK(render_process_id_ != -1 || navigation_ui_data_); + // Make sure we are not proxying a browser initiated non-navigation request + // except for loading service worker scripts. + DCHECK(render_process_id_ != -1 || navigation_ui_data_ || + IsForServiceWorkerScript()); // The request ID doesn't really matter. It just needs to be unique // per-BrowserContext so extensions can make sense of it. Note that @@ -933,10 +942,10 @@ void WebRequestProxyingURLLoaderFactory::CreateLoaderAndStart( } auto result = requests_.emplace( - web_request_id, std::make_unique<InProgressRequest>( - this, web_request_id, request_id, routing_id, options, - request, is_download_, traffic_annotation, - std::move(loader_request), std::move(client))); + web_request_id, + std::make_unique<InProgressRequest>( + this, web_request_id, request_id, routing_id, options, request, + traffic_annotation, std::move(loader_request), std::move(client))); result.first->second->Restart(); } @@ -948,14 +957,14 @@ void WebRequestProxyingURLLoaderFactory::Clone( void WebRequestProxyingURLLoaderFactory::OnLoaderCreated( int32_t request_id, - network::mojom::TrustedHeaderClientRequest request) { + mojo::PendingReceiver<network::mojom::TrustedHeaderClient> receiver) { auto it = network_request_id_to_web_request_id_.find(request_id); if (it == network_request_id_to_web_request_id_.end()) return; auto request_it = requests_.find(it->second); DCHECK(request_it != requests_.end()); - request_it->second->OnLoaderCreated(std::move(request)); + request_it->second->OnLoaderCreated(std::move(receiver)); } void WebRequestProxyingURLLoaderFactory::HandleAuthRequest( diff --git a/chromium/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.h b/chromium/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.h index 83352e0bb3e..c4f34864289 100644 --- a/chromium/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.h +++ b/chromium/extensions/browser/api/web_request/web_request_proxying_url_loader_factory.h @@ -15,10 +15,11 @@ #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "components/keyed_service/core/keyed_service_shutdown_notifier.h" +#include "content/public/browser/content_browser_client.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/api/web_request/web_request_info.h" -#include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/binding_set.h" +#include "mojo/public/cpp/bindings/receiver.h" #include "net/base/completion_once_callback.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "services/network/public/cpp/resource_request.h" @@ -49,7 +50,6 @@ class WebRequestProxyingURLLoaderFactory int32_t network_service_request_id, uint32_t options, const network::ResourceRequest& request, - bool is_download, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, network::mojom::URLLoaderRequest loader_request, network::mojom::URLLoaderClientPtr client); @@ -61,16 +61,15 @@ class WebRequestProxyingURLLoaderFactory void FollowRedirect(const std::vector<std::string>& removed_headers, const net::HttpRequestHeaders& modified_headers, const base::Optional<GURL>& new_url) override; - void ProceedWithResponse() override; void SetPriority(net::RequestPriority priority, int32_t intra_priority_value) override; void PauseReadingBodyFromNet() override; void ResumeReadingBodyFromNet() override; // network::mojom::URLLoaderClient: - void OnReceiveResponse(const network::ResourceResponseHead& head) override; + void OnReceiveResponse(network::mojom::URLResponseHeadPtr head) override; void OnReceiveRedirect(const net::RedirectInfo& redirect_info, - const network::ResourceResponseHead& head) override; + network::mojom::URLResponseHeadPtr head) override; void OnUploadProgress(int64_t current_position, int64_t total_size, OnUploadProgressCallback callback) override; @@ -85,7 +84,8 @@ class WebRequestProxyingURLLoaderFactory scoped_refptr<net::HttpResponseHeaders> response_headers, WebRequestAPI::AuthRequestCallback callback); - void OnLoaderCreated(network::mojom::TrustedHeaderClientRequest request); + void OnLoaderCreated( + mojo::PendingReceiver<network::mojom::TrustedHeaderClient> receiver); // network::mojom::TrustedHeaderClient: void OnBeforeSendHeaders(const net::HttpRequestHeaders& headers, @@ -122,7 +122,6 @@ class WebRequestProxyingURLLoaderFactory WebRequestProxyingURLLoaderFactory* const factory_; network::ResourceRequest request_; const base::Optional<url::Origin> original_initiator_; - const bool is_download_; const uint64_t request_id_; const int32_t network_service_request_id_; const int32_t routing_id_; @@ -161,7 +160,8 @@ class WebRequestProxyingURLLoaderFactory bool current_request_uses_header_client_ = false; OnBeforeSendHeadersCallback on_before_send_headers_callback_; OnHeadersReceivedCallback on_headers_received_callback_; - mojo::Binding<network::mojom::TrustedHeaderClient> header_client_binding_; + mojo::Receiver<network::mojom::TrustedHeaderClient> header_client_receiver_{ + this}; // If |has_any_extra_headers_listeners_| is set to false and a redirect is // in progress, this stores the parameters to FollowRedirect that came from @@ -186,26 +186,28 @@ class WebRequestProxyingURLLoaderFactory WebRequestProxyingURLLoaderFactory( content::BrowserContext* browser_context, int render_process_id, - bool is_download, scoped_refptr<WebRequestAPI::RequestIDGenerator> request_id_generator, std::unique_ptr<ExtensionNavigationUIData> navigation_ui_data, network::mojom::URLLoaderFactoryRequest loader_request, network::mojom::URLLoaderFactoryPtrInfo target_factory_info, - network::mojom::TrustedURLLoaderHeaderClientRequest header_client_request, - WebRequestAPI::ProxySet* proxies); + mojo::PendingReceiver<network::mojom::TrustedURLLoaderHeaderClient> + header_client_receiver, + WebRequestAPI::ProxySet* proxies, + content::ContentBrowserClient::URLLoaderFactoryType loader_factory_type); ~WebRequestProxyingURLLoaderFactory() override; static void StartProxying( content::BrowserContext* browser_context, int render_process_id, - bool is_download, scoped_refptr<WebRequestAPI::RequestIDGenerator> request_id_generator, std::unique_ptr<ExtensionNavigationUIData> navigation_ui_data, network::mojom::URLLoaderFactoryRequest loader_request, network::mojom::URLLoaderFactoryPtrInfo target_factory_info, - network::mojom::TrustedURLLoaderHeaderClientRequest header_client_request, - WebRequestAPI::ProxySet* proxies); + mojo::PendingReceiver<network::mojom::TrustedURLLoaderHeaderClient> + header_client_receiver, + WebRequestAPI::ProxySet* proxies, + content::ContentBrowserClient::URLLoaderFactoryType loader_factory_type); // network::mojom::URLLoaderFactory: void CreateLoaderAndStart(network::mojom::URLLoaderRequest loader_request, @@ -221,7 +223,8 @@ class WebRequestProxyingURLLoaderFactory // network::mojom::TrustedURLLoaderHeaderClient: void OnLoaderCreated( int32_t request_id, - network::mojom::TrustedHeaderClientRequest request) override; + mojo::PendingReceiver<network::mojom::TrustedHeaderClient> receiver) + override; // WebRequestAPI::Proxy: void HandleAuthRequest( @@ -230,6 +233,14 @@ class WebRequestProxyingURLLoaderFactory int32_t request_id, WebRequestAPI::AuthRequestCallback callback) override; + content::ContentBrowserClient::URLLoaderFactoryType loader_factory_type() + const { + return loader_factory_type_; + } + + bool IsForServiceWorkerScript() const; + bool IsForDownload() const; + private: void OnTargetFactoryError(); void OnProxyBindingError(); @@ -238,16 +249,18 @@ class WebRequestProxyingURLLoaderFactory content::BrowserContext* const browser_context_; const int render_process_id_; - const bool is_download_; scoped_refptr<WebRequestAPI::RequestIDGenerator> request_id_generator_; std::unique_ptr<ExtensionNavigationUIData> navigation_ui_data_; mojo::BindingSet<network::mojom::URLLoaderFactory> proxy_bindings_; network::mojom::URLLoaderFactoryPtr target_factory_; - mojo::Binding<network::mojom::TrustedURLLoaderHeaderClient> - url_loader_header_client_binding_; + mojo::Receiver<network::mojom::TrustedURLLoaderHeaderClient> + url_loader_header_client_receiver_{this}; // Owns |this|. WebRequestAPI::ProxySet* const proxies_; + const content::ContentBrowserClient::URLLoaderFactoryType + loader_factory_type_; + // Mapping from our own internally generated request ID to an // InProgressRequest instance. std::map<uint64_t, std::unique_ptr<InProgressRequest>> requests_; diff --git a/chromium/extensions/browser/api/web_request/web_request_proxying_websocket.cc b/chromium/extensions/browser/api/web_request/web_request_proxying_websocket.cc index 6a8553d0a3b..7df1fa30280 100644 --- a/chromium/extensions/browser/api/web_request/web_request_proxying_websocket.cc +++ b/chromium/extensions/browser/api/web_request/web_request_proxying_websocket.cc @@ -11,7 +11,6 @@ #include "content/public/browser/browser_thread.h" #include "extensions/browser/api/web_request/permission_helper.h" #include "extensions/browser/extension_navigation_ui_data.h" -#include "mojo/public/cpp/bindings/strong_binding.h" #include "net/base/ip_endpoint.h" #include "net/http/http_util.h" @@ -47,7 +46,8 @@ class ShutdownNotifierFactory WebRequestProxyingWebSocket::WebRequestProxyingWebSocket( WebSocketFactory factory, const network::ResourceRequest& request, - network::mojom::WebSocketHandshakeClientPtr handshake_client, + mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> + handshake_client, bool has_extra_headers, int process_id, int render_frame_id, @@ -57,18 +57,17 @@ WebRequestProxyingWebSocket::WebRequestProxyingWebSocket( : factory_(std::move(factory)), browser_context_(browser_context), forwarding_handshake_client_(std::move(handshake_client)), - binding_as_handshake_client_(this), - binding_as_auth_handler_(this), - binding_as_header_client_(has_extra_headers ? this : nullptr), request_headers_(request.headers), + has_extra_headers_(has_extra_headers), info_(WebRequestInfoInitParams(request_id_generator->Generate(), process_id, render_frame_id, nullptr, MSG_ROUTING_NONE, request, - false /* is_download */, - true /* is_async */)), + /*is_download=*/false, + /*is_async=*/true, + /*is_service_worker_script=*/false)), proxies_(proxies) { // base::Unretained is safe here because the callback will be canceled when // |shutdown_notifier_| is destroyed, and |proxies_| owns this. @@ -99,7 +98,7 @@ void WebRequestProxyingWebSocket::Start() { // OnBeforeSendHeaders and OnSendHeaders will be handled there. Otherwise, // send these events before the request starts. base::RepeatingCallback<void(int)> continuation; - if (binding_as_header_client_.impl()) { + if (has_extra_headers_) { continuation = base::BindRepeating( &WebRequestProxyingWebSocket::ContinueToStartRequest, weak_factory_.GetWeakPtr()); @@ -144,8 +143,8 @@ void WebRequestProxyingWebSocket::OnResponseReceived( DCHECK(forwarding_handshake_client_); // response_.headers will be set in OnBeforeSendHeaders if - // binding_as_header_client_ is set. - if (!binding_as_header_client_) { + // |receiver_as_header_client_| is set. + if (!receiver_as_header_client_.is_bound()) { response_.headers = base::MakeRefCounted<net::HttpResponseHeaders>(base::StringPrintf( "HTTP/%d.%d %d %s", response->http_version.major_value(), @@ -163,7 +162,7 @@ void WebRequestProxyingWebSocket::OnResponseReceived( // requests. forwarding_handshake_client_->OnResponseReceived(std::move(response)); - if (!binding_as_header_client_ || response_.headers) { + if (!receiver_as_header_client_.is_bound() || response_.headers) { ContinueToHeadersReceived(); } else { waiting_for_header_client_headers_received_ = true; @@ -192,10 +191,11 @@ void WebRequestProxyingWebSocket::ContinueToHeadersReceived() { } void WebRequestProxyingWebSocket::OnConnectionEstablished( - network::mojom::WebSocketPtr websocket, + mojo::PendingRemote<network::mojom::WebSocket> websocket, + mojo::PendingReceiver<network::mojom::WebSocketClient> client_receiver, const std::string& selected_protocol, const std::string& extensions, - uint64_t receive_quota_threshold) { + mojo::ScopedDataPipeConsumerHandle readable) { DCHECK(forwarding_handshake_client_); DCHECK(!is_done_); is_done_ = true; @@ -203,8 +203,8 @@ void WebRequestProxyingWebSocket::OnConnectionEstablished( browser_context_, &info_, net::ERR_WS_UPGRADE); forwarding_handshake_client_->OnConnectionEstablished( - std::move(websocket), selected_protocol, extensions, - receive_quota_threshold); + std::move(websocket), std::move(client_receiver), selected_protocol, + extensions, std::move(readable)); // Deletes |this|. proxies_->RemoveProxy(this); @@ -247,7 +247,7 @@ void WebRequestProxyingWebSocket::OnAuthRequired( void WebRequestProxyingWebSocket::OnBeforeSendHeaders( const net::HttpRequestHeaders& headers, OnBeforeSendHeadersCallback callback) { - DCHECK(binding_as_header_client_); + DCHECK(receiver_as_header_client_.is_bound()); request_headers_ = headers; on_before_send_headers_callback_ = std::move(callback); @@ -257,7 +257,7 @@ void WebRequestProxyingWebSocket::OnBeforeSendHeaders( void WebRequestProxyingWebSocket::OnHeadersReceived( const std::string& headers, OnHeadersReceivedCallback callback) { - DCHECK(binding_as_header_client_); + DCHECK(receiver_as_header_client_.is_bound()); // Note: since there are different pipes used for WebSocketClient and // TrustedHeaderClient, there are no guarantees whether this or @@ -277,7 +277,8 @@ void WebRequestProxyingWebSocket::StartProxying( const GURL& url, const GURL& site_for_cookies, const base::Optional<std::string>& user_agent, - network::mojom::WebSocketHandshakeClientPtrInfo handshake_client, + mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> + handshake_client, bool has_extra_headers, int process_id, int render_frame_id, @@ -295,8 +296,7 @@ void WebRequestProxyingWebSocket::StartProxying( request.request_initiator = origin; auto proxy = std::make_unique<WebRequestProxyingWebSocket>( - std::move(factory), request, - network::mojom::WebSocketHandshakeClientPtr(std::move(handshake_client)), + std::move(factory), request, std::move(handshake_client), has_extra_headers, process_id, render_frame_id, browser_context, std::move(request_id_generator), proxies); @@ -306,7 +306,8 @@ void WebRequestProxyingWebSocket::StartProxying( } void WebRequestProxyingWebSocket::OnBeforeRequestComplete(int error_code) { - DCHECK(binding_as_header_client_ || !binding_as_handshake_client_.is_bound()); + DCHECK(receiver_as_header_client_.is_bound() || + !receiver_as_handshake_client_.is_bound()); DCHECK(info_.url.SchemeIsWSOrWSS()); if (error_code != net::OK) { OnError(error_code); @@ -338,13 +339,14 @@ void WebRequestProxyingWebSocket::OnBeforeSendHeadersComplete( const std::set<std::string>& removed_headers, const std::set<std::string>& set_headers, int error_code) { - DCHECK(binding_as_header_client_ || !binding_as_handshake_client_.is_bound()); + DCHECK(receiver_as_header_client_.is_bound() || + !receiver_as_handshake_client_.is_bound()); if (error_code != net::OK) { OnError(error_code); return; } - if (binding_as_header_client_) { + if (receiver_as_header_client_.is_bound()) { DCHECK(on_before_send_headers_callback_); std::move(on_before_send_headers_callback_) .Run(error_code, request_headers_); @@ -353,7 +355,7 @@ void WebRequestProxyingWebSocket::OnBeforeSendHeadersComplete( ExtensionWebRequestEventRouter::GetInstance()->OnSendHeaders( browser_context_, &info_, request_headers_); - if (!binding_as_header_client_) + if (!receiver_as_header_client_.is_bound()) ContinueToStartRequest(net::OK); } @@ -372,25 +374,25 @@ void WebRequestProxyingWebSocket::ContinueToStartRequest(int error_code) { } } - // Here we detect mojo connection errors on |handshake_client|. See also - // CreateWebSocket in //network/services/public/mojom/network_context.mojom. - // Here we don't have |connection_client| so using |handshake_client| is the - // best. - network::mojom::WebSocketHandshakeClientPtr handshake_client; - binding_as_handshake_client_.Bind(mojo::MakeRequest(&handshake_client)); - binding_as_handshake_client_.set_connection_error_with_reason_handler( - base::BindOnce(&WebRequestProxyingWebSocket::OnMojoConnectionError, - base::Unretained(this))); - network::mojom::AuthenticationHandlerPtr auth_handler; - binding_as_auth_handler_.Bind(mojo::MakeRequest(&auth_handler)); - network::mojom::TrustedHeaderClientPtr trusted_header_client; - if (binding_as_header_client_.impl()) { - binding_as_header_client_.Bind(mojo::MakeRequest(&trusted_header_client)); + mojo::PendingRemote<network::mojom::TrustedHeaderClient> + trusted_header_client = mojo::NullRemote(); + if (has_extra_headers_) { + trusted_header_client = + receiver_as_header_client_.BindNewPipeAndPassRemote(); } - std::move(factory_).Run(info_.url, std::move(additional_headers), - std::move(handshake_client), std::move(auth_handler), - std::move(trusted_header_client)); + std::move(factory_).Run( + info_.url, std::move(additional_headers), + receiver_as_handshake_client_.BindNewPipeAndPassRemote(), + receiver_as_auth_handler_.BindNewPipeAndPassRemote(), + std::move(trusted_header_client)); + + // Here we detect mojo connection errors on |receiver_as_handshake_client_|. + // See also CreateWebSocket in + // //network/services/public/mojom/network_context.mojom. + receiver_as_handshake_client_.set_disconnect_with_reason_handler( + base::BindOnce(&WebRequestProxyingWebSocket::OnMojoConnectionError, + base::Unretained(this))); } void WebRequestProxyingWebSocket::OnHeadersReceivedComplete(int error_code) { @@ -460,17 +462,17 @@ void WebRequestProxyingWebSocket::OnHeadersReceivedCompleteForAuth( } void WebRequestProxyingWebSocket::PauseIncomingMethodCallProcessing() { - binding_as_handshake_client_.PauseIncomingMethodCallProcessing(); - binding_as_auth_handler_.PauseIncomingMethodCallProcessing(); - if (binding_as_header_client_) - binding_as_header_client_.PauseIncomingMethodCallProcessing(); + receiver_as_handshake_client_.Pause(); + receiver_as_auth_handler_.Pause(); + if (receiver_as_header_client_.is_bound()) + receiver_as_header_client_.Pause(); } void WebRequestProxyingWebSocket::ResumeIncomingMethodCallProcessing() { - binding_as_handshake_client_.ResumeIncomingMethodCallProcessing(); - binding_as_auth_handler_.ResumeIncomingMethodCallProcessing(); - if (binding_as_header_client_) - binding_as_header_client_.ResumeIncomingMethodCallProcessing(); + receiver_as_handshake_client_.Resume(); + receiver_as_auth_handler_.Resume(); + if (receiver_as_header_client_.is_bound()) + receiver_as_header_client_.Resume(); } void WebRequestProxyingWebSocket::OnError(int error_code) { diff --git a/chromium/extensions/browser/api/web_request/web_request_proxying_websocket.h b/chromium/extensions/browser/api/web_request/web_request_proxying_websocket.h index fe5e2d4bcf7..93ef131a95a 100644 --- a/chromium/extensions/browser/api/web_request/web_request_proxying_websocket.h +++ b/chromium/extensions/browser/api/web_request/web_request_proxying_websocket.h @@ -16,8 +16,9 @@ #include "components/keyed_service/core/keyed_service_shutdown_notifier.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/api/web_request/web_request_info.h" -#include "mojo/public/cpp/bindings/binding.h" -#include "mojo/public/cpp/bindings/binding_set.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" #include "net/base/network_delegate.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/resource_response.h" @@ -45,7 +46,8 @@ class WebRequestProxyingWebSocket WebRequestProxyingWebSocket( WebSocketFactory factory, const network::ResourceRequest& request, - network::mojom::WebSocketHandshakeClientPtr handshake_client, + mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> + handshake_client, bool has_extra_headers, int process_id, int render_frame_id, @@ -61,10 +63,12 @@ class WebRequestProxyingWebSocket network::mojom::WebSocketHandshakeRequestPtr request) override; void OnResponseReceived( network::mojom::WebSocketHandshakeResponsePtr response) override; - void OnConnectionEstablished(network::mojom::WebSocketPtr websocket, - const std::string& selected_protocol, - const std::string& extensions, - uint64_t receive_quota_threshold) override; + void OnConnectionEstablished( + mojo::PendingRemote<network::mojom::WebSocket> websocket, + mojo::PendingReceiver<network::mojom::WebSocketClient> client_receiver, + const std::string& selected_protocol, + const std::string& extensions, + mojo::ScopedDataPipeConsumerHandle readable) override; // network::mojom::AuthenticationHandler method: void OnAuthRequired(const net::AuthChallengeInfo& auth_info, @@ -83,7 +87,8 @@ class WebRequestProxyingWebSocket const GURL& url, const GURL& site_for_cookies, const base::Optional<std::string>& user_agent, - network::mojom::WebSocketHandshakeClientPtrInfo handshake_client, + mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> + handshake_client, bool has_extra_headers, int process_id, int render_frame_id, @@ -112,11 +117,14 @@ class WebRequestProxyingWebSocket WebSocketFactory factory_; content::BrowserContext* const browser_context_; - network::mojom::WebSocketHandshakeClientPtr forwarding_handshake_client_; - mojo::Binding<network::mojom::WebSocketHandshakeClient> - binding_as_handshake_client_; - mojo::Binding<network::mojom::AuthenticationHandler> binding_as_auth_handler_; - mojo::Binding<network::mojom::TrustedHeaderClient> binding_as_header_client_; + mojo::Remote<network::mojom::WebSocketHandshakeClient> + forwarding_handshake_client_; + mojo::Receiver<network::mojom::WebSocketHandshakeClient> + receiver_as_handshake_client_{this}; + mojo::Receiver<network::mojom::AuthenticationHandler> + receiver_as_auth_handler_{this}; + mojo::Receiver<network::mojom::TrustedHeaderClient> + receiver_as_header_client_{this}; net::HttpRequestHeaders request_headers_; network::ResourceResponseHead response_; @@ -131,6 +139,7 @@ class WebRequestProxyingWebSocket GURL redirect_url_; bool is_done_ = false; bool waiting_for_header_client_headers_received_ = false; + bool has_extra_headers_; WebRequestInfo info_; diff --git a/chromium/extensions/browser/api/web_request/web_request_resource_type.cc b/chromium/extensions/browser/api/web_request/web_request_resource_type.cc index d96632f8b3c..e26d0985ae6 100644 --- a/chromium/extensions/browser/api/web_request/web_request_resource_type.cc +++ b/chromium/extensions/browser/api/web_request/web_request_resource_type.cc @@ -7,7 +7,6 @@ #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/stl_util.h" -#include "content/public/browser/resource_request_info.h" #include "extensions/browser/api/web_request/web_request_info.h" namespace extensions { diff --git a/chromium/extensions/browser/api/webcam_private/visca_webcam.cc b/chromium/extensions/browser/api/webcam_private/visca_webcam.cc index 83455202ca1..a88ec808aee 100644 --- a/chromium/extensions/browser/api/webcam_private/visca_webcam.cc +++ b/chromium/extensions/browser/api/webcam_private/visca_webcam.cc @@ -160,7 +160,7 @@ int GetPositiveValue(int value) { namespace extensions { -ViscaWebcam::ViscaWebcam() : pan_(0), tilt_(0), weak_ptr_factory_(this) {} +ViscaWebcam::ViscaWebcam() : pan_(0), tilt_(0) {} ViscaWebcam::~ViscaWebcam() { } @@ -168,11 +168,10 @@ ViscaWebcam::~ViscaWebcam() { void ViscaWebcam::Open(const std::string& extension_id, device::mojom::SerialPortPtrInfo port_ptr_info, const OpenCompleteCallback& open_callback) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&ViscaWebcam::OpenOnIOThread, - weak_ptr_factory_.GetWeakPtr(), extension_id, - std::move(port_ptr_info), open_callback)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&ViscaWebcam::OpenOnIOThread, + weak_ptr_factory_.GetWeakPtr(), extension_id, + std::move(port_ptr_info), open_callback)); } void ViscaWebcam::OpenOnIOThread(const std::string& extension_id, @@ -237,8 +236,8 @@ void ViscaWebcam::OnClearAllCompleted(const OpenCompleteCallback& open_callback, return; } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(open_callback, true)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(open_callback, true)); } void ViscaWebcam::Send(const std::vector<char>& command, @@ -246,7 +245,7 @@ void ViscaWebcam::Send(const std::vector<char>& command, commands_.push_back(std::make_pair(command, callback)); // If this is the only command in the queue, send it now. if (commands_.size() == 1) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ViscaWebcam::SendOnIOThread, weak_ptr_factory_.GetWeakPtr(), command, callback)); @@ -272,9 +271,8 @@ void ViscaWebcam::OnSendCompleted(const CommandCompleteCallback& callback, base::BindRepeating(&ViscaWebcam::OnReceiveEvent, weak_ptr_factory_.GetWeakPtr(), callback)); } else { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, false, std::vector<char>())); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, false, std::vector<char>())); } } @@ -288,8 +286,8 @@ void ViscaWebcam::OnReceiveEvent(const CommandCompleteCallback& callback, // Clear |data_buffer_|. std::vector<char> response; response.swap(data_buffer_); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, false, response)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, false, response)); serial_connection_->SetPaused(true); return; } @@ -306,14 +304,14 @@ void ViscaWebcam::OnReceiveEvent(const CommandCompleteCallback& callback, if (response.size() < 2 || (static_cast<int>(response[1]) & 0xF0) == kViscaResponseError) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, false, response)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, false, response)); serial_connection_->SetPaused(true); } else if ((static_cast<int>(response[1]) & 0xF0) != kViscaResponseAck && (static_cast<int>(response[1]) & 0xFF) != kViscaResponseNetworkChange) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, true, response)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, true, response)); serial_connection_->SetPaused(true); } } @@ -394,16 +392,16 @@ void ViscaWebcam::ProcessNextCommand() { // If there are pending commands, process the next one. const std::vector<char> next_command = commands_.front().first; const CommandCompleteCallback next_callback = commands_.front().second; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&ViscaWebcam::SendOnIOThread, - weak_ptr_factory_.GetWeakPtr(), - next_command, next_callback)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&ViscaWebcam::SendOnIOThread, + weak_ptr_factory_.GetWeakPtr(), next_command, + next_callback)); } void ViscaWebcam::PostOpenFailureTask( const OpenCompleteCallback& open_callback) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(open_callback, false /* success? */)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(open_callback, false /* success? */)); } void ViscaWebcam::GetPan(const GetPTZCompleteCallback& callback) { diff --git a/chromium/extensions/browser/api/webcam_private/visca_webcam.h b/chromium/extensions/browser/api/webcam_private/visca_webcam.h index db277d56ce9..65da7c28c91 100644 --- a/chromium/extensions/browser/api/webcam_private/visca_webcam.h +++ b/chromium/extensions/browser/api/webcam_private/visca_webcam.h @@ -145,7 +145,7 @@ class ViscaWebcam : public Webcam { int pan_; int tilt_; - base::WeakPtrFactory<ViscaWebcam> weak_ptr_factory_; + base::WeakPtrFactory<ViscaWebcam> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ViscaWebcam); }; diff --git a/chromium/extensions/browser/api/webcam_private/visca_webcam_unittest.cc b/chromium/extensions/browser/api/webcam_private/visca_webcam_unittest.cc index 30a9f5eb772..596269cd443 100644 --- a/chromium/extensions/browser/api/webcam_private/visca_webcam_unittest.cc +++ b/chromium/extensions/browser/api/webcam_private/visca_webcam_unittest.cc @@ -9,7 +9,7 @@ #include "base/bind.h" #include "base/macros.h" #include "base/run_loop.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "testing/gtest/include/gtest/gtest.h" @@ -119,7 +119,7 @@ class ViscaWebcamTest : public testing::Test { } private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; scoped_refptr<ViscaWebcam> webcam_; }; diff --git a/chromium/extensions/browser/api/webcam_private/webcam_private_api.h b/chromium/extensions/browser/api/webcam_private/webcam_private_api.h index 6d36c80b91b..e7e5b484f32 100644 --- a/chromium/extensions/browser/api/webcam_private/webcam_private_api.h +++ b/chromium/extensions/browser/api/webcam_private/webcam_private_api.h @@ -71,7 +71,7 @@ class WebcamPrivateAPI : public BrowserContextKeyedAPI { content::BrowserContext* const browser_context_; std::unique_ptr<ApiResourceManager<WebcamResource>> webcam_resource_manager_; - base::WeakPtrFactory<WebcamPrivateAPI> weak_ptr_factory_; + base::WeakPtrFactory<WebcamPrivateAPI> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(WebcamPrivateAPI); }; @@ -80,7 +80,7 @@ template <> void BrowserContextKeyedAPIFactory<WebcamPrivateAPI> ::DeclareFactoryDependencies(); -class WebcamPrivateOpenSerialWebcamFunction : public UIThreadExtensionFunction { +class WebcamPrivateOpenSerialWebcamFunction : public ExtensionFunction { public: WebcamPrivateOpenSerialWebcamFunction(); DECLARE_EXTENSION_FUNCTION("webcamPrivate.openSerialWebcam", @@ -89,7 +89,7 @@ class WebcamPrivateOpenSerialWebcamFunction : public UIThreadExtensionFunction { protected: ~WebcamPrivateOpenSerialWebcamFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -98,7 +98,7 @@ class WebcamPrivateOpenSerialWebcamFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(WebcamPrivateOpenSerialWebcamFunction); }; -class WebcamPrivateCloseWebcamFunction : public UIThreadExtensionFunction { +class WebcamPrivateCloseWebcamFunction : public ExtensionFunction { public: WebcamPrivateCloseWebcamFunction(); DECLARE_EXTENSION_FUNCTION("webcamPrivate.closeWebcam", @@ -107,14 +107,14 @@ class WebcamPrivateCloseWebcamFunction : public UIThreadExtensionFunction { protected: ~WebcamPrivateCloseWebcamFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: DISALLOW_COPY_AND_ASSIGN(WebcamPrivateCloseWebcamFunction); }; -class WebcamPrivateSetFunction : public UIThreadExtensionFunction { +class WebcamPrivateSetFunction : public ExtensionFunction { public: WebcamPrivateSetFunction(); DECLARE_EXTENSION_FUNCTION("webcamPrivate.set", WEBCAMPRIVATE_SET) @@ -122,7 +122,7 @@ class WebcamPrivateSetFunction : public UIThreadExtensionFunction { protected: ~WebcamPrivateSetFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -134,7 +134,7 @@ class WebcamPrivateSetFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(WebcamPrivateSetFunction); }; -class WebcamPrivateGetFunction : public UIThreadExtensionFunction { +class WebcamPrivateGetFunction : public ExtensionFunction { public: WebcamPrivateGetFunction(); DECLARE_EXTENSION_FUNCTION("webcamPrivate.get", WEBCAMPRIVATE_GET) @@ -142,7 +142,7 @@ class WebcamPrivateGetFunction : public UIThreadExtensionFunction { protected: ~WebcamPrivateGetFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -185,7 +185,7 @@ class WebcamPrivateGetFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(WebcamPrivateGetFunction); }; -class WebcamPrivateResetFunction : public UIThreadExtensionFunction { +class WebcamPrivateResetFunction : public ExtensionFunction { public: WebcamPrivateResetFunction(); DECLARE_EXTENSION_FUNCTION("webcamPrivate.reset", WEBCAMPRIVATE_RESET) @@ -193,7 +193,7 @@ class WebcamPrivateResetFunction : public UIThreadExtensionFunction { protected: ~WebcamPrivateResetFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: diff --git a/chromium/extensions/browser/api/webcam_private/webcam_private_api_chromeos.cc b/chromium/extensions/browser/api/webcam_private/webcam_private_api_chromeos.cc index cd9d3a616ef..55d8ed9be9b 100644 --- a/chromium/extensions/browser/api/webcam_private/webcam_private_api_chromeos.cc +++ b/chromium/extensions/browser/api/webcam_private/webcam_private_api_chromeos.cc @@ -42,8 +42,7 @@ WebcamPrivateAPI* WebcamPrivateAPI::Get(content::BrowserContext* context) { } WebcamPrivateAPI::WebcamPrivateAPI(content::BrowserContext* context) - : browser_context_(context), - weak_ptr_factory_(this) { + : browser_context_(context) { webcam_resource_manager_.reset( new ApiResourceManager<WebcamResource>(context)); } diff --git a/chromium/extensions/browser/api_test_utils.cc b/chromium/extensions/browser/api_test_utils.cc index 3d95cd59f1c..b32757b8cef 100644 --- a/chromium/extensions/browser/api_test_utils.cc +++ b/chromium/extensions/browser/api_test_utils.cc @@ -36,7 +36,7 @@ namespace extensions { namespace api_test_utils { -SendResponseHelper::SendResponseHelper(UIThreadExtensionFunction* function) { +SendResponseHelper::SendResponseHelper(ExtensionFunction* function) { function->set_has_callback(true); function->set_response_callback( base::Bind(&SendResponseHelper::OnResponse, base::Unretained(this))); @@ -89,7 +89,7 @@ std::string GetString(const base::DictionaryValue* val, } std::unique_ptr<base::Value> RunFunctionWithDelegateAndReturnSingleResult( - scoped_refptr<UIThreadExtensionFunction> function, + scoped_refptr<ExtensionFunction> function, const std::string& args, content::BrowserContext* context, std::unique_ptr<extensions::ExtensionFunctionDispatcher> dispatcher, @@ -103,7 +103,7 @@ std::unique_ptr<base::Value> RunFunctionWithDelegateAndReturnSingleResult( } std::unique_ptr<base::Value> RunFunctionWithDelegateAndReturnSingleResult( - scoped_refptr<UIThreadExtensionFunction> function, + scoped_refptr<ExtensionFunction> function, std::unique_ptr<base::ListValue> args, content::BrowserContext* context, std::unique_ptr<extensions::ExtensionFunctionDispatcher> dispatcher, @@ -121,14 +121,14 @@ std::unique_ptr<base::Value> RunFunctionWithDelegateAndReturnSingleResult( } std::unique_ptr<base::Value> RunFunctionAndReturnSingleResult( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& args, content::BrowserContext* context) { return RunFunctionAndReturnSingleResult(function, args, context, NONE); } std::unique_ptr<base::Value> RunFunctionAndReturnSingleResult( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& args, content::BrowserContext* context, RunFunctionFlags flags) { @@ -139,13 +139,13 @@ std::unique_ptr<base::Value> RunFunctionAndReturnSingleResult( function, args, context, std::move(dispatcher), flags); } -std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, +std::string RunFunctionAndReturnError(ExtensionFunction* function, const std::string& args, content::BrowserContext* context) { return RunFunctionAndReturnError(function, args, context, NONE); } -std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, +std::string RunFunctionAndReturnError(ExtensionFunction* function, const std::string& args, content::BrowserContext* context, RunFunctionFlags flags) { @@ -164,7 +164,7 @@ std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, return function->GetError(); } -bool RunFunction(UIThreadExtensionFunction* function, +bool RunFunction(ExtensionFunction* function, const std::string& args, content::BrowserContext* context) { std::unique_ptr<ExtensionFunctionDispatcher> dispatcher( @@ -173,7 +173,7 @@ bool RunFunction(UIThreadExtensionFunction* function, } bool RunFunction( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& args, content::BrowserContext* context, std::unique_ptr<extensions::ExtensionFunctionDispatcher> dispatcher, @@ -186,7 +186,7 @@ bool RunFunction( } bool RunFunction( - UIThreadExtensionFunction* function, + ExtensionFunction* function, std::unique_ptr<base::ListValue> args, content::BrowserContext* context, std::unique_ptr<extensions::ExtensionFunctionDispatcher> dispatcher, diff --git a/chromium/extensions/browser/api_test_utils.h b/chromium/extensions/browser/api_test_utils.h index 77c823f38b9..fb94e4cf5eb 100644 --- a/chromium/extensions/browser/api_test_utils.h +++ b/chromium/extensions/browser/api_test_utils.h @@ -35,7 +35,7 @@ namespace api_test_utils { // A helper class to handle waiting for a function response. class SendResponseHelper { public: - explicit SendResponseHelper(UIThreadExtensionFunction* function); + explicit SendResponseHelper(ExtensionFunction* function); ~SendResponseHelper(); bool has_response() { return response_.get() != nullptr; } @@ -75,13 +75,13 @@ std::string GetString(const base::DictionaryValue* val, const std::string& key); // current test if |function| returns an error. Takes ownership of // |function|. The caller takes ownership of the result. std::unique_ptr<base::Value> RunFunctionWithDelegateAndReturnSingleResult( - scoped_refptr<UIThreadExtensionFunction> function, + scoped_refptr<ExtensionFunction> function, const std::string& args, content::BrowserContext* context, std::unique_ptr<ExtensionFunctionDispatcher> dispatcher, RunFunctionFlags flags); std::unique_ptr<base::Value> RunFunctionWithDelegateAndReturnSingleResult( - scoped_refptr<UIThreadExtensionFunction> function, + scoped_refptr<ExtensionFunction> function, std::unique_ptr<base::ListValue> args, content::BrowserContext* context, std::unique_ptr<ExtensionFunctionDispatcher> dispatcher, @@ -90,11 +90,11 @@ std::unique_ptr<base::Value> RunFunctionWithDelegateAndReturnSingleResult( // RunFunctionWithDelegateAndReturnSingleResult, except with a NULL // implementation of the Delegate. std::unique_ptr<base::Value> RunFunctionAndReturnSingleResult( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& args, content::BrowserContext* context); std::unique_ptr<base::Value> RunFunctionAndReturnSingleResult( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& args, content::BrowserContext* context, RunFunctionFlags flags); @@ -102,11 +102,11 @@ std::unique_ptr<base::Value> RunFunctionAndReturnSingleResult( // Run |function| with |args| and return the resulting error. Adds an error to // the current test if |function| returns a result. Takes ownership of // |function|. -std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, +std::string RunFunctionAndReturnError(ExtensionFunction* function, const std::string& args, content::BrowserContext* context, RunFunctionFlags flags); -std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, +std::string RunFunctionAndReturnError(ExtensionFunction* function, const std::string& args, content::BrowserContext* context); @@ -120,15 +120,15 @@ std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, // TODO(aa): I'm concerned that this style won't scale to all the bits and bobs // we're going to need to frob for all the different extension functions. But // we can refactor when we see what is needed. -bool RunFunction(UIThreadExtensionFunction* function, +bool RunFunction(ExtensionFunction* function, const std::string& args, content::BrowserContext* context); -bool RunFunction(UIThreadExtensionFunction* function, +bool RunFunction(ExtensionFunction* function, const std::string& args, content::BrowserContext* context, std::unique_ptr<ExtensionFunctionDispatcher> dispatcher, RunFunctionFlags flags); -bool RunFunction(UIThreadExtensionFunction* function, +bool RunFunction(ExtensionFunction* function, std::unique_ptr<base::ListValue> args, content::BrowserContext* context, std::unique_ptr<ExtensionFunctionDispatcher> dispatcher, diff --git a/chromium/extensions/browser/api_unittest.cc b/chromium/extensions/browser/api_unittest.cc index 186b6d3d940..e4ad721ce86 100644 --- a/chromium/extensions/browser/api_unittest.cc +++ b/chromium/extensions/browser/api_unittest.cc @@ -58,7 +58,7 @@ void ApiUnitTest::CreateBackgroundPage() { } std::unique_ptr<base::Value> ApiUnitTest::RunFunctionAndReturnValue( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& args) { function->set_extension(extension()); if (contents_) @@ -68,7 +68,7 @@ std::unique_ptr<base::Value> ApiUnitTest::RunFunctionAndReturnValue( } std::unique_ptr<base::DictionaryValue> -ApiUnitTest::RunFunctionAndReturnDictionary(UIThreadExtensionFunction* function, +ApiUnitTest::RunFunctionAndReturnDictionary(ExtensionFunction* function, const std::string& args) { base::Value* value = RunFunctionAndReturnValue(function, args).release(); base::DictionaryValue* dict = NULL; @@ -83,7 +83,7 @@ ApiUnitTest::RunFunctionAndReturnDictionary(UIThreadExtensionFunction* function, } std::unique_ptr<base::ListValue> ApiUnitTest::RunFunctionAndReturnList( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& args) { base::Value* value = RunFunctionAndReturnValue(function, args).release(); base::ListValue* list = NULL; @@ -97,16 +97,15 @@ std::unique_ptr<base::ListValue> ApiUnitTest::RunFunctionAndReturnList( return std::unique_ptr<base::ListValue>(list); } -std::string ApiUnitTest::RunFunctionAndReturnError( - UIThreadExtensionFunction* function, - const std::string& args) { +std::string ApiUnitTest::RunFunctionAndReturnError(ExtensionFunction* function, + const std::string& args) { function->set_extension(extension()); if (contents_) function->SetRenderFrameHost(contents_->GetMainFrame()); return utils::RunFunctionAndReturnError(function, args, browser_context()); } -void ApiUnitTest::RunFunction(UIThreadExtensionFunction* function, +void ApiUnitTest::RunFunction(ExtensionFunction* function, const std::string& args) { RunFunctionAndReturnValue(function, args); } diff --git a/chromium/extensions/browser/api_unittest.h b/chromium/extensions/browser/api_unittest.h index 72c71f81dec..33de01eab69 100644 --- a/chromium/extensions/browser/api_unittest.h +++ b/chromium/extensions/browser/api_unittest.h @@ -22,7 +22,7 @@ namespace content { class WebContents; } -class UIThreadExtensionFunction; +class ExtensionFunction; namespace extensions { @@ -60,29 +60,28 @@ class ApiUnitTest : public ExtensionsTest { // Return the function result as a base::Value. std::unique_ptr<base::Value> RunFunctionAndReturnValue( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& args); // Return the function result as a base::DictionaryValue, or NULL. // This will EXPECT-fail if the result is not a DictionaryValue. std::unique_ptr<base::DictionaryValue> RunFunctionAndReturnDictionary( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& args); // Return the function result as a base::ListValue, or NULL. // This will EXPECT-fail if the result is not a ListValue. std::unique_ptr<base::ListValue> RunFunctionAndReturnList( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& args); // Return an error thrown from the function, if one exists. // This will EXPECT-fail if any result is returned from the function. - std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, + std::string RunFunctionAndReturnError(ExtensionFunction* function, const std::string& args); // Run the function and ignore any result. - void RunFunction(UIThreadExtensionFunction* function, - const std::string& args); + void RunFunction(ExtensionFunction* function, const std::string& args); private: sync_preferences::TestingPrefServiceSyncable testing_pref_service_; diff --git a/chromium/extensions/browser/app_window/OWNERS b/chromium/extensions/browser/app_window/OWNERS new file mode 100644 index 00000000000..780e097b707 --- /dev/null +++ b/chromium/extensions/browser/app_window/OWNERS @@ -0,0 +1 @@ +# COMPONENT: Platform>Apps diff --git a/chromium/extensions/browser/app_window/app_window.cc b/chromium/extensions/browser/app_window/app_window.cc index bee0690eaf7..f43fba0260d 100644 --- a/chromium/extensions/browser/app_window/app_window.cc +++ b/chromium/extensions/browser/app_window/app_window.cc @@ -27,7 +27,6 @@ #include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" -#include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/app_window/app_delegate.h" #include "extensions/browser/app_window/app_web_contents_helper.h" @@ -1086,10 +1085,8 @@ SkRegion* AppWindow::RawDraggableRegionsToSkRegion( for (auto iter = regions.cbegin(); iter != regions.cend(); ++iter) { const DraggableRegion& region = *iter; sk_region->op( - region.bounds.x(), - region.bounds.y(), - region.bounds.right(), - region.bounds.bottom(), + SkIRect::MakeLTRB(region.bounds.x(), region.bounds.y(), + region.bounds.right(), region.bounds.bottom()), region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op); } return sk_region; diff --git a/chromium/extensions/browser/app_window/app_window.h b/chromium/extensions/browser/app_window/app_window.h index c12d1257c14..e25cec0e93c 100644 --- a/chromium/extensions/browser/app_window/app_window.h +++ b/chromium/extensions/browser/app_window/app_window.h @@ -587,8 +587,8 @@ class AppWindow : public content::WebContentsDelegate, // race condition of loading custom app icon and app content simultaneously. bool window_ready_ = false; - // PlzNavigate: these callbacks are called when the navigation is finished on - // both browser and renderer sides. + // These callbacks are called when the navigation is finished on both browser + // and renderer sides. std::vector<DidFinishFirstNavigationCallback> on_did_finish_first_navigation_callbacks_; // Whether the first navigation was completed in both browser and renderer diff --git a/chromium/extensions/browser/app_window/app_window_geometry_cache.cc b/chromium/extensions/browser/app_window/app_window_geometry_cache.cc index 57db19c9d81..28cc2ad35b8 100644 --- a/chromium/extensions/browser/app_window/app_window_geometry_cache.cc +++ b/chromium/extensions/browser/app_window/app_window_geometry_cache.cc @@ -14,7 +14,6 @@ #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_prefs_factory.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/common/extension.h" @@ -31,8 +30,7 @@ namespace extensions { AppWindowGeometryCache::AppWindowGeometryCache(content::BrowserContext* context, ExtensionPrefs* prefs) : prefs_(prefs), - sync_delay_(base::TimeDelta::FromMilliseconds(kSyncTimeoutMilliseconds)), - extension_registry_observer_(this) { + sync_delay_(base::TimeDelta::FromMilliseconds(kSyncTimeoutMilliseconds)) { extension_registry_observer_.Add(ExtensionRegistry::Get(context)); } diff --git a/chromium/extensions/browser/app_window/app_window_geometry_cache.h b/chromium/extensions/browser/app_window/app_window_geometry_cache.h index a0b6b6f8a3c..6fe525be35a 100644 --- a/chromium/extensions/browser/app_window/app_window_geometry_cache.h +++ b/chromium/extensions/browser/app_window/app_window_geometry_cache.h @@ -20,6 +20,7 @@ #include "base/values.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" #include "components/keyed_service/core/keyed_service.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "ui/base/ui_base_types.h" #include "ui/gfx/geometry/rect.h" @@ -27,7 +28,6 @@ namespace extensions { class ExtensionPrefs; -class ExtensionRegistry; // A cache for persisted geometry of app windows, both to not have to wait // for IO when creating a new window, and to not cause IO on every window @@ -149,7 +149,7 @@ class AppWindowGeometryCache : public KeyedService, // Listen to extension load, unloaded notifications. ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; base::ObserverList<Observer>::Unchecked observers_; }; diff --git a/chromium/extensions/browser/app_window/app_window_registry.cc b/chromium/extensions/browser/app_window/app_window_registry.cc index cc11d60d96d..4aa4729b508 100644 --- a/chromium/extensions/browser/app_window/app_window_registry.cc +++ b/chromium/extensions/browser/app_window/app_window_registry.cc @@ -107,13 +107,6 @@ AppWindowRegistry::AppWindowList AppWindowRegistry::GetAppWindowsForApp( return app_windows; } -void AppWindowRegistry::CloseAllAppWindowsForApp(const std::string& app_id) { - const AppWindowList windows = GetAppWindowsForApp(app_id); - for (auto it = windows.cbegin(); it != windows.cend(); ++it) { - (*it)->GetBaseWindow()->Close(); - } -} - AppWindow* AppWindowRegistry::GetAppWindowForWebContents( const content::WebContents* web_contents) const { for (AppWindow* window : app_windows_) { diff --git a/chromium/extensions/browser/app_window/app_window_registry.h b/chromium/extensions/browser/app_window/app_window_registry.h index a6141971565..ac3da331b5d 100644 --- a/chromium/extensions/browser/app_window/app_window_registry.h +++ b/chromium/extensions/browser/app_window/app_window_registry.h @@ -80,9 +80,6 @@ class AppWindowRegistry : public KeyedService, AppWindowList GetAppWindowsForApp(const std::string& app_id) const; const AppWindowList& app_windows() const { return app_windows_; } - // Close all app windows associated with an app. - void CloseAllAppWindowsForApp(const std::string& app_id); - // Helper functions to find app windows with particular attributes. AppWindow* GetAppWindowForWebContents( const content::WebContents* web_contents) const; diff --git a/chromium/extensions/browser/app_window/native_app_window.h b/chromium/extensions/browser/app_window/native_app_window.h index f6f4ed5b215..8590dda1e3f 100644 --- a/chromium/extensions/browser/app_window/native_app_window.h +++ b/chromium/extensions/browser/app_window/native_app_window.h @@ -74,12 +74,6 @@ class NativeAppWindow : public ui::BaseWindow, // borders) and the content bounds, if any. virtual gfx::Insets GetFrameInsets() const = 0; - // Hide or show this window as part of hiding or showing the app. - // This may have different logic to Hide, Show, and ShowInactive as those are - // called via the AppWindow javascript API. - virtual void ShowWithApp() = 0; - virtual void HideWithApp() = 0; - // Returns the minimum size constraints of the content. virtual gfx::Size GetContentMinimumSize() const = 0; diff --git a/chromium/extensions/browser/blob_reader.cc b/chromium/extensions/browser/blob_reader.cc index f7cea575e99..aa7736843be 100644 --- a/chromium/extensions/browser/blob_reader.cc +++ b/chromium/extensions/browser/blob_reader.cc @@ -19,7 +19,7 @@ BlobReader::BlobReader(content::BrowserContext* browser_context, std::move(callback)) {} BlobReader::BlobReader(blink::mojom::BlobPtr blob, BlobReadCallback callback) - : callback_(std::move(callback)), blob_(std::move(blob)), binding_(this) { + : callback_(std::move(callback)), blob_(std::move(blob)) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); blob_.set_connection_error_handler( base::BindOnce(&BlobReader::Failed, base::Unretained(this))); @@ -46,13 +46,13 @@ void BlobReader::Start() { Failed(); return; } - blink::mojom::BlobReaderClientPtr client_ptr; - binding_.Bind(MakeRequest(&client_ptr)); if (read_range_) { blob_->ReadRange(read_range_->offset, read_range_->length, - std::move(producer_handle), std::move(client_ptr)); + std::move(producer_handle), + receiver_.BindNewPipeAndPassRemote()); } else { - blob_->ReadAll(std::move(producer_handle), std::move(client_ptr)); + blob_->ReadAll(std::move(producer_handle), + receiver_.BindNewPipeAndPassRemote()); } data_pipe_drainer_ = std::make_unique<mojo::DataPipeDrainer>(this, std::move(consumer_handle)); diff --git a/chromium/extensions/browser/blob_reader.h b/chromium/extensions/browser/blob_reader.h index 126d6c5d137..e0d72aa52b0 100644 --- a/chromium/extensions/browser/blob_reader.h +++ b/chromium/extensions/browser/blob_reader.h @@ -12,7 +12,7 @@ #include "base/callback.h" #include "base/macros.h" -#include "mojo/public/cpp/bindings/binding.h" +#include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/system/data_pipe_drainer.h" #include "third_party/blink/public/mojom/blob/blob.mojom.h" #include "url/gurl.h" @@ -64,7 +64,7 @@ class BlobReader : public blink::mojom::BlobReaderClient, }; base::Optional<Range> read_range_; - mojo::Binding<blink::mojom::BlobReaderClient> binding_; + mojo::Receiver<blink::mojom::BlobReaderClient> receiver_{this}; std::unique_ptr<mojo::DataPipeDrainer> data_pipe_drainer_; base::Optional<uint64_t> blob_length_; diff --git a/chromium/extensions/browser/computed_hashes.cc b/chromium/extensions/browser/computed_hashes.cc index c99e990f179..396d33e9bd4 100644 --- a/chromium/extensions/browser/computed_hashes.cc +++ b/chromium/extensions/browser/computed_hashes.cc @@ -12,12 +12,12 @@ #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" -#include "base/metrics/histogram_macros.h" #include "base/stl_util.h" #include "base/timer/elapsed_timer.h" #include "base/values.h" #include "crypto/secure_hash.h" #include "crypto/sha2.h" +#include "extensions/browser/content_verifier/scoped_uma_recorder.h" namespace extensions { @@ -32,38 +32,10 @@ const int kVersion = 2; namespace { -// Helper to record UMA for ComputedHashes::Reader::InitFromFile. -// Records failure UMA if RecordSuccess() isn't explicitly called. -class ScopedUMARecorder { - public: - ScopedUMARecorder() = default; - - ~ScopedUMARecorder() { - if (recorded_) - return; - RecordImpl(false); - } - - void RecordSuccess() { - recorded_ = true; - RecordImpl(true); - } - - private: - void RecordImpl(bool succeeded) { - UMA_HISTOGRAM_BOOLEAN( - "Extensions.ContentVerification.ComputedHashesReadResult", succeeded); - if (succeeded) { - UMA_HISTOGRAM_TIMES( - "Extensions.ContentVerification.ComputedHashesInitTime", - timer_.Elapsed()); - } - } - - bool recorded_ = false; - base::ElapsedTimer timer_; - DISALLOW_COPY_AND_ASSIGN(ScopedUMARecorder); -}; +const char kUMAComputedHashesReadResult[] = + "Extensions.ContentVerification.ComputedHashesReadResult"; +const char kUMAComputedHashesInitTime[] = + "Extensions.ContentVerification.ComputedHashesInitTime"; } // namespace @@ -74,7 +46,8 @@ ComputedHashes::Reader::~Reader() { } bool ComputedHashes::Reader::InitFromFile(const base::FilePath& path) { - ScopedUMARecorder uma_recorder; + ScopedUMARecorder<kUMAComputedHashesReadResult, kUMAComputedHashesInitTime> + uma_recorder; std::string contents; if (!base::ReadFileToString(path, &contents)) return false; diff --git a/chromium/extensions/browser/content_hash_fetcher.cc b/chromium/extensions/browser/content_hash_fetcher.cc index db1c8d02119..668874c5704 100644 --- a/chromium/extensions/browser/content_hash_fetcher.cc +++ b/chromium/extensions/browser/content_hash_fetcher.cc @@ -33,22 +33,21 @@ namespace extensions { namespace internals { -ContentHashFetcher::ContentHashFetcher(const ContentHash::ExtensionKey& key, - ContentHash::FetchParams fetch_params) - : extension_key_(key), - fetch_params_(std::move(fetch_params)), +ContentHashFetcher::ContentHashFetcher(ContentHash::FetchKey key) + : fetch_key_(std::move(key)), response_task_runner_(base::SequencedTaskRunnerHandle::Get()) {} void ContentHashFetcher::OnSimpleLoaderComplete( std::unique_ptr<std::string> response_body) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - VLOG(1) << "URLFetchComplete for " << extension_key_.extension_id + VLOG(1) << "URLFetchComplete for " << fetch_key_.extension_id << " is_success:" << !!response_body << " " - << fetch_params_.fetch_url.possibly_invalid_spec(); + << fetch_key_.fetch_url.possibly_invalid_spec(); DCHECK(hash_fetcher_callback_); response_task_runner_->PostTask( - FROM_HERE, base::BindOnce(std::move(hash_fetcher_callback_), - extension_key_, std::move(response_body))); + FROM_HERE, + base::BindOnce(std::move(hash_fetcher_callback_), std::move(fetch_key_), + std::move(response_body))); delete this; } @@ -82,14 +81,13 @@ void ContentHashFetcher::Start(HashFetcherCallback hash_fetcher_callback) { "extensions match what is distributed by the store." })"); auto resource_request = std::make_unique<network::ResourceRequest>(); - resource_request->url = fetch_params_.fetch_url; - resource_request->load_flags = net::LOAD_DO_NOT_SEND_COOKIES | - net::LOAD_DO_NOT_SAVE_COOKIES | - net::LOAD_DISABLE_CACHE; + resource_request->url = fetch_key_.fetch_url; + resource_request->load_flags = net::LOAD_DISABLE_CACHE; + resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; network::mojom::URLLoaderFactoryPtr url_loader_factory_ptr; url_loader_factory_ptr.Bind( - std::move(fetch_params_.url_loader_factory_ptr_info)); + std::move(fetch_key_.url_loader_factory_ptr_info)); simple_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); diff --git a/chromium/extensions/browser/content_hash_fetcher.h b/chromium/extensions/browser/content_hash_fetcher.h index 2a45cb992c1..8c8d64d5f3a 100644 --- a/chromium/extensions/browser/content_hash_fetcher.h +++ b/chromium/extensions/browser/content_hash_fetcher.h @@ -46,11 +46,10 @@ class ContentHashFetcher { // A callback for when fetch is complete. // The response contents is passed through std::unique_ptr<std::string>. using HashFetcherCallback = - base::OnceCallback<void(const ContentHash::ExtensionKey&, + base::OnceCallback<void(ContentHash::FetchKey, std::unique_ptr<std::string>)>; - ContentHashFetcher(const ContentHash::ExtensionKey& extension_key, - ContentHash::FetchParams fetch_params); + ContentHashFetcher(ContentHash::FetchKey fetch_key); // Note: |this| is deleted once OnSimpleLoaderComplete() completes. void Start(HashFetcherCallback hash_fetcher_callback); @@ -62,8 +61,7 @@ class ContentHashFetcher { void OnSimpleLoaderComplete(std::unique_ptr<std::string> response_body); - ContentHash::ExtensionKey extension_key_; - ContentHash::FetchParams fetch_params_; + ContentHash::FetchKey fetch_key_; HashFetcherCallback hash_fetcher_callback_; diff --git a/chromium/extensions/browser/content_hash_fetcher_unittest.cc b/chromium/extensions/browser/content_hash_fetcher_unittest.cc index 6e643d38cc3..c44e764373d 100644 --- a/chromium/extensions/browser/content_hash_fetcher_unittest.cc +++ b/chromium/extensions/browser/content_hash_fetcher_unittest.cc @@ -16,7 +16,7 @@ #include "base/task/post_task.h" #include "base/version.h" #include "content/public/browser/browser_thread.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/content_hash_fetcher.h" #include "extensions/browser/content_verifier/test_utils.h" #include "extensions/browser/extension_file_task_runner.h" @@ -51,12 +51,10 @@ class ContentHashWaiter { : reply_task_runner_(base::SequencedTaskRunnerHandle::Get()) {} std::unique_ptr<ContentHashFetcherResult> CreateAndWaitForCallback( - const ContentHash::ExtensionKey& key, - ContentHash::FetchParams fetch_params) { + ContentHash::FetchKey key) { GetExtensionFileTaskRunner()->PostTask( - FROM_HERE, - base::BindOnce(&ContentHashWaiter::CreateContentHash, - base::Unretained(this), key, std::move(fetch_params))); + FROM_HERE, base::BindOnce(&ContentHashWaiter::CreateContentHash, + base::Unretained(this), std::move(key))); run_loop_.Run(); DCHECK(result_); return std::move(result_); @@ -74,7 +72,7 @@ class ContentHashWaiter { } result_ = std::make_unique<ContentHashFetcherResult>(); - result_->extension_id = content_hash->extension_key().extension_id; + result_->extension_id = content_hash->extension_id(); result_->success = content_hash->succeeded(); result_->was_cancelled = was_cancelled; result_->mismatch_paths = content_hash->hash_mismatch_unix_paths(); @@ -82,10 +80,8 @@ class ContentHashWaiter { run_loop_.QuitWhenIdle(); } - void CreateContentHash(const ContentHash::ExtensionKey& key, - ContentHash::FetchParams fetch_params) { - ContentHash::Create(key, std::move(fetch_params), - ContentHash::IsCancelledCallback(), + void CreateContentHash(ContentHash::FetchKey key) { + ContentHash::Create(std::move(key), ContentHash::IsCancelledCallback(), base::BindOnce(&ContentHashWaiter::CreatedCallback, base::Unretained(this))); } @@ -103,7 +99,7 @@ class ContentHashFetcherTest : public ExtensionsTest { ContentHashFetcherTest() // We need a real IO thread to be able to entercept the network request // for the missing verified_contents.json file. - : ExtensionsTest(content::TestBrowserThreadBundle::REAL_IO_THREAD), + : ExtensionsTest(content::BrowserTaskEnvironment::REAL_IO_THREAD), test_shared_loader_factory_( base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &test_url_loader_factory_)) {} @@ -143,12 +139,10 @@ class ContentHashFetcherTest : public ExtensionsTest { url_loader_factory_ptr.PassInterface(); std::unique_ptr<ContentHashFetcherResult> result = - ContentHashWaiter().CreateAndWaitForCallback( - ContentHash::ExtensionKey(extension_->id(), extension_->path(), - extension_->version(), - delegate_->GetPublicKey()), - ContentHash::FetchParams(std::move(url_loader_factory_ptr_info), - fetch_url_)); + ContentHashWaiter().CreateAndWaitForCallback(ContentHash::FetchKey( + extension_->id(), extension_->path(), extension_->version(), + std::move(url_loader_factory_ptr_info), fetch_url_, + delegate_->GetPublicKey())); delegate_.reset(); diff --git a/chromium/extensions/browser/content_hash_reader.cc b/chromium/extensions/browser/content_hash_reader.cc index 9967783679f..391a84e3fdf 100644 --- a/chromium/extensions/browser/content_hash_reader.cc +++ b/chromium/extensions/browser/content_hash_reader.cc @@ -28,8 +28,6 @@ std::unique_ptr<const ContentHashReader> ContentHashReader::Create( const scoped_refptr<const ContentHash>& content_hash) { base::ElapsedTimer timer; - const ContentHash::ExtensionKey& extension_key = - content_hash->extension_key(); auto hash_reader = base::WrapUnique(new ContentHashReader); if (!content_hash->succeeded()) @@ -44,7 +42,7 @@ std::unique_ptr<const ContentHashReader> ContentHashReader::Create( // resource. if (!verified_contents.HasTreeHashRoot(relative_path)) { base::FilePath full_path = - extension_key.extension_root.Append(relative_path); + content_hash->extension_root().Append(relative_path); // Making a request to a non-existent file or to a directory should not // result in content verification failure. // TODO(proberge): This logic could be simplified if |content_verify_job| diff --git a/chromium/extensions/browser/content_verifier.cc b/chromium/extensions/browser/content_verifier.cc index 47ec494f50c..3cef80c7588 100644 --- a/chromium/extensions/browser/content_verifier.cc +++ b/chromium/extensions/browser/content_verifier.cc @@ -11,6 +11,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/files/file_path.h" +#include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" @@ -25,7 +26,6 @@ #include "extensions/browser/content_hash_reader.h" #include "extensions/browser/content_verifier_delegate.h" #include "extensions/browser/extension_file_task_runner.h" -#include "extensions/browser/extension_registry.h" #include "extensions/common/constants.h" #include "extensions/common/extension_l10n_util.h" #include "extensions/common/file_util.h" @@ -178,13 +178,12 @@ class ContentVerifier::HashHelper { // // Must be called on IO thread. The method responds through |callback| on IO // thread. - void GetContentHash(const ContentHash::ExtensionKey& extension_key, - ContentHash::FetchParams fetch_params, + void GetContentHash(ContentHash::FetchKey fetch_key, bool force_missing_computed_hashes_creation, ContentHashCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - auto callback_key = std::make_pair(extension_key.extension_id, - extension_key.extension_version); + auto callback_key = + std::make_pair(fetch_key.extension_id, fetch_key.extension_version); auto iter = callback_infos_.find(callback_key); if (iter != callback_infos_.end()) { iter->second.callbacks.push_back(std::move(callback)); @@ -203,8 +202,7 @@ class ContentVerifier::HashHelper { GetExtensionFileTaskRunner()->PostTask( FROM_HERE, base::BindOnce( - &HashHelper::ReadHashOnFileTaskRunner, extension_key, - std::move(fetch_params), + &HashHelper::ReadHashOnFileTaskRunner, std::move(fetch_key), base::BindRepeating(&IsCancelledChecker::IsCancelled, checker), base::BindOnce(&HashHelper::DidReadHash, weak_factory_.GetWeakPtr(), callback_key, checker))); @@ -280,18 +278,17 @@ class ContentVerifier::HashHelper { if (was_cancelled) return; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(std::move(callback), content_hash, was_cancelled)); } static void ReadHashOnFileTaskRunner( - const ContentHash::ExtensionKey& extension_key, - ContentHash::FetchParams fetch_params, + ContentHash::FetchKey fetch_key, const IsCancelledCallback& is_cancelled, ContentHash::CreatedCallback created_callback) { ContentHash::Create( - extension_key, std::move(fetch_params), is_cancelled, + std::move(fetch_key), is_cancelled, base::BindOnce(&HashHelper::ForwardToIO, std::move(created_callback))); } @@ -391,7 +388,7 @@ void ContentVerifier::SetObserverForTests(TestObserver* observer) { ContentVerifier::ContentVerifier( content::BrowserContext* context, std::unique_ptr<ContentVerifierDelegate> delegate) - : context_(context), delegate_(std::move(delegate)), observer_(this) {} + : context_(context), delegate_(std::move(delegate)) {} ContentVerifier::~ContentVerifier() { } @@ -404,9 +401,8 @@ void ContentVerifier::Start() { void ContentVerifier::Shutdown() { shutdown_on_ui_ = true; delegate_->Shutdown(); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&ContentVerifier::ShutdownOnIO, this)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&ContentVerifier::ShutdownOnIO, this)); observer_.RemoveAll(); } @@ -468,10 +464,9 @@ void ContentVerifier::GetContentHash( // TODO(lazyboy): Make CreateJobFor return a scoped_refptr instead of raw // pointer to fix this. Also add unit test to exercise this code path // explicitly. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(base::DoNothing::Once<ContentHashCallback>(), - std::move(callback))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(base::DoNothing::Once<ContentHashCallback>(), + std::move(callback))); return; } @@ -480,22 +475,17 @@ void ContentVerifier::GetContentHash( auto cache_iter = cache_.find(cache_key); if (cache_iter != cache_.end()) { // Currently, we expect |callback| to be called asynchronously. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(std::move(callback), cache_iter->second)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(std::move(callback), cache_iter->second)); return; } - ContentHash::ExtensionKey extension_key(extension_id, extension_root, - extension_version, - delegate_->GetPublicKey()); - ContentHash::FetchParams fetch_params = - GetFetchParams(extension_id, extension_version); + ContentHash::FetchKey fetch_key = + GetFetchKey(extension_id, extension_root, extension_version); // Since |shutdown_on_io_| = false, GetOrCreateHashHelper() must return // non-nullptr instance of HashHelper. GetOrCreateHashHelper()->GetContentHash( - extension_key, std::move(fetch_params), - force_missing_computed_hashes_creation, + std::move(fetch_key), force_missing_computed_hashes_creation, base::BindOnce(&ContentVerifier::DidGetContentHash, this, cache_key, std::move(callback))); } @@ -503,9 +493,9 @@ void ContentVerifier::GetContentHash( void ContentVerifier::VerifyFailed(const ExtensionId& extension_id, ContentVerifyJob::FailureReason reason) { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ContentVerifier::VerifyFailed, - this, extension_id, reason)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ContentVerifier::VerifyFailed, this, + extension_id, reason)); return; } if (shutdown_on_ui_) @@ -523,8 +513,9 @@ void ContentVerifier::OnExtensionLoaded( if (shutdown_on_ui_) return; - if (delegate_->ShouldBeVerified(*extension)) { - base::PostTaskWithTraits( + if (delegate_->GetVerifierSourceType(*extension) == + ContentVerifierDelegate::VerifierSourceType::SIGNED_HASHES) { + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&ContentVerifier::OnExtensionLoadedOnIO, this, extension->id(), extension->path(), extension->version(), @@ -553,10 +544,9 @@ void ContentVerifier::OnExtensionUnloaded( UnloadedExtensionReason reason) { if (shutdown_on_ui_) return; - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&ContentVerifier::OnExtensionUnloadedOnIO, this, - extension->id(), extension->version())); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&ContentVerifier::OnExtensionUnloadedOnIO, this, + extension->id(), extension->version())); } GURL ContentVerifier::GetSignatureFetchUrlForTest( @@ -595,7 +585,7 @@ void ContentVerifier::OnExtensionUnloadedOnIO( void ContentVerifier::OnFetchComplete( const scoped_refptr<const ContentHash>& content_hash) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - ExtensionId extension_id = content_hash->extension_key().extension_id; + ExtensionId extension_id = content_hash->extension_id(); if (g_content_verifier_test_observer) { g_content_verifier_test_observer->OnFetchComplete( extension_id, content_hash->has_verified_contents()); @@ -604,32 +594,35 @@ void ContentVerifier::OnFetchComplete( VLOG(1) << "OnFetchComplete " << extension_id << " success:" << content_hash->succeeded(); - const bool did_hash_mismatch = ShouldVerifyAnyPaths( - extension_id, content_hash->extension_key().extension_root, - content_hash->hash_mismatch_unix_paths()); + const bool did_hash_mismatch = + ShouldVerifyAnyPaths(extension_id, content_hash->extension_root(), + content_hash->hash_mismatch_unix_paths()); if (!did_hash_mismatch) return; VerifyFailed(extension_id, ContentVerifyJob::HASH_MISMATCH); } -ContentHash::FetchParams ContentVerifier::GetFetchParams( +ContentHash::FetchKey ContentVerifier::GetFetchKey( const ExtensionId& extension_id, + const base::FilePath& extension_root, const base::Version& extension_version) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // Create a new mojo pipe. It's safe to pass this around and use immediately, // even though it needs to finish initialization on the UI thread. network::mojom::URLLoaderFactoryPtr url_loader_factory_ptr; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&ContentVerifier::BindURLLoaderFactoryRequestOnUIThread, this, mojo::MakeRequest(&url_loader_factory_ptr))); network::mojom::URLLoaderFactoryPtrInfo url_loader_factory_info = url_loader_factory_ptr.PassInterface(); - return ContentHash::FetchParams( + return ContentHash::FetchKey( + extension_id, extension_root, extension_version, std::move(url_loader_factory_info), - delegate_->GetSignatureFetchUrl(extension_id, extension_version)); + delegate_->GetSignatureFetchUrl(extension_id, extension_version), + delegate_->GetPublicKey()); } void ContentVerifier::DidGetContentHash( diff --git a/chromium/extensions/browser/content_verifier.h b/chromium/extensions/browser/content_verifier.h index 2b3669b97d7..368c2bbf8ba 100644 --- a/chromium/extensions/browser/content_verifier.h +++ b/chromium/extensions/browser/content_verifier.h @@ -11,6 +11,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_refptr.h" #include "base/scoped_observer.h" #include "base/version.h" #include "content/public/browser/browser_thread.h" @@ -18,6 +19,7 @@ #include "extensions/browser/content_verifier_delegate.h" #include "extensions/browser/content_verifier_io_data.h" #include "extensions/browser/content_verify_job.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "services/network/public/cpp/shared_url_loader_factory.h" @@ -116,9 +118,9 @@ class ContentVerifier : public base::RefCountedThreadSafe<ContentVerifier>, class HashHelper; void OnFetchComplete(const scoped_refptr<const ContentHash>& content_hash); - ContentHash::FetchParams GetFetchParams( - const ExtensionId& extension_id, - const base::Version& extension_version); + ContentHash::FetchKey GetFetchKey(const ExtensionId& extension_id, + const base::FilePath& extension_root, + const base::Version& extension_version); void DidGetContentHash(const CacheKey& cache_key, ContentHashCallback orig_callback, @@ -179,7 +181,7 @@ class ContentVerifier : public base::RefCountedThreadSafe<ContentVerifier>, std::unique_ptr<ContentVerifierDelegate> delegate_; // For observing the ExtensionRegistry. - ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> observer_; + ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> observer_{this}; // Data that should only be used on the IO thread. ContentVerifierIOData io_data_; diff --git a/chromium/extensions/browser/content_verifier/content_hash.cc b/chromium/extensions/browser/content_verifier/content_hash.cc index 56a63cffcd6..b8c5af1e591 100644 --- a/chromium/extensions/browser/content_verifier/content_hash.cc +++ b/chromium/extensions/browser/content_verifier/content_hash.cc @@ -42,7 +42,7 @@ bool CreateDirAndWriteFile(const base::FilePath& destination, } std::unique_ptr<VerifiedContents> GetVerifiedContents( - const ContentHash::ExtensionKey& key, + const ContentHash::FetchKey& key, bool delete_invalid_file) { DCHECK(GetExtensionFileTaskRunner()->RunsTasksInCurrentSequence()); base::FilePath verified_contents_path = @@ -61,36 +61,29 @@ std::unique_ptr<VerifiedContents> GetVerifiedContents( } // namespace -ContentHash::ExtensionKey::ExtensionKey(const ExtensionId& extension_id, - const base::FilePath& extension_root, - const base::Version& extension_version, - ContentVerifierKey verifier_key) +ContentHash::FetchKey::FetchKey( + const ExtensionId& extension_id, + const base::FilePath& extension_root, + const base::Version& extension_version, + network::mojom::URLLoaderFactoryPtrInfo url_loader_factory_ptr_info, + const GURL& fetch_url, + ContentVerifierKey verifier_key) : extension_id(extension_id), extension_root(extension_root), extension_version(extension_version), + url_loader_factory_ptr_info(std::move(url_loader_factory_ptr_info)), + fetch_url(std::move(fetch_url)), verifier_key(verifier_key) {} -ContentHash::ExtensionKey::~ExtensionKey() = default; - -ContentHash::ExtensionKey::ExtensionKey( - const ContentHash::ExtensionKey& other) = default; +ContentHash::FetchKey::~FetchKey() = default; -ContentHash::ExtensionKey& ContentHash::ExtensionKey::operator=( - const ContentHash::ExtensionKey& other) = default; +ContentHash::FetchKey::FetchKey(ContentHash::FetchKey&& other) = default; -ContentHash::FetchParams::FetchParams( - network::mojom::URLLoaderFactoryPtrInfo url_loader_factory_ptr_info, - const GURL& fetch_url) - : url_loader_factory_ptr_info(std::move(url_loader_factory_ptr_info)), - fetch_url(fetch_url) {} -ContentHash::FetchParams::~FetchParams() = default; -ContentHash::FetchParams::FetchParams(FetchParams&&) = default; -ContentHash::FetchParams& ContentHash::FetchParams::operator=(FetchParams&&) = - default; +ContentHash::FetchKey& ContentHash::FetchKey::operator=( + ContentHash::FetchKey&& other) = default; // static -void ContentHash::Create(const ExtensionKey& key, - FetchParams fetch_params, +void ContentHash::Create(FetchKey key, const IsCancelledCallback& is_cancelled, CreatedCallback created_callback) { // Step 1/2: verified_contents.json: @@ -102,14 +95,15 @@ void ContentHash::Create(const ExtensionKey& key, if (!verified_contents) { // Fetch verified_contents.json and then respond. - FetchVerifiedContents(key, std::move(fetch_params), is_cancelled, + FetchVerifiedContents(std::move(key), is_cancelled, std::move(created_callback)); return; } // Step 2/2: computed_hashes.json: scoped_refptr<ContentHash> hash = - new ContentHash(key, std::move(verified_contents), nullptr); + new ContentHash(key.extension_id, key.extension_root, + std::move(verified_contents), nullptr); const bool did_fetch_verified_contents = false; hash->BuildComputedHashes(did_fetch_verified_contents, false /* force_build */, is_cancelled); @@ -135,10 +129,12 @@ const ComputedHashes::Reader& ContentHash::computed_hashes() const { } ContentHash::ContentHash( - const ExtensionKey& key, + const ExtensionId& id, + const base::FilePath& root, std::unique_ptr<VerifiedContents> verified_contents, std::unique_ptr<ComputedHashes::Reader> computed_hashes) - : key_(key), + : extension_id_(id), + extension_root_(root), verified_contents_(std::move(verified_contents)), computed_hashes_(std::move(computed_hashes)) { if (!verified_contents_) @@ -153,13 +149,12 @@ ContentHash::~ContentHash() = default; // static void ContentHash::FetchVerifiedContents( - const ContentHash::ExtensionKey& extension_key, - ContentHash::FetchParams fetch_params, + ContentHash::FetchKey key, const ContentHash::IsCancelledCallback& is_cancelled, ContentHash::CreatedCallback created_callback) { // |fetcher| deletes itself when it's done. internals::ContentHashFetcher* fetcher = - new internals::ContentHashFetcher(extension_key, std::move(fetch_params)); + new internals::ContentHashFetcher(std::move(key)); fetcher->Start(base::BindOnce(&ContentHash::DidFetchVerifiedContents, std::move(created_callback), is_cancelled)); } @@ -168,11 +163,11 @@ void ContentHash::FetchVerifiedContents( void ContentHash::DidFetchVerifiedContents( ContentHash::CreatedCallback created_callback, const ContentHash::IsCancelledCallback& is_cancelled, - const ContentHash::ExtensionKey& key, + ContentHash::FetchKey key, std::unique_ptr<std::string> fetched_contents) { if (!fetched_contents) { - ContentHash::DispatchFetchFailure(key, std::move(created_callback), - is_cancelled); + ContentHash::DispatchFetchFailure( + std::move(key), std::move(created_callback), is_cancelled); return; } @@ -185,8 +180,8 @@ void ContentHash::DidFetchVerifiedContents( base::Optional<base::Value> parsed = base::JSONReader::Read(*fetched_contents); if (!parsed) { - ContentHash::DispatchFetchFailure(key, std::move(created_callback), - is_cancelled); + ContentHash::DispatchFetchFailure( + std::move(key), std::move(created_callback), is_cancelled); return; } @@ -197,8 +192,8 @@ void ContentHash::DidFetchVerifiedContents( file_util::GetVerifiedContentsPath(key.extension_root); if (!CreateDirAndWriteFile(destination, *fetched_contents)) { LOG(ERROR) << "Error writing computed_hashes.json at " << destination; - ContentHash::DispatchFetchFailure(key, std::move(created_callback), - is_cancelled); + ContentHash::DispatchFetchFailure( + std::move(key), std::move(created_callback), is_cancelled); return; } @@ -211,14 +206,15 @@ void ContentHash::DidFetchVerifiedContents( false /* delete_invalid_file */); if (!verified_contents) { - ContentHash::DispatchFetchFailure(key, std::move(created_callback), - is_cancelled); + ContentHash::DispatchFetchFailure( + std::move(key), std::move(created_callback), is_cancelled); return; } RecordFetchResult(true); scoped_refptr<ContentHash> hash = - new ContentHash(key, std::move(verified_contents), nullptr); + new ContentHash(key.extension_id, key.extension_root, + std::move(verified_contents), nullptr); const bool did_fetch_verified_contents = true; hash->BuildComputedHashes(did_fetch_verified_contents, false /* force_build */, is_cancelled); @@ -227,13 +223,13 @@ void ContentHash::DidFetchVerifiedContents( // static void ContentHash::DispatchFetchFailure( - const ExtensionKey& key, + FetchKey key, CreatedCallback created_callback, const IsCancelledCallback& is_cancelled) { RecordFetchResult(false); // NOTE: bare new because ContentHash constructor is private. scoped_refptr<ContentHash> content_hash = - new ContentHash(key, nullptr, nullptr); + new ContentHash(key.extension_id, key.extension_root, nullptr, nullptr); std::move(created_callback) .Run(content_hash, is_cancelled && is_cancelled.Run()); } @@ -251,7 +247,7 @@ bool ContentHash::CreateHashes(const base::FilePath& hashes_file, if (!base::CreateDirectoryAndGetError(hashes_file.DirName(), nullptr)) return false; - base::FileEnumerator enumerator(key_.extension_root, true, /* recursive */ + base::FileEnumerator enumerator(extension_root_, true, /* recursive */ base::FileEnumerator::FILES); // First discover all the file paths and put them in a sorted set. SortedFilePathSet paths; @@ -274,7 +270,7 @@ bool ContentHash::CreateHashes(const base::FilePath& hashes_file, const base::FilePath& full_path = *i; base::FilePath relative_unix_path; - key_.extension_root.AppendRelativePath(full_path, &relative_unix_path); + extension_root_.AppendRelativePath(full_path, &relative_unix_path); relative_unix_path = relative_unix_path.NormalizePathSeparatorsTo('/'); if (!verified_contents_->HasTreeHashRoot(relative_unix_path)) @@ -314,7 +310,7 @@ void ContentHash::BuildComputedHashes(bool attempted_fetching_verified_contents, bool force_build, const IsCancelledCallback& is_cancelled) { base::FilePath computed_hashes_path = - file_util::GetComputedHashesPath(key_.extension_root); + file_util::GetComputedHashesPath(extension_root_); // Create computed_hashes.json file if any of the following is true: // - We just fetched and wrote a verified_contents.json (i.e. diff --git a/chromium/extensions/browser/content_verifier/content_hash.h b/chromium/extensions/browser/content_verifier/content_hash.h index 2cc33b709cc..6701d209027 100644 --- a/chromium/extensions/browser/content_verifier/content_hash.h +++ b/chromium/extensions/browser/content_verifier/content_hash.h @@ -48,35 +48,34 @@ namespace extensions { // take long time. This cancellation can be performed through |is_cancelled|. class ContentHash : public base::RefCountedThreadSafe<ContentHash> { public: - // Key to identify an extension. - struct ExtensionKey { + // Holds key to identify an extension for content verification, parameters to + // fetch verified_contents.json and other supplementary info. + struct FetchKey { + // Extension info. ExtensionId extension_id; base::FilePath extension_root; base::Version extension_version; - // The key used to validate verified_contents.json. - ContentVerifierKey verifier_key; - ExtensionKey(const ExtensionId& extension_id, - const base::FilePath& extension_root, - const base::Version& extension_version, - ContentVerifierKey verifier_key); - ~ExtensionKey(); + // Fetch parameters. + network::mojom::URLLoaderFactoryPtrInfo url_loader_factory_ptr_info; + GURL fetch_url; - ExtensionKey(const ExtensionKey& other); - ExtensionKey& operator=(const ExtensionKey& other); - }; + // The key used to validate verified_contents.json. + ContentVerifierKey verifier_key; - // Parameters to fetch verified_contents.json. - struct FetchParams { - FetchParams( + FetchKey( + const ExtensionId& extension_id, + const base::FilePath& extension_root, + const base::Version& extension_version, network::mojom::URLLoaderFactoryPtrInfo url_loader_factory_ptr_info, - const GURL& fetch_url); - ~FetchParams(); - FetchParams(FetchParams&&); - FetchParams& operator=(FetchParams&&); + const GURL& fetch_url, + ContentVerifierKey verifier_key); + ~FetchKey(); - network::mojom::URLLoaderFactoryPtrInfo url_loader_factory_ptr_info; - GURL fetch_url; + FetchKey(FetchKey&& other); + FetchKey& operator=(FetchKey&& other); + + DISALLOW_COPY_AND_ASSIGN(FetchKey); }; using IsCancelledCallback = base::RepeatingCallback<bool(void)>; @@ -90,8 +89,7 @@ class ContentHash : public base::RefCountedThreadSafe<ContentHash> { using CreatedCallback = base::OnceCallback<void(scoped_refptr<ContentHash> hash, bool was_cancelled)>; - static void Create(const ExtensionKey& key, - FetchParams fetch_params, + static void Create(FetchKey key, const IsCancelledCallback& is_cancelled, CreatedCallback created_callback); @@ -114,7 +112,8 @@ class ContentHash : public base::RefCountedThreadSafe<ContentHash> { const std::set<base::FilePath>& hash_mismatch_unix_paths() const { return hash_mismatch_unix_paths_; } - const ExtensionKey extension_key() const { return key_; } + const ExtensionId& extension_id() const { return extension_id_; } + const base::FilePath& extension_root() const { return extension_root_; } // Returns whether or not computed_hashes.json re-creation might be required // for |this| to succeed. @@ -138,22 +137,22 @@ class ContentHash : public base::RefCountedThreadSafe<ContentHash> { kSucceeded, }; - ContentHash(const ExtensionKey& key, + ContentHash(const ExtensionId& id, + const base::FilePath& root, std::unique_ptr<VerifiedContents> verified_contents, std::unique_ptr<ComputedHashes::Reader> computed_hashes); ~ContentHash(); - static void FetchVerifiedContents(const ExtensionKey& extension_key, - FetchParams fetch_params, + static void FetchVerifiedContents(FetchKey key, const IsCancelledCallback& is_cancelled, CreatedCallback created_callback); static void DidFetchVerifiedContents( CreatedCallback created_callback, const IsCancelledCallback& is_cancelled, - const ExtensionKey& key, + FetchKey key, std::unique_ptr<std::string> fetched_contents); - static void DispatchFetchFailure(const ExtensionKey& key, + static void DispatchFetchFailure(FetchKey key, CreatedCallback created_callback, const IsCancelledCallback& is_cancelled); @@ -177,7 +176,8 @@ class ContentHash : public base::RefCountedThreadSafe<ContentHash> { bool force_build, const IsCancelledCallback& is_cancelled); - ExtensionKey key_; + const ExtensionId extension_id_; + const base::FilePath extension_root_; Status status_ = Status::kInvalid; diff --git a/chromium/extensions/browser/content_verifier/scoped_uma_recorder.h b/chromium/extensions/browser/content_verifier/scoped_uma_recorder.h new file mode 100644 index 00000000000..b958223dbef --- /dev/null +++ b/chromium/extensions/browser/content_verifier/scoped_uma_recorder.h @@ -0,0 +1,45 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef EXTENSIONS_BROWSER_CONTENT_VERIFIER_SCOPED_UMA_RECORDER_H_ +#define EXTENSIONS_BROWSER_CONTENT_VERIFIER_SCOPED_UMA_RECORDER_H_ + +#include "base/metrics/histogram_macros.h" + +namespace extensions { + +// Helper to record UMA for ComputedHashes::Reader::InitFromFile and results of +// initializing verified_contents.json file. +// Records failure UMA if RecordSuccess() isn't explicitly called. +template <const char* RESULT_HISTOGRAM_NAME, const char* TIME_HISTOGRAM_NAME> +class ScopedUMARecorder { + public: + ScopedUMARecorder() = default; + + ~ScopedUMARecorder() { + if (recorded_) + return; + RecordImpl(false); + } + + void RecordSuccess() { + recorded_ = true; + RecordImpl(true); + } + + private: + void RecordImpl(bool succeeded) { + UMA_HISTOGRAM_BOOLEAN(RESULT_HISTOGRAM_NAME, succeeded); + if (succeeded) + UMA_HISTOGRAM_TIMES(TIME_HISTOGRAM_NAME, timer_.Elapsed()); + } + + bool recorded_ = false; + base::ElapsedTimer timer_; + DISALLOW_COPY_AND_ASSIGN(ScopedUMARecorder); +}; + +} // namespace extensions + +#endif // EXTENSIONS_BROWSER_CONTENT_VERIFIER_SCOPED_UMA_RECORDER_H_ diff --git a/chromium/extensions/browser/content_verifier/test_utils.cc b/chromium/extensions/browser/content_verifier/test_utils.cc index c99fc00d88e..6194b19b219 100644 --- a/chromium/extensions/browser/content_verifier/test_utils.cc +++ b/chromium/extensions/browser/content_verifier/test_utils.cc @@ -101,11 +101,10 @@ void TestContentVerifyJobObserver::JobFinished( const base::FilePath& relative_path, ContentVerifyJob::FailureReason failure_reason) { if (!content::BrowserThread::CurrentlyOn(creation_thread_)) { - base::PostTaskWithTraits( - FROM_HERE, {creation_thread_}, - base::BindOnce(&TestContentVerifyJobObserver::JobFinished, - base::Unretained(this), extension_id, relative_path, - failure_reason)); + base::PostTask(FROM_HERE, {creation_thread_}, + base::BindOnce(&TestContentVerifyJobObserver::JobFinished, + base::Unretained(this), extension_id, + relative_path, failure_reason)); return; } Result result = failure_reason == ContentVerifyJob::NONE ? Result::SUCCESS @@ -133,8 +132,9 @@ void TestContentVerifyJobObserver::JobFinished( MockContentVerifierDelegate::MockContentVerifierDelegate() = default; MockContentVerifierDelegate::~MockContentVerifierDelegate() = default; -bool MockContentVerifierDelegate::ShouldBeVerified(const Extension& extension) { - return true; +ContentVerifierDelegate::VerifierSourceType +MockContentVerifierDelegate::GetVerifierSourceType(const Extension& extension) { + return VerifierSourceType::SIGNED_HASHES; } ContentVerifierKey MockContentVerifierDelegate::GetPublicKey() { @@ -190,7 +190,7 @@ void VerifierObserver::WaitForFetchComplete(const ExtensionId& extension_id) { void VerifierObserver::OnFetchComplete(const ExtensionId& extension_id, bool success) { if (!content::BrowserThread::CurrentlyOn(creation_thread_)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {creation_thread_}, base::BindOnce(&VerifierObserver::OnFetchComplete, base::Unretained(this), extension_id, success)); diff --git a/chromium/extensions/browser/content_verifier/test_utils.h b/chromium/extensions/browser/content_verifier/test_utils.h index f6fd5871c87..c2bdf0e552f 100644 --- a/chromium/extensions/browser/content_verifier/test_utils.h +++ b/chromium/extensions/browser/content_verifier/test_utils.h @@ -111,7 +111,7 @@ class MockContentVerifierDelegate : public ContentVerifierDelegate { ~MockContentVerifierDelegate() override; // ContentVerifierDelegate: - bool ShouldBeVerified(const Extension& extension) override; + VerifierSourceType GetVerifierSourceType(const Extension& extension) override; ContentVerifierKey GetPublicKey() override; GURL GetSignatureFetchUrl(const ExtensionId& extension_id, const base::Version& version) override; diff --git a/chromium/extensions/browser/content_verifier_delegate.h b/chromium/extensions/browser/content_verifier_delegate.h index 8447423a984..f89399239d4 100644 --- a/chromium/extensions/browser/content_verifier_delegate.h +++ b/chromium/extensions/browser/content_verifier_delegate.h @@ -23,13 +23,29 @@ class Extension; // This is an interface for clients that want to use a ContentVerifier. class ContentVerifierDelegate { public: + // Types of hash sources used for content verification of an extension. + enum class VerifierSourceType { + // Use no hashes for verification, this effectively means the extension + // won't be verified. + NONE, + + // Use unsigned local hashes (computed_hashes.json) only and not + // verified_contents.json. + UNSIGNED_HASHES, + + // Use signed hashes (verified_contents.json). + // Note that GetPublicKey and GetSignatureFetchUrl would be required for + // this. + SIGNED_HASHES, + }; + virtual ~ContentVerifierDelegate() {} - // Returns whether or not resources from |extension| should be verified. - virtual bool ShouldBeVerified(const Extension& extension) = 0; + // Returns verification source type for |extension|. + virtual VerifierSourceType GetVerifierSourceType( + const Extension& extension) = 0; - // Returns the public key to use for validating signatures via the two out - // parameters. + // Returns the public key to use for validating signatures. virtual ContentVerifierKey GetPublicKey() = 0; // Returns a URL that can be used to fetch the verified_contents.json diff --git a/chromium/extensions/browser/content_verifier_unittest.cc b/chromium/extensions/browser/content_verifier_unittest.cc index 7d850b14a41..024b7f17ea1 100644 --- a/chromium/extensions/browser/content_verifier_unittest.cc +++ b/chromium/extensions/browser/content_verifier_unittest.cc @@ -7,7 +7,7 @@ #include "base/files/file_path.h" #include "base/path_service.h" #include "base/values.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/content_verifier.h" #include "extensions/browser/content_verifier/test_utils.h" diff --git a/chromium/extensions/browser/content_verify_job.cc b/chromium/extensions/browser/content_verify_job.cc index 0d5d54df6fc..036f14e3fd6 100644 --- a/chromium/extensions/browser/content_verify_job.cc +++ b/chromium/extensions/browser/content_verify_job.cc @@ -90,8 +90,9 @@ void ContentVerifyJob::DidGetContentHashOnIO( g_content_verify_job_test_observer->JobStarted(extension_id_, relative_path_); // Build |hash_reader_|. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&ContentHashReader::Create, relative_path_, content_hash), base::BindOnce(&ContentVerifyJob::OnHashesReady, this)); } diff --git a/chromium/extensions/browser/content_verify_job_unittest.cc b/chromium/extensions/browser/content_verify_job_unittest.cc index 52c873da77f..d10a558d509 100644 --- a/chromium/extensions/browser/content_verify_job_unittest.cc +++ b/chromium/extensions/browser/content_verify_job_unittest.cc @@ -12,8 +12,8 @@ #include "base/version.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/url_loader_interceptor.h" #include "extensions/browser/content_verifier.h" #include "extensions/browser/content_verifier/test_utils.h" @@ -159,10 +159,9 @@ class ContentVerifyJobUnittest : public ExtensionsTest { private: void StartJob(scoped_refptr<ContentVerifyJob> job) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&ContentVerifyJob::Start, job, - base::Unretained(content_verifier_.get()))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&ContentVerifyJob::Start, job, + base::Unretained(content_verifier_.get()))); } scoped_refptr<InfoMap> extension_info_map_; diff --git a/chromium/extensions/browser/declarative_user_script_manager.cc b/chromium/extensions/browser/declarative_user_script_manager.cc index 48075a5f523..84f7e266d5c 100644 --- a/chromium/extensions/browser/declarative_user_script_manager.cc +++ b/chromium/extensions/browser/declarative_user_script_manager.cc @@ -7,13 +7,12 @@ #include "content/public/browser/browser_context.h" #include "extensions/browser/declarative_user_script_manager_factory.h" #include "extensions/browser/declarative_user_script_master.h" -#include "extensions/browser/extension_registry.h" namespace extensions { DeclarativeUserScriptManager::DeclarativeUserScriptManager( content::BrowserContext* browser_context) - : browser_context_(browser_context), extension_registry_observer_(this) { + : browser_context_(browser_context) { extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context)); } diff --git a/chromium/extensions/browser/declarative_user_script_manager.h b/chromium/extensions/browser/declarative_user_script_manager.h index 83c481c75cd..5ebed9f45f9 100644 --- a/chromium/extensions/browser/declarative_user_script_manager.h +++ b/chromium/extensions/browser/declarative_user_script_manager.h @@ -10,6 +10,7 @@ #include "base/macros.h" #include "base/scoped_observer.h" #include "components/keyed_service/core/keyed_service.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/common/host_id.h" @@ -57,7 +58,7 @@ class DeclarativeUserScriptManager : public KeyedService, content::BrowserContext* browser_context_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; DISALLOW_COPY_AND_ASSIGN(DeclarativeUserScriptManager); }; diff --git a/chromium/extensions/browser/event_router.cc b/chromium/extensions/browser/event_router.cc index a7e96cd8ea4..96b9ab85ffe 100644 --- a/chromium/extensions/browser/event_router.cc +++ b/chromium/extensions/browser/event_router.cc @@ -26,7 +26,6 @@ #include "extensions/browser/events/lazy_event_dispatcher.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_prefs.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/process_manager.h" @@ -168,8 +167,6 @@ EventRouter::EventRouter(BrowserContext* browser_context, ExtensionPrefs* extension_prefs) : browser_context_(browser_context), extension_prefs_(extension_prefs), - extension_registry_observer_(this), - listeners_(this), lazy_event_dispatch_util_(browser_context_) { extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_)); } @@ -670,8 +667,8 @@ void EventRouter::DispatchEventToProcess( } if (!event->will_dispatch_callback.is_null() && - !event->will_dispatch_callback.Run(listener_context, extension, event, - listener_filter)) { + !event->will_dispatch_callback.Run(listener_context, target_context, + extension, event, listener_filter)) { return; } diff --git a/chromium/extensions/browser/event_router.h b/chromium/extensions/browser/event_router.h index 0a889e448c5..3b1f759d6fb 100644 --- a/chromium/extensions/browser/event_router.h +++ b/chromium/extensions/browser/event_router.h @@ -23,10 +23,12 @@ #include "extensions/browser/events/event_ack_data.h" #include "extensions/browser/events/lazy_event_dispatch_util.h" #include "extensions/browser/extension_event_histogram_value.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/browser/lazy_context_task_queue.h" #include "extensions/common/constants.h" #include "extensions/common/event_filtering_info.h" +#include "extensions/common/features/feature.h" #include "ipc/ipc_sender.h" #include "url/gurl.h" @@ -41,7 +43,6 @@ class RenderProcessHost; namespace extensions { class Extension; class ExtensionPrefs; -class ExtensionRegistry; struct Event; struct EventListenerInfo; @@ -379,9 +380,9 @@ class EventRouter : public KeyedService, ExtensionPrefs* const extension_prefs_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; - EventListenerMap listeners_; + EventListenerMap listeners_{this}; // Map from base event name to observer. using ObserverMap = std::unordered_map<std::string, Observer*>; @@ -405,6 +406,7 @@ struct Event { // given context and extension, and false otherwise. using WillDispatchCallback = base::RepeatingCallback<bool(content::BrowserContext*, + Feature::Context, const Extension*, Event*, const base::DictionaryValue*)>; diff --git a/chromium/extensions/browser/events/event_ack_data.cc b/chromium/extensions/browser/events/event_ack_data.cc index a6683526dc3..d9d0080dfa2 100644 --- a/chromium/extensions/browser/events/event_ack_data.cc +++ b/chromium/extensions/browser/events/event_ack_data.cc @@ -101,8 +101,7 @@ void EventAckData::IncrementInflightEvent( DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::ServiceWorkerContext::RunTask( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}), FROM_HERE, context, base::BindOnce(&EventAckData::StartExternalRequestOnIO, context, render_process_id, version_id, event_id, unacked_events_)); @@ -117,8 +116,7 @@ void EventAckData::DecrementInflightEvent( DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::ServiceWorkerContext::RunTask( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}), FROM_HERE, context, base::BindOnce(&EventAckData::FinishExternalRequestOnIO, context, render_process_id, version_id, event_id, unacked_events_, diff --git a/chromium/extensions/browser/events/lazy_event_dispatch_util.cc b/chromium/extensions/browser/events/lazy_event_dispatch_util.cc index 83d3637af4e..d0ab433f435 100644 --- a/chromium/extensions/browser/events/lazy_event_dispatch_util.cc +++ b/chromium/extensions/browser/events/lazy_event_dispatch_util.cc @@ -8,7 +8,6 @@ #include "content/public/browser/browser_context.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_prefs.h" -#include "extensions/browser/extension_registry.h" namespace extensions { @@ -27,7 +26,7 @@ const char kPrefPendingOnInstalledEventDispatchInfo[] = LazyEventDispatchUtil::LazyEventDispatchUtil( content::BrowserContext* browser_context) - : browser_context_(browser_context), extension_registry_observer_(this) { + : browser_context_(browser_context) { extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_)); } diff --git a/chromium/extensions/browser/events/lazy_event_dispatch_util.h b/chromium/extensions/browser/events/lazy_event_dispatch_util.h index 2606a73f099..3fe41e6e480 100644 --- a/chromium/extensions/browser/events/lazy_event_dispatch_util.h +++ b/chromium/extensions/browser/events/lazy_event_dispatch_util.h @@ -7,6 +7,7 @@ #include "base/observer_list.h" #include "base/scoped_observer.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/browser/uninstall_reason.h" @@ -64,7 +65,7 @@ class LazyEventDispatchUtil : public ExtensionRegistryObserver { content::BrowserContext* browser_context_; base::ObserverList<Observer>::Unchecked observers_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; DISALLOW_COPY_AND_ASSIGN(LazyEventDispatchUtil); }; diff --git a/chromium/extensions/browser/events/lazy_event_dispatcher.cc b/chromium/extensions/browser/events/lazy_event_dispatcher.cc index fe30c553c62..e4174bdb0ba 100644 --- a/chromium/extensions/browser/events/lazy_event_dispatcher.cc +++ b/chromium/extensions/browser/events/lazy_event_dispatcher.cc @@ -9,6 +9,7 @@ #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/lazy_context_id.h" +#include "extensions/common/features/feature.h" #include "extensions/common/manifest_handlers/incognito_info.h" using content::BrowserContext; @@ -84,7 +85,11 @@ bool LazyEventDispatcher::QueueEventDispatch( // last until the event is dispatched. if (!dispatched_event->will_dispatch_callback.is_null()) { if (!dispatched_event->will_dispatch_callback.Run( - dispatch_context.browser_context(), extension, + dispatch_context.browser_context(), + // The only lazy listeners belong to an extension's background + // context (either an event page or a service worker), which are + // always BLESSED_EXTENSION_CONTEXTs + extensions::Feature::BLESSED_EXTENSION_CONTEXT, extension, dispatched_event.get(), listener_filter)) { // The event has been canceled. return true; diff --git a/chromium/extensions/browser/extension_api_frame_id_map.cc b/chromium/extensions/browser/extension_api_frame_id_map.cc index 5fa0ca5e693..11732db812a 100644 --- a/chromium/extensions/browser/extension_api_frame_id_map.cc +++ b/chromium/extensions/browser/extension_api_frame_id_map.cc @@ -9,10 +9,9 @@ #include "base/bind.h" #include "base/logging.h" -#include "base/metrics/histogram_macros.h" #include "base/task/post_task.h" -#include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" @@ -41,16 +40,19 @@ ExtensionApiFrameIdMap::FrameData::FrameData() tab_id(extension_misc::kUnknownTabId), window_id(extension_misc::kUnknownWindowId) {} -ExtensionApiFrameIdMap::FrameData::FrameData(int frame_id, - int parent_frame_id, - int tab_id, - int window_id, - GURL last_committed_main_frame_url) +ExtensionApiFrameIdMap::FrameData::FrameData( + int frame_id, + int parent_frame_id, + int tab_id, + int window_id, + GURL last_committed_main_frame_url, + base::Optional<GURL> pending_main_frame_url) : frame_id(frame_id), parent_frame_id(parent_frame_id), tab_id(tab_id), window_id(window_id), - last_committed_main_frame_url(std::move(last_committed_main_frame_url)) {} + last_committed_main_frame_url(std::move(last_committed_main_frame_url)), + pending_main_frame_url(std::move(pending_main_frame_url)) {} ExtensionApiFrameIdMap::FrameData::~FrameData() = default; @@ -69,14 +71,6 @@ ExtensionApiFrameIdMap::RenderFrameIdKey::RenderFrameIdKey( : render_process_id(render_process_id), frame_routing_id(frame_routing_id) {} -ExtensionApiFrameIdMap::FrameDataCallbacks::FrameDataCallbacks() - : is_iterating(false) {} - -ExtensionApiFrameIdMap::FrameDataCallbacks::FrameDataCallbacks( - const FrameDataCallbacks& other) = default; - -ExtensionApiFrameIdMap::FrameDataCallbacks::~FrameDataCallbacks() {} - bool ExtensionApiFrameIdMap::RenderFrameIdKey::operator<( const RenderFrameIdKey& other) const { return std::tie(render_process_id, frame_routing_id) < @@ -89,14 +83,7 @@ bool ExtensionApiFrameIdMap::RenderFrameIdKey::operator==( frame_routing_id == other.frame_routing_id; } -ExtensionApiFrameIdMap::ExtensionApiFrameIdMap() { - // The browser client can be null in unittests. - if (ExtensionsBrowserClient::Get()) { - helper_ = - ExtensionsBrowserClient::Get()->CreateExtensionApiFrameIdMapHelper( - this); - } -} +ExtensionApiFrameIdMap::ExtensionApiFrameIdMap() {} ExtensionApiFrameIdMap::~ExtensionApiFrameIdMap() {} @@ -165,50 +152,40 @@ content::RenderFrameHost* ExtensionApiFrameIdMap::GetRenderFrameHostById( } ExtensionApiFrameIdMap::FrameData ExtensionApiFrameIdMap::KeyToValue( - const RenderFrameIdKey& key) const { + const RenderFrameIdKey& key, + bool require_live_frame) const { content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( key.render_process_id, key.frame_routing_id); - if (!rfh || !rfh->IsRenderFrameLive()) + if (!rfh || (require_live_frame && !rfh->IsRenderFrameLive())) return FrameData(); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(rfh); + base::Optional<GURL> pending_main_frame_url; + // Only set |pending_main_frame_url| if |rfh| is the main frame and a pending + // entry exists. + if (rfh->GetParent() == nullptr && web_contents && + web_contents->GetController().GetPendingEntry()) { + pending_main_frame_url = + web_contents->GetController().GetPendingEntry()->GetURL(); + } + // The RenderFrameHost may not have an associated WebContents in cases // such as interstitial pages. GURL last_committed_main_frame_url = web_contents ? web_contents->GetLastCommittedURL() : GURL(); int tab_id = extension_misc::kUnknownTabId; int window_id = extension_misc::kUnknownWindowId; - if (helper_) - helper_->PopulateTabData(rfh, &tab_id, &window_id); - return FrameData(GetFrameId(rfh), GetParentFrameId(rfh), tab_id, window_id, - std::move(last_committed_main_frame_url)); -} - -ExtensionApiFrameIdMap::FrameData ExtensionApiFrameIdMap::LookupFrameDataOnUI( - const RenderFrameIdKey& key, - bool check_deleted_frames) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - FrameDataMap::const_iterator frame_id_iter = frame_data_map_.find(key); - - if (frame_id_iter != frame_data_map_.end()) - return frame_id_iter->second; - - if (check_deleted_frames) { - frame_id_iter = deleted_frame_data_map_.find(key); - if (frame_id_iter != deleted_frame_data_map_.end()) - return frame_id_iter->second; + // The browser client can be null in unittests. + if (ExtensionsBrowserClient::Get()) { + ExtensionsBrowserClient::Get()->GetTabAndWindowIdForWebContents( + web_contents, &tab_id, &window_id); } - - FrameData data = KeyToValue(key); - // Don't save invalid values in the map. - if (data.frame_id != kInvalidFrameId) - frame_data_map_.insert({key, data}); - - return data; + return FrameData(GetFrameId(rfh), GetParentFrameId(rfh), tab_id, window_id, + std::move(last_committed_main_frame_url), + std::move(pending_main_frame_url)); } ExtensionApiFrameIdMap::FrameData ExtensionApiFrameIdMap::GetFrameData( @@ -216,18 +193,11 @@ ExtensionApiFrameIdMap::FrameData ExtensionApiFrameIdMap::GetFrameData( int render_frame_id) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); const RenderFrameIdKey key(render_process_id, render_frame_id); - return LookupFrameDataOnUI(key, true /* check_deleted_frames */); -} - -void ExtensionApiFrameIdMap::InitializeRenderFrameData( - content::RenderFrameHost* rfh) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(rfh); - DCHECK(rfh->IsRenderFrameLive()); + auto frame_id_iter = deleted_frame_data_map_.find(key); + if (frame_id_iter != deleted_frame_data_map_.end()) + return frame_id_iter->second; - const RenderFrameIdKey key(rfh->GetProcess()->GetID(), rfh->GetRoutingID()); - LookupFrameDataOnUI(key, false /* check_deleted_frames */); - DCHECK(frame_data_map_.find(key) != frame_data_map_.end()); + return KeyToValue(key, true /* require_live_frame */); } void ExtensionApiFrameIdMap::OnRenderFrameDeleted( @@ -240,12 +210,8 @@ void ExtensionApiFrameIdMap::OnRenderFrameDeleted( // requests made in window.onunload may start after this has been called. // Delay the RemoveFrameData() call, so we will still have the frame data // cached when the beacon request comes in. - auto iter = frame_data_map_.find(key); - if (iter == frame_data_map_.end()) - return; - - deleted_frame_data_map_.insert({key, iter->second}); - frame_data_map_.erase(key); + deleted_frame_data_map_.insert( + {key, KeyToValue(key, false /* require_live_frame */)}); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( @@ -255,110 +221,4 @@ void ExtensionApiFrameIdMap::OnRenderFrameDeleted( base::Unretained(this), key)); } -void ExtensionApiFrameIdMap::UpdateTabAndWindowId( - int tab_id, - int window_id, - content::RenderFrameHost* rfh) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(rfh); - const RenderFrameIdKey key(rfh->GetProcess()->GetID(), rfh->GetRoutingID()); - - // Only track FrameData for live render frames. - if (!rfh->IsRenderFrameLive()) { - return; - } - - auto iter = frame_data_map_.find(key); - // The FrameData for |rfh| should have already been initialized. - DCHECK(iter != frame_data_map_.end()); - iter->second.tab_id = tab_id; - iter->second.window_id = window_id; -} - -void ExtensionApiFrameIdMap::OnMainFrameReadyToCommitNavigation( - content::NavigationHandle* navigation_handle) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(navigation_handle->IsInMainFrame()); - - bool did_insert = false; - std::tie(std::ignore, did_insert) = - ready_to_commit_document_navigations_.insert(navigation_handle); - DCHECK(did_insert); - - content::RenderFrameHost* main_frame = - navigation_handle->GetRenderFrameHost(); - DCHECK(main_frame); - - // We only track live frames. - if (!main_frame->IsRenderFrameLive()) - return; - - const RenderFrameIdKey key(main_frame->GetProcess()->GetID(), - main_frame->GetRoutingID()); - auto iter = frame_data_map_.find(key); - - // We must have already cached the FrameData for this in - // InitializeRenderFrameHost. - DCHECK(iter != frame_data_map_.end()); - iter->second.pending_main_frame_url = navigation_handle->GetURL(); -} - -void ExtensionApiFrameIdMap::OnMainFrameDidFinishNavigation( - content::NavigationHandle* navigation_handle) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(navigation_handle->IsInMainFrame()); - - bool did_fire_ready_to_commit_navigation = - !!ready_to_commit_document_navigations_.erase(navigation_handle); - - // It's safe to call NavigationHandle::GetRenderFrameHost here iff the - // navigation committed or a ReadyToCommitNavigation event was dispatched for - // this navigation. - // Note a RenderFrameHost might not be associated with the NavigationHandle in - // WebContentsObserver::DidFinishNavigation. This might happen when the - // navigation doesn't commit which might happen for a variety of reasons like - // the network network request to fetch the navigation url failed, the - // navigation was cancelled, by say a NavigationThrottle etc. - // There's nothing to do if the RenderFrameHost can't be fetched for this - // navigation. - bool can_fetch_render_frame_host = - navigation_handle->HasCommitted() || did_fire_ready_to_commit_navigation; - if (!can_fetch_render_frame_host) - return; - - content::RenderFrameHost* main_frame = - navigation_handle->GetRenderFrameHost(); - DCHECK(main_frame); - - // We only track live frames. - if (!main_frame->IsRenderFrameLive()) - return; - - const RenderFrameIdKey key(main_frame->GetProcess()->GetID(), - main_frame->GetRoutingID()); - auto iter = frame_data_map_.find(key); - - // We must have already cached the FrameData for this in - // InitializeRenderFrameHost. - DCHECK(iter != frame_data_map_.end()); - iter->second.last_committed_main_frame_url = - main_frame->GetLastCommittedURL(); - iter->second.pending_main_frame_url = base::nullopt; -} - -bool ExtensionApiFrameIdMap::HasCachedFrameDataForTesting( - content::RenderFrameHost* rfh) const { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (!rfh) - return false; - - const RenderFrameIdKey key(rfh->GetProcess()->GetID(), rfh->GetRoutingID()); - return frame_data_map_.find(key) != frame_data_map_.end(); -} - -size_t ExtensionApiFrameIdMap::GetFrameDataCountForTesting() const { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - return frame_data_map_.size(); -} - } // namespace extensions diff --git a/chromium/extensions/browser/extension_api_frame_id_map.h b/chromium/extensions/browser/extension_api_frame_id_map.h index c8566e43de5..8eacf1aaea1 100644 --- a/chromium/extensions/browser/extension_api_frame_id_map.h +++ b/chromium/extensions/browser/extension_api_frame_id_map.h @@ -5,16 +5,13 @@ #ifndef EXTENSIONS_BROWSER_EXTENSION_API_FRAME_ID_MAP_H_ #define EXTENSIONS_BROWSER_EXTENSION_API_FRAME_ID_MAP_H_ -#include <list> #include <map> #include <memory> #include <set> -#include "base/callback.h" #include "base/lazy_instance.h" #include "base/macros.h" #include "base/optional.h" -#include "base/synchronization/lock.h" #include "url/gurl.h" namespace content { @@ -25,16 +22,6 @@ class WebContents; namespace extensions { -// TODO(http://crbug.com/980774): Investigate if this class and -// ExtensionApiFrameIdMap are still needed. -class ExtensionApiFrameIdMapHelper { - public: - virtual void PopulateTabData(content::RenderFrameHost* rfh, - int* tab_id_out, - int* window_id_out) = 0; - virtual ~ExtensionApiFrameIdMapHelper() {} -}; - // Extension frame IDs are exposed through the chrome.* APIs and have the // following characteristics: // - The top-level frame has ID 0. @@ -53,8 +40,6 @@ class ExtensionApiFrameIdMapHelper { // Unless stated otherwise, the methods can only be called on the UI thread. // // The non-static methods of this class use an internal cache. -// TODO(http://crbug.com/980774): This cache may not be necessary now that this -// is not accessed on IO. class ExtensionApiFrameIdMap { public: // The data for a RenderFrame. Every RenderFrameIdKey maps to a FrameData. @@ -64,7 +49,8 @@ class ExtensionApiFrameIdMap { int parent_frame_id, int tab_id, int window_id, - GURL last_committed_main_frame_url); + GURL last_committed_main_frame_url, + base::Optional<GURL> pending_main_frame_url); ~FrameData(); FrameData(const FrameData&); @@ -94,8 +80,6 @@ class ExtensionApiFrameIdMap { base::Optional<GURL> pending_main_frame_url; }; - using FrameDataCallback = base::Callback<void(const FrameData&)>; - // An invalid extension API frame ID. static const int kInvalidFrameId; @@ -124,39 +108,15 @@ class ExtensionApiFrameIdMap { int frame_id); // Retrieves the FrameData for a given |render_process_id| and - // |render_frame_id|. The map may be updated with the result if the map did - // not contain the FrameData before the lookup. If a RenderFrameHost is not - // found, then the map is not modified. + // |render_frame_id|. FrameData GetFrameData(int render_process_id, int render_frame_id) WARN_UNUSED_RESULT; - // Initializes the FrameData for the given |rfh|. - void InitializeRenderFrameData(content::RenderFrameHost* rfh); - - // Called when a render frame is deleted. Removes the FrameData mapping for - // the given render frame. + // Called when a render frame is deleted. Stores the FrameData for |rfh| in + // the deleted frames map so it can still be accessed for beacon requests. The + // FrameData will be removed later in a task. void OnRenderFrameDeleted(content::RenderFrameHost* rfh); - // Updates the tab and window id for the given RenderFrameHost if necessary. - void UpdateTabAndWindowId(int tab_id, - int window_id, - content::RenderFrameHost* rfh); - - // Called when WebContentsObserver::ReadyToCommitNavigation is dispatched for - // a main frame. - void OnMainFrameReadyToCommitNavigation( - content::NavigationHandle* navigation_handle); - - // Called when WebContentsObserver::DidFinishNavigation is dispatched for a - // main frame. - void OnMainFrameDidFinishNavigation( - content::NavigationHandle* navigation_handle); - - // Returns whether frame data for |rfh| is cached. - bool HasCachedFrameDataForTesting(content::RenderFrameHost* rfh) const; - - size_t GetFrameDataCountForTesting() const; - protected: friend struct base::LazyInstanceTraitsBase<ExtensionApiFrameIdMap>; @@ -175,54 +135,23 @@ class ExtensionApiFrameIdMap { bool operator==(const RenderFrameIdKey& other) const; }; - struct FrameDataCallbacks { - FrameDataCallbacks(); - FrameDataCallbacks(const FrameDataCallbacks& other); - ~FrameDataCallbacks(); - - // This is a std::list so that iterators are not invalidated when the list - // is modified during an iteration. - std::list<FrameDataCallback> callbacks; - - // To avoid re-entrant processing of callbacks. - bool is_iterating; - }; - using FrameDataMap = std::map<RenderFrameIdKey, FrameData>; - using FrameDataCallbacksMap = std::map<RenderFrameIdKey, FrameDataCallbacks>; ExtensionApiFrameIdMap(); - virtual ~ExtensionApiFrameIdMap(); + ~ExtensionApiFrameIdMap(); // Determines the value to be stored in |frame_data_map_| for a given key. + // If |require_live_frame| is true, FrameData will only // Returns empty FrameData when the corresponding RenderFrameHost is not - // alive. This method is only called when |key| is not in |frame_data_map_|. - // Virtual for testing. - virtual FrameData KeyToValue(const RenderFrameIdKey& key) const; - - // Looks up the data for the given |key| and adds it to the |frame_data_map_|. - // If |check_deleted_frames| is true, |deleted_frame_data_map_| will also be - // used. - FrameData LookupFrameDataOnUI(const RenderFrameIdKey& key, - bool check_deleted_frames); - - std::unique_ptr<ExtensionApiFrameIdMapHelper> helper_; - - // This map holds a mapping of render frame key to FrameData. - // TODO(http://crbug.com/980774): Investigate if this is still needed. - FrameDataMap frame_data_map_; + // alive and |require_live_frame| is true. + FrameData KeyToValue(const RenderFrameIdKey& key, + bool require_live_frame) const; // Holds mappings of render frame key to FrameData from frames that have been // recently deleted. These are kept for a short time so beacon requests that // continue after a frame is unloaded can access the FrameData. FrameDataMap deleted_frame_data_map_; - // The set of pending main frame navigations for which ReadyToCommitNavigation - // has been fired. Only used on the UI thread. This is needed to clear state - // set up in OnMainFrameReadyToCommitNavigation for navigations which - // eventually do not commit. - std::set<content::NavigationHandle*> ready_to_commit_document_navigations_; - DISALLOW_COPY_AND_ASSIGN(ExtensionApiFrameIdMap); }; diff --git a/chromium/extensions/browser/extension_event_histogram_value.h b/chromium/extensions/browser/extension_event_histogram_value.h index 665e37e154d..359ebe60718 100644 --- a/chromium/extensions/browser/extension_event_histogram_value.h +++ b/chromium/extensions/browser/extension_event_histogram_value.h @@ -363,7 +363,8 @@ enum HistogramValue { TYPES_CHROME_SETTING_ON_CHANGE = 342, DELETED_TYPES_PRIVATE_CHROME_DIRECT_SETTING_ON_CHANGE = 343, WEB_VIEW_INTERNAL_ON_MESSAGE = 344, - EXTENSION_VIEW_INTERNAL_ON_LOAD_COMMIT = 345, + // Obsolete: crbug.com/982858 + DELETED_EXTENSION_VIEW_INTERNAL_ON_LOAD_COMMIT = 345, RUNTIME_ON_REQUEST = 346, RUNTIME_ON_REQUEST_EXTERNAL = 347, CHROME_WEB_VIEW_INTERNAL_ON_CONTEXT_MENU_SHOW = 348, @@ -459,6 +460,7 @@ enum HistogramValue { ACTION_ON_CLICKED = 438, ACCESSIBILITY_PRIVATE_ON_SWITCH_ACCESS_COMMAND = 439, ACCESSIBILITY_PRIVATE_FIND_SCROLLABLE_BOUNDS_FOR_POINT = 440, + LOGIN_STATE_ON_SESSION_STATE_CHANGED = 441, // Last entry: Add new entries above, then run: // python tools/metrics/histograms/update_extension_histograms.py ENUM_BOUNDARY diff --git a/chromium/extensions/browser/extension_function.cc b/chromium/extensions/browser/extension_function.cc index 7bf63da6411..51ad258f8fe 100644 --- a/chromium/extensions/browser/extension_function.cc +++ b/chromium/extensions/browser/extension_function.cc @@ -254,22 +254,16 @@ bool ExtensionFunction::ignore_all_did_respond_for_testing_do_not_use = false; // static const char ExtensionFunction::kUnknownErrorDoNotUse[] = "Unknown error."; -// static -void ExtensionFunctionDeleteTraits::Destruct(const ExtensionFunction* x) { - x->Destruct(); -} - // Helper class to track the lifetime of ExtensionFunction's RenderFrameHost and // notify the function when it is deleted, as well as forwarding any messages // to the ExtensionFunction. -class UIThreadExtensionFunction::RenderFrameHostTracker +class ExtensionFunction::RenderFrameHostTracker : public content::WebContentsObserver { public: - explicit RenderFrameHostTracker(UIThreadExtensionFunction* function) + explicit RenderFrameHostTracker(ExtensionFunction* function) : content::WebContentsObserver( WebContents::FromRenderFrameHost(function->render_frame_host())), - function_(function) { - } + function_(function) {} private: // content::WebContentsObserver: @@ -285,34 +279,27 @@ class UIThreadExtensionFunction::RenderFrameHostTracker function_->OnMessageReceived(message); } - UIThreadExtensionFunction* function_; // Owns us. + ExtensionFunction* function_; // Owns us. DISALLOW_COPY_AND_ASSIGN(RenderFrameHostTracker); }; -ExtensionFunction::ExtensionFunction() - : request_id_(-1), - profile_id_(NULL), - name_(""), - has_callback_(false), - include_incognito_information_(false), - user_gesture_(false), - bad_message_(false), - histogram_value_(extensions::functions::UNKNOWN), - source_context_type_(Feature::UNSPECIFIED_CONTEXT), - source_process_id_(-1), - service_worker_version_id_(blink::mojom::kInvalidServiceWorkerVersionId), - did_respond_(false) {} +ExtensionFunction::ExtensionFunction() = default; ExtensionFunction::~ExtensionFunction() { -} - -UIThreadExtensionFunction* ExtensionFunction::AsUIThreadExtensionFunction() { - return NULL; -} + if (dispatcher() && (render_frame_host() || is_from_service_worker())) { + dispatcher()->OnExtensionFunctionCompleted( + extension(), is_from_service_worker(), name()); + } -IOThreadExtensionFunction* ExtensionFunction::AsIOThreadExtensionFunction() { - return NULL; + // The extension function should always respond to avoid leaks in the + // renderer, dangling callbacks, etc. The exception is if the system is + // shutting down. + extensions::ExtensionsBrowserClient* browser_client = + extensions::ExtensionsBrowserClient::Get(); + DCHECK(!browser_client || browser_client->IsShuttingDown() || did_respond() || + ignore_all_did_respond_for_testing_do_not_use) + << name(); } bool ExtensionFunction::HasPermission() const { @@ -323,6 +310,36 @@ bool ExtensionFunction::HasPermission() const { return availability.is_available(); } +bool ExtensionFunction::PreRunValidation(std::string* error) { + // TODO(crbug.com/625646) This is a partial fix to avoid crashes when certain + // extension functions run during shutdown. Browser or Notification creation + // for example create a ScopedKeepAlive, which hit a CHECK if the browser is + // shutting down. This fixes the current problem as the known issues happen + // through synchronous calls from Run(), but posted tasks will not be covered. + // A possible fix would involve refactoring ExtensionFunction: unrefcount + // here and use weakptrs for the tasks, then have it owned by something that + // will be destroyed naturally in the course of shut down. + if (extensions::ExtensionsBrowserClient::Get()->IsShuttingDown()) { + *error = "The browser is shutting down."; + return false; + } + + return true; +} + +ExtensionFunction::ResponseAction ExtensionFunction::RunWithValidation() { + std::string error; + if (!PreRunValidation(&error)) { + DCHECK(!error.empty() || bad_message_); + return bad_message_ ? ValidationFailure(this) : RespondNow(Error(error)); + } + return Run(); +} + +bool ExtensionFunction::ShouldSkipQuotaLimiting() const { + return false; +} + void ExtensionFunction::OnQuotaExceeded(const std::string& violation_error) { error_ = violation_error; SendResponseImpl(false); @@ -344,12 +361,44 @@ const std::string& ExtensionFunction::GetError() const { void ExtensionFunction::SetBadMessage() { bad_message_ = true; + + if (render_frame_host()) { + ReceivedBadMessage(render_frame_host()->GetProcess(), + is_from_service_worker() + ? extensions::bad_message::EFD_BAD_MESSAGE_WORKER + : extensions::bad_message::EFD_BAD_MESSAGE, + histogram_value()); + } } bool ExtensionFunction::user_gesture() const { return user_gesture_ || UserGestureForTests::GetInstance()->HaveGesture(); } +bool ExtensionFunction::OnMessageReceived(const IPC::Message& message) { + return false; +} + +void ExtensionFunction::SetRenderFrameHost( + content::RenderFrameHost* render_frame_host) { + // An extension function from Service Worker does not have a RenderFrameHost. + if (is_from_service_worker()) { + DCHECK(!render_frame_host); + return; + } + + DCHECK_NE(render_frame_host_ == nullptr, render_frame_host == nullptr); + render_frame_host_ = render_frame_host; + tracker_.reset(render_frame_host ? new RenderFrameHostTracker(this) + : nullptr); +} + +content::WebContents* ExtensionFunction::GetSenderWebContents() { + return render_frame_host_ + ? content::WebContents::FromRenderFrameHost(render_frame_host_) + : nullptr; +} + ExtensionFunction::ResponseValue ExtensionFunction::NoArguments() { return ResponseValue( new ArgumentListResponseValue(this, std::make_unique<base::ListValue>())); @@ -443,21 +492,11 @@ void ExtensionFunction::Respond(ResponseValue result) { SendResponseImpl(result->Apply()); } -bool ExtensionFunction::PreRunValidation(std::string* error) { - return true; -} - -ExtensionFunction::ResponseAction ExtensionFunction::RunWithValidation() { - std::string error; - if (!PreRunValidation(&error)) { - DCHECK(!error.empty() || bad_message_); - return bad_message_ ? ValidationFailure(this) : RespondNow(Error(error)); +void ExtensionFunction::OnResponded() { + if (!transferred_blob_uuids_.empty()) { + render_frame_host_->Send( + new ExtensionMsg_TransferBlobs(transferred_blob_uuids_)); } - return Run(); -} - -bool ExtensionFunction::ShouldSkipQuotaLimiting() const { - return false; } bool ExtensionFunction::HasOptionalArgument(size_t index) { @@ -465,6 +504,20 @@ bool ExtensionFunction::HasOptionalArgument(size_t index) { return args_->Get(index, &value) && !value->is_none(); } +void ExtensionFunction::WriteToConsole(blink::mojom::ConsoleMessageLevel level, + const std::string& message) { + // Only the main frame handles dev tools messages. + WebContents::FromRenderFrameHost(render_frame_host_) + ->GetMainFrame() + ->AddMessageToConsole(level, message); +} + +void ExtensionFunction::SetTransferredBlobUUIDs( + const std::vector<std::string>& blob_uuids) { + DCHECK(transferred_blob_uuids_.empty()); // Should only be called once. + transferred_blob_uuids_ = blob_uuids; +} + void ExtensionFunction::SendResponseImpl(bool success) { DCHECK(!response_callback_.is_null()); DCHECK(!did_respond_) << name_; @@ -487,137 +540,6 @@ void ExtensionFunction::SendResponseImpl(bool success) { OnResponded(); } -UIThreadExtensionFunction::UIThreadExtensionFunction() - : context_(nullptr), render_frame_host_(nullptr) {} - -UIThreadExtensionFunction::~UIThreadExtensionFunction() { - if (dispatcher() && (render_frame_host() || is_from_service_worker())) { - dispatcher()->OnExtensionFunctionCompleted( - extension(), is_from_service_worker(), name()); - } - - // The extension function should always respond to avoid leaks in the - // renderer, dangling callbacks, etc. The exception is if the system is - // shutting down. - // TODO(devlin): Duplicate this check in IOThreadExtensionFunction. It's - // tricky because checking IsShuttingDown has to be called from the UI thread. - extensions::ExtensionsBrowserClient* browser_client = - extensions::ExtensionsBrowserClient::Get(); - DCHECK(!browser_client || browser_client->IsShuttingDown() || did_respond() || - ignore_all_did_respond_for_testing_do_not_use) - << name(); -} - -UIThreadExtensionFunction* -UIThreadExtensionFunction::AsUIThreadExtensionFunction() { - return this; -} - -bool UIThreadExtensionFunction::PreRunValidation(std::string* error) { - if (!ExtensionFunction::PreRunValidation(error)) - return false; - - // TODO(crbug.com/625646) This is a partial fix to avoid crashes when certain - // extension functions run during shutdown. Browser or Notification creation - // for example create a ScopedKeepAlive, which hit a CHECK if the browser is - // shutting down. This fixes the current problem as the known issues happen - // through synchronous calls from Run(), but posted tasks will not be covered. - // A possible fix would involve refactoring ExtensionFunction: unrefcount - // here and use weakptrs for the tasks, then have it owned by something that - // will be destroyed naturally in the course of shut down. - if (extensions::ExtensionsBrowserClient::Get()->IsShuttingDown()) { - *error = "The browser is shutting down."; - return false; - } - - return true; -} - -void UIThreadExtensionFunction::SetBadMessage() { - ExtensionFunction::SetBadMessage(); - - if (render_frame_host()) { - ReceivedBadMessage(render_frame_host()->GetProcess(), - is_from_service_worker() - ? extensions::bad_message::EFD_BAD_MESSAGE_WORKER - : extensions::bad_message::EFD_BAD_MESSAGE, - histogram_value()); - } -} - -bool UIThreadExtensionFunction::OnMessageReceived(const IPC::Message& message) { - return false; -} - -void UIThreadExtensionFunction::Destruct() const { - BrowserThread::DeleteOnUIThread::Destruct(this); -} - -void UIThreadExtensionFunction::SetRenderFrameHost( - content::RenderFrameHost* render_frame_host) { - // An extension function from Service Worker does not have a RenderFrameHost. - if (is_from_service_worker()) { - DCHECK(!render_frame_host); - return; - } - - DCHECK_NE(render_frame_host_ == nullptr, render_frame_host == nullptr); - render_frame_host_ = render_frame_host; - tracker_.reset( - render_frame_host ? new RenderFrameHostTracker(this) : nullptr); -} - -content::WebContents* UIThreadExtensionFunction::GetSenderWebContents() { - return render_frame_host_ ? - content::WebContents::FromRenderFrameHost(render_frame_host_) : nullptr; -} - -void UIThreadExtensionFunction::OnResponded() { - if (!transferred_blob_uuids_.empty()) { - render_frame_host_->Send( - new ExtensionMsg_TransferBlobs(transferred_blob_uuids_)); - } -} - -void UIThreadExtensionFunction::SetTransferredBlobUUIDs( - const std::vector<std::string>& blob_uuids) { - DCHECK(transferred_blob_uuids_.empty()); // Should only be called once. - transferred_blob_uuids_ = blob_uuids; -} - -void UIThreadExtensionFunction::WriteToConsole( - blink::mojom::ConsoleMessageLevel level, - const std::string& message) { - // Only the main frame handles dev tools messages. - WebContents::FromRenderFrameHost(render_frame_host_) - ->GetMainFrame() - ->AddMessageToConsole(level, message); -} - -IOThreadExtensionFunction::IOThreadExtensionFunction() - : worker_thread_id_(extensions::kMainThreadId) {} - -IOThreadExtensionFunction::~IOThreadExtensionFunction() { -} - -IOThreadExtensionFunction* -IOThreadExtensionFunction::AsIOThreadExtensionFunction() { - return this; -} - -void IOThreadExtensionFunction::SetBadMessage() { - ExtensionFunction::SetBadMessage(); - if (ipc_sender_) { - ReceivedBadMessage( - static_cast<content::BrowserMessageFilter*>(ipc_sender_.get()), - extensions::bad_message::EFD_BAD_MESSAGE, histogram_value()); - } -} - -void IOThreadExtensionFunction::Destruct() const { - BrowserThread::DeleteOnIOThread::Destruct(this); -} - ExtensionFunction::ScopedUserGestureForTests::ScopedUserGestureForTests() { UserGestureForTests::GetInstance()->IncrementCount(); } diff --git a/chromium/extensions/browser/extension_function.h b/chromium/extensions/browser/extension_function.h index 437e9b0aa69..139992fa576 100644 --- a/chromium/extensions/browser/extension_function.h +++ b/chromium/extensions/browser/extension_function.h @@ -30,10 +30,6 @@ #include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom-forward.h" #include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom-forward.h" -class ExtensionFunction; -class UIThreadExtensionFunction; -class IOThreadExtensionFunction; - namespace base { class ListValue; class Value; @@ -47,7 +43,6 @@ class WebContents; namespace extensions { class ExtensionFunctionDispatcher; -class IOThreadExtensionMessageFilter; class QuotaLimitHeuristic; } @@ -75,13 +70,6 @@ class QuotaLimitHeuristic; #define EXTENSION_FUNCTION_PRERUN_VALIDATE(test) CHECK(test) #endif // NDEBUG -#define EXTENSION_FUNCTION_ERROR(error) \ - do { \ - error_ = error; \ - this->SetBadMessage(); \ - return ValidationFailure(this); \ - } while (0) - // Declares a callable extension function with the given |name|. You must also // supply a unique |histogramvalue| used for histograms of extension function // invocation (add new ones at the end of the enum in @@ -95,19 +83,11 @@ class QuotaLimitHeuristic; return extensions::functions::histogramvalue; \ } -// Traits that describe how ExtensionFunction should be deleted. This just calls -// the virtual "Destruct" method on ExtensionFunction, allowing derived classes -// to override the behavior. -struct ExtensionFunctionDeleteTraits { - public: - static void Destruct(const ExtensionFunction* x); -}; - // Abstract base class for extension functions the ExtensionFunctionDispatcher // knows how to dispatch to. -class ExtensionFunction - : public base::RefCountedThreadSafe<ExtensionFunction, - ExtensionFunctionDeleteTraits> { +class ExtensionFunction : public base::RefCountedThreadSafe< + ExtensionFunction, + content::BrowserThread::DeleteOnUIThread> { public: enum ResponseType { // The function has succeeded. @@ -125,9 +105,6 @@ class ExtensionFunction ExtensionFunction(); - virtual UIThreadExtensionFunction* AsUIThreadExtensionFunction(); - virtual IOThreadExtensionFunction* AsIOThreadExtensionFunction(); - // Returns true if the function has permission to run. // // This checks the Extension's permissions against the features declared in @@ -327,6 +304,40 @@ class ExtensionFunction bool did_respond() const { return did_respond_; } + // Called when a message was received. + // Should return true if it processed the message. + virtual bool OnMessageReceived(const IPC::Message& message); + + // Set the browser context which contains the extension that has originated + // this function call. + void set_browser_context(content::BrowserContext* context) { + context_ = context; + } + content::BrowserContext* browser_context() const { return context_; } + + void SetRenderFrameHost(content::RenderFrameHost* render_frame_host); + content::RenderFrameHost* render_frame_host() const { + return render_frame_host_; + } + + void set_dispatcher( + const base::WeakPtr<extensions::ExtensionFunctionDispatcher>& + dispatcher) { + dispatcher_ = dispatcher; + } + extensions::ExtensionFunctionDispatcher* dispatcher() const { + return dispatcher_.get(); + } + + void set_worker_thread_id(int worker_thread_id) { + worker_thread_id_ = worker_thread_id; + } + int worker_thread_id() const { return worker_thread_id_; } + + // Returns the web contents associated with the sending |render_frame_host_|. + // This can be null. + content::WebContents* GetSenderWebContents(); + // Sets did_respond_ to true so that the function won't DCHECK if it never // sends a response. Typically, this shouldn't be used, even in testing. It's // only for when you want to test functionality that doesn't exercise the @@ -426,25 +437,37 @@ class ExtensionFunction virtual ~ExtensionFunction(); - // Helper method for ExtensionFunctionDeleteTraits. Deletes this object. - virtual void Destruct() const = 0; - // Called after the response is sent, allowing the function to perform any // additional work or cleanup. - virtual void OnResponded() {} + virtual void OnResponded(); // Return true if the argument to this function at |index| was provided and // is non-null. bool HasOptionalArgument(size_t index); + // Emits a message to the extension's devtools console. + void WriteToConsole(blink::mojom::ConsoleMessageLevel level, + const std::string& message); + + // Sets the Blob UUIDs whose ownership is being transferred to the renderer. + void SetTransferredBlobUUIDs(const std::vector<std::string>& blob_uuids); + // The extension that called this function. scoped_refptr<const extensions::Extension> extension_; // The arguments to the API. Only non-null if argument were specified. std::unique_ptr<base::ListValue> args_; + // The BrowserContext of this function's extension. + // TODO(devlin): Grr... protected members. Move this to be private. + content::BrowserContext* context_ = nullptr; + private: + friend struct content::BrowserThread::DeleteOnThread< + content::BrowserThread::UI>; + friend class base::DeleteHelper<ExtensionFunction>; friend class ResponseValueObject; + class RenderFrameHostTracker; // Call with true to indicate success, false to indicate failure. If this // failed, |error_| should be set. @@ -465,133 +488,64 @@ class ExtensionFunction ResponseCallback response_callback_; // Id of this request, used to map the response back to the caller. - int request_id_; + int request_id_ = -1; // The id of the profile of this function's extension. - void* profile_id_; + void* profile_id_ = nullptr; // The name of this function. - const char* name_; + const char* name_ = nullptr; // The URL of the frame which is making this request GURL source_url_; // True if the js caller provides a callback function to receive the response // of this call. - bool has_callback_; + bool has_callback_ = false; // True if this callback should include information from incognito contexts // even if our profile_ is non-incognito. Note that in the case of a "split" // mode extension, this will always be false, and we will limit access to // data from within the same profile_ (either incognito or not). - bool include_incognito_information_; + bool include_incognito_information_ = false; // True if the call was made in response of user gesture. - bool user_gesture_; + bool user_gesture_ = false; // Any class that gets a malformed message should set this to true before // returning. Usually we want to kill the message sending process. - bool bad_message_; + bool bad_message_ = false; // The sample value to record with the histogram API when the function // is invoked. - extensions::functions::HistogramValue histogram_value_; + extensions::functions::HistogramValue histogram_value_ = + extensions::functions::UNKNOWN; // The type of the JavaScript context where this call originated. - extensions::Feature::Context source_context_type_; + extensions::Feature::Context source_context_type_ = + extensions::Feature::UNSPECIFIED_CONTEXT; // The process ID of the page that triggered this function call, or -1 // if unknown. - int source_process_id_; + int source_process_id_ = -1; // If this ExtensionFunction was called by an extension Service Worker, then // this contains the worker's version id. - int64_t service_worker_version_id_; + int64_t service_worker_version_id_ = + blink::mojom::kInvalidServiceWorkerVersionId; // The response type of the function, if the response has been sent. std::unique_ptr<ResponseType> response_type_; // Whether this function has responded. // TODO(devlin): Replace this with response_type_ != null. - bool did_respond_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionFunction); -}; - -// Extension functions that run on the UI thread. Most functions fall into -// this category. -class UIThreadExtensionFunction : public ExtensionFunction { - public: - UIThreadExtensionFunction(); - - UIThreadExtensionFunction* AsUIThreadExtensionFunction() override; - - bool PreRunValidation(std::string* error) override; - void SetBadMessage() final; - - // Called when a message was received. - // Should return true if it processed the message. - virtual bool OnMessageReceived(const IPC::Message& message); - - // Set the browser context which contains the extension that has originated - // this function call. - void set_browser_context(content::BrowserContext* context) { - context_ = context; - } - content::BrowserContext* browser_context() const { return context_; } - - void SetRenderFrameHost(content::RenderFrameHost* render_frame_host); - content::RenderFrameHost* render_frame_host() const { - return render_frame_host_; - } - - void set_dispatcher(const base::WeakPtr< - extensions::ExtensionFunctionDispatcher>& dispatcher) { - dispatcher_ = dispatcher; - } - extensions::ExtensionFunctionDispatcher* dispatcher() const { - return dispatcher_.get(); - } - - void set_worker_thread_id(int worker_thread_id) { - worker_thread_id_ = worker_thread_id; - } - int worker_thread_id() const { return worker_thread_id_; } - - // Returns the web contents associated with the sending |render_frame_host_|. - // This can be null. - content::WebContents* GetSenderWebContents(); - - protected: - // Emits a message to the extension's devtools console. - void WriteToConsole(blink::mojom::ConsoleMessageLevel level, - const std::string& message); - - friend struct content::BrowserThread::DeleteOnThread< - content::BrowserThread::UI>; - friend class base::DeleteHelper<UIThreadExtensionFunction>; - - ~UIThreadExtensionFunction() override; - - void OnResponded() override; - - // Sets the Blob UUIDs whose ownership is being transferred to the renderer. - void SetTransferredBlobUUIDs(const std::vector<std::string>& blob_uuids); - - // The BrowserContext of this function's extension. - // TODO(devlin): Grr... protected members. Move this to be private. - content::BrowserContext* context_; - - private: - class RenderFrameHostTracker; - - void Destruct() const override; + bool did_respond_ = false; // The dispatcher that will service this extension function call. base::WeakPtr<extensions::ExtensionFunctionDispatcher> dispatcher_; // The RenderFrameHost we will send responses to. - content::RenderFrameHost* render_frame_host_; + content::RenderFrameHost* render_frame_host_ = nullptr; std::unique_ptr<RenderFrameHostTracker> tracker_; @@ -600,63 +554,7 @@ class UIThreadExtensionFunction : public ExtensionFunction { int worker_thread_id_ = -1; - DISALLOW_COPY_AND_ASSIGN(UIThreadExtensionFunction); -}; - -// Extension functions that run on the IO thread. This type of function avoids -// a roundtrip to and from the UI thread (because communication with the -// extension process happens on the IO thread). It's intended to be used when -// performance is critical (e.g. the webRequest API which can block network -// requests). Generally, UIThreadExtensionFunction is more appropriate and will -// be easier to use and interface with the rest of the browser. -// To use this, specify `"forIOThread": true` in the function's schema. -// TODO(http://crbug.com/980774): Remove this as it is no longer used. Also -// remove "forIOThread" support in JSON. -class IOThreadExtensionFunction : public ExtensionFunction { - public: - IOThreadExtensionFunction(); - - IOThreadExtensionFunction* AsIOThreadExtensionFunction() override; - void SetBadMessage() final; - - void set_ipc_sender( - base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender) { - ipc_sender_ = ipc_sender; - } - - base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender_weak() - const { - return ipc_sender_; - } - - void set_worker_thread_id(int worker_thread_id) { - worker_thread_id_ = worker_thread_id; - } - int worker_thread_id() const { return worker_thread_id_; } - - void set_extension_info_map(const extensions::InfoMap* extension_info_map) { - extension_info_map_ = extension_info_map; - } - const extensions::InfoMap* extension_info_map() const { - return extension_info_map_.get(); - } - - protected: - friend struct content::BrowserThread::DeleteOnThread< - content::BrowserThread::IO>; - friend class base::DeleteHelper<IOThreadExtensionFunction>; - - ~IOThreadExtensionFunction() override; - - void Destruct() const override; - - private: - base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender_; - int worker_thread_id_; - - scoped_refptr<const extensions::InfoMap> extension_info_map_; - - DISALLOW_COPY_AND_ASSIGN(IOThreadExtensionFunction); + DISALLOW_COPY_AND_ASSIGN(ExtensionFunction); }; #endif // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_ diff --git a/chromium/extensions/browser/extension_function_dispatcher.cc b/chromium/extensions/browser/extension_function_dispatcher.cc index f63b7d3c006..24b3892d2c3 100644 --- a/chromium/extensions/browser/extension_function_dispatcher.cc +++ b/chromium/extensions/browser/extension_function_dispatcher.cc @@ -13,6 +13,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/process/process.h" @@ -67,16 +68,6 @@ bool IsRequestFromServiceWorker( blink::mojom::kInvalidServiceWorkerVersionId; } -// Separate copy of ExtensionAPI used for IO thread extension functions. We need -// this because ExtensionAPI has mutable data. It should be possible to remove -// this once all the extension APIs are updated to the feature system. -struct Static { - Static() : api(ExtensionAPI::CreateWithDefaultConfiguration()) {} - std::unique_ptr<ExtensionAPI> api; -}; -base::LazyInstance<Static>::DestructorAtExit g_global_io_data = - LAZY_INSTANCE_INITIALIZER; - void CommonResponseCallback(IPC::Sender* ipc_sender, int routing_id, int worker_thread_id, @@ -104,23 +95,10 @@ void CommonResponseCallback(IPC::Sender* ipc_sender, } } -void IOThreadResponseCallback( - const base::WeakPtr<IOThreadExtensionMessageFilter>& ipc_sender, - int routing_id, - int worker_thread_id, - int request_id, - ExtensionFunction::ResponseType type, - const base::ListValue& results, - const std::string& error) { - if (!ipc_sender.get()) - return; - - CommonResponseCallback(ipc_sender.get(), routing_id, worker_thread_id, - request_id, type, results, error); -} - } // namespace +// TODO(http://crbug.com/980774): Simplify this or change the name now that +// IOThreadExtensionFunction is gone. class ExtensionFunctionDispatcher::UIThreadResponseCallbackWrapper : public content::WebContentsObserver { public: @@ -232,9 +210,8 @@ class ExtensionFunctionDispatcher::UIThreadWorkerResponseCallbackWrapper } base::WeakPtr<ExtensionFunctionDispatcher> dispatcher_; - ScopedObserver<content::RenderProcessHost, - UIThreadWorkerResponseCallbackWrapper> - observer_; + ScopedObserver<content::RenderProcessHost, content::RenderProcessHostObserver> + observer_{this}; content::RenderProcessHost* const render_process_host_; const int worker_thread_id_; base::WeakPtrFactory<UIThreadWorkerResponseCallbackWrapper> weak_ptr_factory_{ @@ -273,109 +250,6 @@ ExtensionFunctionDispatcher::Delegate::GetVisibleWebContents() const { return GetAssociatedWebContents(); } -// static -void ExtensionFunctionDispatcher::DoDispatchOnIOThread( - InfoMap* extension_info_map, - void* profile_id, - int render_process_id, - base::WeakPtr<IOThreadExtensionMessageFilter> ipc_sender, - const ExtensionHostMsg_Request_Params& params, - const ExtensionFunction::ResponseCallback& callback) { - const Extension* extension = - extension_info_map->extensions().GetByID(params.extension_id); - - scoped_refptr<ExtensionFunction> function( - CreateExtensionFunction(params, - extension, - render_process_id, - extension_info_map->process_map(), - g_global_io_data.Get().api.get(), - profile_id, - callback)); - if (!function.get()) - return; - - IOThreadExtensionFunction* function_io = - function->AsIOThreadExtensionFunction(); - if (!function_io) { - NOTREACHED(); - return; - } - function_io->set_ipc_sender(ipc_sender); - function_io->set_worker_thread_id(params.worker_thread_id); - function_io->set_service_worker_version_id(params.service_worker_version_id); - function_io->set_extension_info_map(extension_info_map); - if (extension) { - function->set_include_incognito_information( - extension_info_map->CanCrossIncognito(extension)); - } - - if (!CheckPermissions(function.get(), params, callback)) - return; - - if (!extension) { - // Skip all of the UMA, quota, event page, activity logging stuff if there - // isn't an extension, e.g. if the function call was from WebUI. - function->RunWithValidation()->Execute(); - return; - } - - QuotaService* quota = extension_info_map->GetQuotaService(); - std::string violation_error = quota->Assess(extension->id(), - function.get(), - ¶ms.arguments, - base::TimeTicks::Now()); - if (violation_error.empty()) { - NotifyApiFunctionCalled(extension->id(), params.name, params.arguments, - static_cast<content::BrowserContext*>(profile_id)); - base::UmaHistogramSparse("Extensions.FunctionCalls", - function->histogram_value()); - base::ElapsedTimer timer; - function->RunWithValidation()->Execute(); - // TODO(devlin): Once we have a baseline metric for how long functions take, - // we can create a handful of buckets and record the function name so that - // we can find what the fastest/slowest are. - // Note: Many functions execute finish asynchronously, so this time is not - // always a representation of total time taken. See also - // Extensions.Functions.TotalExecutionTime. - UMA_HISTOGRAM_TIMES("Extensions.Functions.SynchronousExecutionTime", - timer.Elapsed()); - } else { - function->OnQuotaExceeded(violation_error); - } -} - -// static -void ExtensionFunctionDispatcher::DispatchOnIOThread( - InfoMap* extension_info_map, - void* profile_id, - int render_process_id, - base::WeakPtr<IOThreadExtensionMessageFilter> ipc_sender, - int routing_id, - const ExtensionHostMsg_Request_Params& params) { - ExtensionFunction::ResponseCallback callback( - base::BindRepeating(&IOThreadResponseCallback, ipc_sender, routing_id, - kMainThreadId, params.request_id)); - - DoDispatchOnIOThread(extension_info_map, profile_id, render_process_id, - ipc_sender, params, callback); -} - -// static -void ExtensionFunctionDispatcher::DispatchOnIOThreadForServiceWorker( - InfoMap* extension_info_map, - void* profile_id, - int render_process_id, - base::WeakPtr<IOThreadExtensionMessageFilter> ipc_sender, - const ExtensionHostMsg_Request_Params& params) { - ExtensionFunction::ResponseCallback callback(base::BindRepeating( - &IOThreadResponseCallback, ipc_sender, MSG_ROUTING_NONE, - params.worker_thread_id, params.request_id)); - - DoDispatchOnIOThread(extension_info_map, profile_id, render_process_id, - ipc_sender, params, callback); -} - ExtensionFunctionDispatcher::ExtensionFunctionDispatcher( content::BrowserContext* browser_context) : browser_context_(browser_context), delegate_(nullptr) {} @@ -446,8 +320,6 @@ void ExtensionFunctionDispatcher::DispatchWithCallbackInternal( content::RenderFrameHost* render_frame_host, int render_process_id, const ExtensionFunction::ResponseCallback& callback) { - // TODO(yzshen): There is some shared logic between this method and - // DispatchOnIOThread(). It is nice to deduplicate. ProcessMap* process_map = ProcessMap::Get(browser_context_); if (!process_map) return; @@ -463,27 +335,20 @@ void ExtensionFunctionDispatcher::DispatchWithCallbackInternal( if (render_frame_host) DCHECK_EQ(render_process_id, render_frame_host->GetProcess()->GetID()); - scoped_refptr<ExtensionFunction> function(CreateExtensionFunction( + scoped_refptr<ExtensionFunction> function = CreateExtensionFunction( params, extension, render_process_id, *process_map, - ExtensionAPI::GetSharedInstance(), browser_context_, callback)); + ExtensionAPI::GetSharedInstance(), browser_context_, callback); if (!function.get()) return; - UIThreadExtensionFunction* function_ui = - function->AsUIThreadExtensionFunction(); - if (!function_ui) { - NOTREACHED(); - return; - } - function_ui->set_worker_thread_id(params.worker_thread_id); + function->set_worker_thread_id(params.worker_thread_id); if (IsRequestFromServiceWorker(params)) { - function_ui->set_service_worker_version_id( - params.service_worker_version_id); + function->set_service_worker_version_id(params.service_worker_version_id); } else { - function_ui->SetRenderFrameHost(render_frame_host); + function->SetRenderFrameHost(render_frame_host); } - function_ui->set_dispatcher(AsWeakPtr()); - function_ui->set_browser_context(browser_context_); + function->set_dispatcher(AsWeakPtr()); + function->set_browser_context(browser_context_); if (extension && ExtensionsBrowserClient::Get()->CanExtensionCrossIncognito( extension, browser_context_)) { @@ -556,11 +421,6 @@ void ExtensionFunctionDispatcher::DispatchWithCallbackInternal( if (!IsRequestFromServiceWorker(params)) { // Increment ref count for non-service worker extension API. Ref count for // service worker extension API is handled separately on IO thread via IPC. - - // We only adjust the keepalive count for UIThreadExtensionFunction for - // now, largely for simplicity's sake. This is OK because currently, only - // the webRequest API uses IOThreadExtensionFunction, and that API is not - // compatible with lazy background pages. process_manager->IncrementLazyKeepaliveCount( function->extension(), Activity::API_FUNCTION, function->name()); } @@ -622,7 +482,8 @@ bool ExtensionFunctionDispatcher::CheckPermissions( } // static -ExtensionFunction* ExtensionFunctionDispatcher::CreateExtensionFunction( +scoped_refptr<ExtensionFunction> +ExtensionFunctionDispatcher::CreateExtensionFunction( const ExtensionHostMsg_Request_Params& params, const Extension* extension, int requesting_process_id, @@ -630,7 +491,7 @@ ExtensionFunction* ExtensionFunctionDispatcher::CreateExtensionFunction( ExtensionAPI* api, void* profile_id, const ExtensionFunction::ResponseCallback& callback) { - ExtensionFunction* function = + scoped_refptr<ExtensionFunction> function = ExtensionFunctionRegistry::GetInstance().NewFunction(params.name); if (!function) { LOG(ERROR) << "Unknown Extension API - " << params.name; diff --git a/chromium/extensions/browser/extension_function_dispatcher.h b/chromium/extensions/browser/extension_function_dispatcher.h index 08f11f8ebe7..6721cee02ae 100644 --- a/chromium/extensions/browser/extension_function_dispatcher.h +++ b/chromium/extensions/browser/extension_function_dispatcher.h @@ -25,14 +25,9 @@ namespace extensions { class Extension; class ExtensionAPI; -class InfoMap; -class IOThreadExtensionMessageFilter; class ProcessMap; class WindowController; -// A factory function for creating new ExtensionFunction instances. -typedef ExtensionFunction* (*ExtensionFunctionFactory)(); - // ExtensionFunctionDispatcher receives requests to execute functions from // Chrome extensions running in a RenderFrameHost and dispatches them to the // appropriate handler. It lives entirely on the UI thread. @@ -70,25 +65,6 @@ class ExtensionFunctionDispatcher virtual ~Delegate() {} }; - // Dispatches an IO-thread extension function. Only used for specific - // functions that must be handled on the IO-thread. - static void DispatchOnIOThread( - InfoMap* extension_info_map, - void* profile_id, - int render_process_id, - base::WeakPtr<IOThreadExtensionMessageFilter> ipc_sender, - int routing_id, - const ExtensionHostMsg_Request_Params& params); - - // Dispatches an IO-thread extension function for a Service Worker. Only - // used for specific functions that must be handled on the IO-thread. - static void DispatchOnIOThreadForServiceWorker( - InfoMap* extension_info_map, - void* profile_id, - int render_process_id, - base::WeakPtr<IOThreadExtensionMessageFilter> ipc_sender, - const ExtensionHostMsg_Request_Params& params); - // Public constructor. Callers must ensure that: // - This object outlives any RenderFrameHost's passed to created // ExtensionFunctions. @@ -137,14 +113,6 @@ class ExtensionFunctionDispatcher // |ui_thread_response_callback_wrappers_for_worker_|. struct WorkerResponseCallbackMapKey; - static void DoDispatchOnIOThread( - InfoMap* extension_info_map, - void* profile_id, - int render_process_id, - base::WeakPtr<IOThreadExtensionMessageFilter> ipc_sender, - const ExtensionHostMsg_Request_Params& params, - const ExtensionFunction::ResponseCallback& callback); - // Helper to check whether an ExtensionFunction has the required permissions. // This should be called after the function is fully initialized. // If the check fails, |callback| is run with an access-denied error and false @@ -157,7 +125,7 @@ class ExtensionFunctionDispatcher // Helper to create an ExtensionFunction to handle the function given by // |params|. Can be called on any thread. // Does not set subclass properties, or include_incognito. - static ExtensionFunction* CreateExtensionFunction( + static scoped_refptr<ExtensionFunction> CreateExtensionFunction( const ExtensionHostMsg_Request_Params& params, const Extension* extension, int requesting_process_id, diff --git a/chromium/extensions/browser/extension_function_histogram_value.h b/chromium/extensions/browser/extension_function_histogram_value.h index b86a97c3001..1ca160f53a5 100644 --- a/chromium/extensions/browser/extension_function_histogram_value.h +++ b/chromium/extensions/browser/extension_function_histogram_value.h @@ -285,8 +285,8 @@ enum HistogramValue { WEBNAVIGATION_GETFRAME = 224, EXPERIMENTAL_POWER_RELEASEKEEPAWAKE = 225, APP_CURRENTWINDOWINTERNAL_SETICON = 226, - PUSHMESSAGING_GETCHANNELID = 227, - EXPERIMENTAL_INFOBARS_SHOW = 228, + DELETED_PUSHMESSAGING_GETCHANNELID = 227, + DELETED_EXPERIMENTAL_INFOBARS_SHOW = 228, INPUT_IME_SETCANDIDATEWINDOWPROPERTIES = 229, METRICSPRIVATE_RECORDPERCENTAGE = 230, TYPES_CHROMESETTING_GET = 231, @@ -363,7 +363,7 @@ enum HistogramValue { MANAGEMENT_LAUNCHAPP = 302, INPUT_IME_CLEARCOMPOSITION = 303, ALARMS_GETALL = 304, - DIAL_DISCOVERNOW = 305, + DELETED_DIAL_DISCOVERNOW = 305, TYPES_CHROMESETTING_SET = 306, BROWSERACTION_SETICON = 307, ACCESSIBILITY_PRIVATE_SETACCESSIBILITYENABLED = 308, @@ -579,7 +579,7 @@ enum HistogramValue { DELETED_SYSTEM_STORAGE_REMOVEALLAVAILABLECAPACITYWATCHES = 518, DOWNLOADS_REMOVEFILE = 519, DOWNLOADS_SHOWDEFAULTFOLDER = 520, - INFOBARS_SHOW = 521, + DELETED_INFOBARS_SHOW = 521, DOWNLOADS_SETSHELFENABLED = 522, IMAGEWRITER_WRITEFROMURL = 523, IMAGEWRITER_WRITEFROMFILE = 524, @@ -912,14 +912,14 @@ enum HistogramValue { DELETED_EXPERIENCESAMPLINGPRIVATE_GETBROWSERINFO = 851, DELETED_EASYUNLOCKPRIVATE_SEEKBLUETOOTHDEVICEBYADDRESS = 852, DELETED_EASYUNLOCKPRIVATE_GETSTRINGS = 853, - NOTIFICATIONPROVIDER_SENDONCLEAR = 854, - NOTIFICATIONPROVIDER_NOTIFYONCLEARED = 855, - NOTIFICATIONPROVIDER_NOTIFYONCLICKED = 856, - NOTIFICATIONPROVIDER_NOTIFYONBUTTONCLICKED = 857, - NOTIFICATIONPROVIDER_NOTIFYONPERMISSIONLEVELCHANGED = 858, - NOTIFICATIONPROVIDER_NOTIFYONSHOWSETTINGS = 859, - NOTIFICATIONPROVIDER_GETNOTIFIER = 860, - NOTIFICATIONPROVIDER_GETALLNOTIFIERS = 861, + DELETED_NOTIFICATIONPROVIDER_SENDONCLEAR = 854, + DELETED_NOTIFICATIONPROVIDER_NOTIFYONCLEARED = 855, + DELETED_NOTIFICATIONPROVIDER_NOTIFYONCLICKED = 856, + DELETED_NOTIFICATIONPROVIDER_NOTIFYONBUTTONCLICKED = 857, + DELETED_NOTIFICATIONPROVIDER_NOTIFYONPERMISSIONLEVELCHANGED = 858, + DELETED_NOTIFICATIONPROVIDER_NOTIFYONSHOWSETTINGS = 859, + DELETED_NOTIFICATIONPROVIDER_GETNOTIFIER = 860, + DELETED_NOTIFICATIONPROVIDER_GETALLNOTIFIERS = 861, DELETED_GCDPRIVATE_GETPREFETCHEDWIFINAMELIST = 862, GUESTVIEWINTERNAL_SETAUTOSIZE = 863, DELETED_COPRESENCEPRIVATE_SENDFOUND = 864, @@ -932,8 +932,8 @@ enum HistogramValue { DELETED_FILESYSTEM_UNOBSERVEENTRY = 871, DELETED_FILESYSTEM_GETOBSERVEDENTRIES = 872, BROWSINGDATA_REMOVESERVICEWORKERS = 873, - USBPRIVATE_GETDEVICES = 874, - USBPRIVATE_GETDEVICEINFO = 875, + DELETED_USBPRIVATE_GETDEVICES = 874, + DELETED_USBPRIVATE_GETDEVICEINFO = 875, DELETED_EASYUNLOCKPRIVATE_UPDATESCREENLOCKSTATE = 876, CAST_CHANNEL_GETLOGS = 877, DELETED_EASYUNLOCKPRIVATE_SETPERMITACCESS = 878, @@ -986,8 +986,8 @@ enum HistogramValue { HOTWORDPRIVATE_SETAUDIOHISTORYENABLED = 925, HOTWORDPRIVATE_GETAUDIOHISTORYENABLED = 926, DELETED_APP_CURRENTWINDOWINTERNAL_SETINTERCEPTALLKEYS = 927, - LAUNCHERPAGE_PUSHSUBPAGE = 928, - LAUNCHERPAGE_SHOW = 929, + DELETED_LAUNCHERPAGE_PUSHSUBPAGE = 928, + DELETED_LAUNCHERPAGE_SHOW = 929, AUTOTESTPRIVATE_SETTOUCHPADSENSITIVITY = 930, AUTOTESTPRIVATE_SETTAPTOCLICK = 931, AUTOTESTPRIVATE_SETTHREEFINGERCLICK = 932, @@ -999,7 +999,7 @@ enum HistogramValue { DELETED_COPRESENCEENDPOINTS_DESTROYLOCALENDPOINT = 938, DELETED_COPRESENCEENDPOINTS_SEND = 939, DELETED_INLINE_INSTALL_PRIVATE_INSTALL = 940, - LAUNCHERPAGE_SETENABLED = 941, + DELETED_LAUNCHERPAGE_SETENABLED = 941, DELETED_CRYPTOTOKENPRIVATE_REQUESTPERMISSION = 942, BLUETOOTHPRIVATE_DISCONNECTALL = 943, FILEMANAGERPRIVATEINTERNAL_GETMIMETYPE = 944, @@ -1012,7 +1012,7 @@ enum HistogramValue { FILESYSTEMPROVIDER_GET = 951, FILEMANAGERPRIVATE_SEARCHFILESBYHASHES = 952, DELETED_EASYUNLOCKPRIVATE_SHOWERRORBUBBLE = 953, - EXTENSIONVIEWINTERNAL_NAVIGATE = 954, + DELETED_EXTENSIONVIEWINTERNAL_NAVIGATE = 954, // Obsolete: crbug.com/982858 NETWORKING_CONFIG_SETNETWORKFILTER = 955, NETWORKING_CONFIG_FINISHAUTHENTICATION = 956, PLATFORMKEYSINTERNAL_SELECTCLIENTCERTIFICATES = 957, @@ -1098,7 +1098,7 @@ enum HistogramValue { PASSWORDSPRIVATE_REMOVESAVEDPASSWORD = 1037, PASSWORDSPRIVATE_REMOVEPASSWORDEXCEPTION = 1038, PASSWORDSPRIVATE_REQUESTPLAINTEXTPASSWORD = 1039, - LAUNCHERPAGE_HIDE = 1040, + DELETED_LAUNCHERPAGE_HIDE = 1040, PLATFORMKEYS_VERIFYTLSSERVERCERTIFICATE = 1041, DEVELOPERPRIVATE_SETSHORTCUTHANDLINGSUSPENDED = 1042, DEVELOPERPRIVATE_UPDATEEXTENSIONCOMMAND = 1043, @@ -1113,8 +1113,8 @@ enum HistogramValue { WEBCAMPRIVATE_CLOSEWEBCAM = 1052, SERIAL_SETBREAK = 1053, SERIAL_CLEARBREAK = 1054, - EXTENSIONVIEWINTERNAL_LOADSRC = 1055, - EXTENSIONVIEWINTERNAL_PARSESRC = 1056, + DELETED_EXTENSIONVIEWINTERNAL_LOADSRC = 1055, // Obsolete: crbug.com/982858 + DELETED_EXTENSIONVIEWINTERNAL_PARSESRC = 1056, // Obsolete: crbug.com/982858 HID_GETUSERSELECTEDDEVICES = 1057, FILESYSTEMPROVIDERINTERNAL_GETACTIONSREQUESTEDSUCCESS = 1058, DASHBOARDPRIVATE_SHOWPERMISSIONPROMPTFORDELEGATEDBUNDLEINSTALL = 1059, @@ -1216,7 +1216,7 @@ enum HistogramValue { QUICKUNLOCKPRIVATE_GETCREDENTIALREQUIREMENTS = 1155, CLIPBOARD_SETIMAGEDATA = 1156, NETWORKINGPRIVATE_GETGLOBALPOLICY = 1157, - DIAL_FETCHDEVICEDESCRIPTION = 1158, + DELETED_DIAL_FETCHDEVICEDESCRIPTION = 1158, SYSTEM_DISPLAY_STARTCUSTOMTOUCHCALIBRATION = 1159, AUDIO_GETMUTE = 1160, AUDIO_SETMUTE = 1161, @@ -1238,7 +1238,7 @@ enum HistogramValue { MEDIAPERCEPTIONPRIVATE_SETSTATE = 1175, MEDIAPERCEPTIONPRIVATE_GETDIAGNOSTICS = 1176, NETWORKINGPRIVATE_GETCERTIFICATELISTS = 1177, - ACCESSIBILITY_PRIVATE_SETSWITCHACCESSKEYS = 1178, + DELETED_ACCESSIBILITY_PRIVATE_SETSWITCHACCESSKEYS = 1178, FEEDBACKPRIVATE_READLOGSOURCE = 1179, LOCKSCREENDATA_CREATE = 1180, LOCKSCREENDATA_GETALL = 1181, @@ -1408,7 +1408,7 @@ enum HistogramValue { BLUETOOTHPRIVATE_RECORDDEVICESELECTION = 1345, LOGIN_LAUNCHMANAGEDGUESTSESSION = 1346, LOGIN_EXITCURRENTSESSION = 1347, - LOGIN_ISRUNNINGINLOGINPROFILE = 1348, + DELETED_LOGIN_ISRUNNINGINLOGINPROFILE = 1348, LOGIN_FETCHDATAFORNEXTLOGINATTEMPT = 1349, ACTION_SETICON = 1350, AUTOTESTPRIVATE_GETALLENTERPRISEPOLICIES = 1351, @@ -1425,6 +1425,24 @@ enum HistogramValue { ACCESSIBILITY_PRIVATE_OPENSETTINGSSUBPAGE = 1362, ACTION_ENABLE = 1363, ACTION_DISABLE = 1364, + FILEMANAGERPRIVATEINTERNAL_IMPORTCROSTINIIMAGE = 1365, + AUTOTESTPRIVATE_GETSHELFITEMS = 1366, + MANAGEMENT_INSTALLREPLACEMENTANDROIDAPP = 1367, + MANAGEMENT_CANINSTALLREPLACEMENTANDROIDAPP = 1368, + AUTOTESTPRIVATE_REGISTERCOMPONENT = 1369, + LOGINSCREENSTORAGE_STOREPERSISTENTDATA = 1370, + LOGINSCREENSTORAGE_RETRIEVEPERSISTENTDATA = 1371, + LOGINSCREENSTORAGE_STORECREDENTIALS = 1372, + LOGINSCREENSTORAGE_RETRIEVECREDENTIALS = 1373, + AUTOTESTPRIVATE_GETARCAPPWINDOWSTATE = 1374, + AUTOTESTPRIVATE_GETARCAPPWINDOWINFO = 1375, + AUTOTESTPRIVATE_GETALLINSTALLEDAPPS = 1376, + AUTOTESTPRIVATE_SWAPWINDOWSINSPLITVIEW = 1377, + AUTOTESTPRIVATE_SETARCAPPWINDOWFOCUS = 1378, + LOGINSTATE_GETPROFILETYPE = 1379, + LOGINSTATE_GETSESSIONSTATE = 1380, + AUTOTESTPRIVATE_GETARCSTARTTIME = 1381, + AUTOTESTPRIVATE_SETOVERVIEWMODESTATE = 1382, // Last entry: Add new entries above, then run: // python tools/metrics/histograms/update_extension_histograms.py ENUM_BOUNDARY diff --git a/chromium/extensions/browser/extension_function_registry.cc b/chromium/extensions/browser/extension_function_registry.cc index f9a8d72c0e2..6b8fb3e4ab1 100644 --- a/chromium/extensions/browser/extension_function_registry.cc +++ b/chromium/extensions/browser/extension_function_registry.cc @@ -34,13 +34,13 @@ bool ExtensionFunctionRegistry::OverrideFunctionForTesting( return true; } -ExtensionFunction* ExtensionFunctionRegistry::NewFunction( +scoped_refptr<ExtensionFunction> ExtensionFunctionRegistry::NewFunction( const std::string& name) { auto iter = factories_.find(name); if (iter == factories_.end()) { return NULL; } - ExtensionFunction* function = iter->second.factory_(); + scoped_refptr<ExtensionFunction> function = iter->second.factory_(); function->set_name(iter->second.function_name_); function->set_histogram_value(iter->second.histogram_value_); return function; diff --git a/chromium/extensions/browser/extension_function_registry.h b/chromium/extensions/browser/extension_function_registry.h index 93b5411b096..0e265174340 100644 --- a/chromium/extensions/browser/extension_function_registry.h +++ b/chromium/extensions/browser/extension_function_registry.h @@ -9,17 +9,18 @@ #include <string> #include "base/macros.h" +#include "base/memory/scoped_refptr.h" #include "extensions/browser/extension_function_histogram_value.h" class ExtensionFunction; // A factory function for creating new ExtensionFunction instances. -using ExtensionFunctionFactory = ExtensionFunction* (*)(); +using ExtensionFunctionFactory = scoped_refptr<ExtensionFunction> (*)(); // Template for defining ExtensionFunctionFactory. template <class T> -ExtensionFunction* NewExtensionFunction() { - return new T(); +scoped_refptr<ExtensionFunction> NewExtensionFunction() { + return base::MakeRefCounted<T>(); } // Contains a list of all known extension functions and allows clients to @@ -54,7 +55,7 @@ class ExtensionFunctionRegistry { ExtensionFunctionFactory factory); // Factory method for the ExtensionFunction registered as 'name'. - ExtensionFunction* NewFunction(const std::string& name); + scoped_refptr<ExtensionFunction> NewFunction(const std::string& name); // Registers a new extension function. This will override any existing entry. void Register(const FactoryEntry& entry); diff --git a/chromium/extensions/browser/extension_navigation_throttle.cc b/chromium/extensions/browser/extension_navigation_throttle.cc index 880a1b8b25d..b4fa481e897 100644 --- a/chromium/extensions/browser/extension_navigation_throttle.cc +++ b/chromium/extensions/browser/extension_navigation_throttle.cc @@ -98,9 +98,8 @@ ExtensionNavigationThrottle::WillStartOrRedirectRequest() { guest_view::GuestViewBase* guest = guest_view::GuestViewBase::FromWebContents(web_contents); if (url_has_extension_scheme && guest) { - // This variant of this logic applies to PlzNavigate top-level - // navigations. It is performed for subresources, and for non-PlzNavigate - // top navigations, in url_request_util::AllowCrossRendererResourceLoad. + // This only handles top-level navigations. For subresources, is is done + // in url_request_util::AllowCrossRendererResourceLoad. const std::string& owner_extension_id = guest->owner_host(); const Extension* owner_extension = registry->enabled_extensions().GetByID(owner_extension_id); @@ -192,7 +191,7 @@ ExtensionNavigationThrottle::WillRedirectRequest() { ThrottleCheckResult result = WillStartOrRedirectRequest(); if (result.action() == BLOCK_REQUEST) { // TODO(nick): https://crbug.com/695421 means that BLOCK_REQUEST does not - // work here. Once PlzNavigate is enabled 100%, just return |result|. + // work here. Just return |result|. return CANCEL; } return result; diff --git a/chromium/extensions/browser/extension_navigation_ui_data.cc b/chromium/extensions/browser/extension_navigation_ui_data.cc index f6b0f034738..26e6f73b756 100644 --- a/chromium/extensions/browser/extension_navigation_ui_data.cc +++ b/chromium/extensions/browser/extension_navigation_ui_data.cc @@ -71,7 +71,8 @@ ExtensionNavigationUIData::ExtensionNavigationUIData( window_id, // The RenderFrameHost may not have an associated WebContents // in cases such as interstitial pages. - web_contents ? web_contents->GetLastCommittedURL() : GURL()) { + web_contents ? web_contents->GetLastCommittedURL() : GURL(), + base::nullopt /* pending_main_frame_url */) { WebViewGuest* web_view = WebViewGuest::FromWebContents(web_contents); if (web_view) { is_web_view_ = true; diff --git a/chromium/extensions/browser/extension_navigation_ui_data.h b/chromium/extensions/browser/extension_navigation_ui_data.h index 8998f5e7fdc..8d67981bd12 100644 --- a/chromium/extensions/browser/extension_navigation_ui_data.h +++ b/chromium/extensions/browser/extension_navigation_ui_data.h @@ -16,8 +16,8 @@ class NavigationHandle; namespace extensions { -// PlzNavigate: initialized on the UI thread for all navigations. A copy is used -// on the IO thread by the WebRequest API to access to the FrameData. +// Initialized on the UI thread for all navigations. A copy is used on the IO +// thread by the WebRequest API to access to the FrameData. class ExtensionNavigationUIData { public: ExtensionNavigationUIData(); diff --git a/chromium/extensions/browser/extension_prefs.cc b/chromium/extensions/browser/extension_prefs.cc index 23ff15507c4..4ee6dad4c47 100644 --- a/chromium/extensions/browser/extension_prefs.cc +++ b/chromium/extensions/browser/extension_prefs.cc @@ -31,6 +31,7 @@ #include "extensions/browser/extension_system.h" #include "extensions/browser/install_flag.h" #include "extensions/browser/pref_names.h" +#include "extensions/common/constants.h" #include "extensions/common/manifest.h" #include "extensions/common/permissions/permission_set.h" #include "extensions/common/permissions/permissions_info.h" @@ -137,6 +138,12 @@ constexpr const char kPrefUserDraggedApp[] = "user_dragged_app_ntp"; constexpr const char kPrefActivePermissions[] = "active_permissions"; constexpr const char kPrefGrantedPermissions[] = "granted_permissions"; +// A preference indicating if an extension should be granted all the requested +// host permissions without requiring explicit runtime permission from the user. +// The preference name is different for legacy reasons. +const char kGrantExtensionAllHostPermissions[] = + "extension_can_script_all_urls"; + // The set of permissions that were granted at runtime, rather than at install // time. This includes permissions granted through the permissions API and // runtime host permissions. @@ -798,12 +805,20 @@ void ExtensionPrefs::ClearInapplicableDisableReasonsForComponentExtension( disable_reason::DISABLE_UNSUPPORTED_REQUIREMENT | disable_reason::DISABLE_CORRUPTED; + // Allow the camera app to be disabled by extension policy. This is a + // temporary solution until there's a dedicated policy to disable the + // camera, at which point this should be removed. + // TODO(http://crbug.com/1002935) + int allowed_disable_reasons = kAllowDisableReasons; + if (component_extension_id == extension_misc::kCameraAppId) + allowed_disable_reasons |= disable_reason::DISABLE_BLOCKED_BY_POLICY; + // Some disable reasons incorrectly cause component extensions to never // activate on load. See https://crbug.com/946839 for more details on why we // do this. ModifyDisableReasons( component_extension_id, - kAllowDisableReasons & GetDisableReasons(component_extension_id), + allowed_disable_reasons & GetDisableReasons(component_extension_id), DISABLE_REASON_REPLACE); } @@ -890,10 +905,6 @@ bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const { return ext_prefs && IsBlacklistBitSet(ext_prefs); } -bool ExtensionPrefs::InsecureExtensionUpdatesEnabled() const { - return prefs_->GetBoolean(pref_names::kInsecureExtensionUpdatesEnabled); -} - namespace { // Serializes a 64bit integer as a string value. @@ -1019,6 +1030,30 @@ void ExtensionPrefs::SetActivePermissions(const std::string& extension_id, extension_id, kPrefActivePermissions, permissions); } +void ExtensionPrefs::SetShouldWithholdPermissions( + const ExtensionId& extension_id, + bool should_withhold) { + // NOTE: For legacy reasons, the preference stores whether the extension was + // allowed access to all its host permissions, rather than if Chrome should + // withhold permissions. Invert the boolean for backwards compatibility. + bool permissions_allowed = !should_withhold; + UpdateExtensionPref(extension_id, kGrantExtensionAllHostPermissions, + std::make_unique<base::Value>(permissions_allowed)); +} + +base::Optional<bool> ExtensionPrefs::GetShouldWithholdPermissions( + const ExtensionId& extension_id) const { + bool permissions_allowed = false; + if (!ReadPrefAsBoolean(extension_id, kGrantExtensionAllHostPermissions, + &permissions_allowed)) { + return base::nullopt; + } + // NOTE: For legacy reasons, the preference stores whether the extension was + // allowed access to all its host permissions, rather than if Chrome should + // withhold permissions. Invert the boolean for backwards compatibility. + return !permissions_allowed; +} + std::unique_ptr<const PermissionSet> ExtensionPrefs::GetRuntimeGrantedPermissions( const ExtensionId& extension_id) const { @@ -1909,8 +1944,6 @@ void ExtensionPrefs::RegisterProfilePrefs( registry->RegisterBooleanPref(pref_names::kNativeMessagingUserLevelHosts, true); registry->RegisterIntegerPref(kCorruptedDisableCount, 0); - registry->RegisterBooleanPref(pref_names::kInsecureExtensionUpdatesEnabled, - false); #if !defined(OS_MACOSX) registry->RegisterBooleanPref(pref_names::kAppFullscreenAllowed, true); @@ -2121,6 +2154,9 @@ void ExtensionPrefs::MigrateObsoleteExtensionPrefs() { // Added 2019-07. "has_set_script_all_urls", + + // Added 2019-07. + "browser_action_visible", }; for (const auto& key_value : extensions_dictionary->DictItems()) { diff --git a/chromium/extensions/browser/extension_prefs.h b/chromium/extensions/browser/extension_prefs.h index b11f1c607a5..563d6afddbe 100644 --- a/chromium/extensions/browser/extension_prefs.h +++ b/chromium/extensions/browser/extension_prefs.h @@ -318,10 +318,6 @@ class ExtensionPrefs : public KeyedService { // to use Blacklist::GetBlacklistedIDs rather than this method. bool IsExtensionBlacklisted(const std::string& id) const; - // Returns whether insecure algorithms like SHA1 are trusted for the - // purpose of updating the extension. - bool InsecureExtensionUpdatesEnabled() const; - // Increment the count of how many times we prompted the user to acknowledge // the given extension, and return the new count. int IncrementAcknowledgePromptCount(const std::string& extension_id); @@ -398,6 +394,14 @@ class ExtensionPrefs : public KeyedService { void SetActivePermissions(const std::string& extension_id, const PermissionSet& permissions); + // Sets/Gets the value indicating if an extension should be granted all the + // requested host permissions without requiring explicit runtime-granted + // permissions from the user. + void SetShouldWithholdPermissions(const ExtensionId& extension_id, + bool should_withhold); + base::Optional<bool> GetShouldWithholdPermissions( + const ExtensionId& extension_id) const; + // Returns the set of runtime-granted permissions. These are permissions that // the user explicitly approved at runtime, rather than install time (such // as those granted through the permissions API or the runtime host diff --git a/chromium/extensions/browser/extension_protocols.cc b/chromium/extensions/browser/extension_protocols.cc index 751868e6993..ef8257bc44b 100644 --- a/chromium/extensions/browser/extension_protocols.cc +++ b/chromium/extensions/browser/extension_protocols.cc @@ -43,7 +43,6 @@ #include "content/public/browser/navigation_ui_data.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" -#include "content/public/browser/resource_request_info.h" #include "content/public/common/resource_type.h" #include "crypto/secure_hash.h" #include "crypto/sha2.h" @@ -76,11 +75,11 @@ #include "net/http/http_request_headers.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" +#include "services/network/public/cpp/resource_response.h" #include "services/network/public/cpp/url_loader_completion_status.h" #include "url/url_util.h" using content::BrowserContext; -using content::ResourceRequestInfo; using extensions::Extension; using extensions::SharedModuleInfo; @@ -537,8 +536,8 @@ class ExtensionURLLoaderFactory : public network::mojom::URLLoaderFactory { scoped_refptr<ContentVerifier> content_verifier = extension_info_map_->content_verifier(); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ReadResourceFilePathAndLastModifiedTime, resource, directory_path, base::Unretained(read_file_path), base::Unretained(last_modified_time)), @@ -561,7 +560,7 @@ class ExtensionURLLoaderFactory : public network::mojom::URLLoaderFactory { bool send_cors_header) { request.url = net::FilePathToFileURL(*read_file_path); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &StartVerifyJob, std::move(request), std::move(loader), diff --git a/chromium/extensions/browser/extension_registrar.cc b/chromium/extensions/browser/extension_registrar.cc index 7704d273b1e..64aa0abf365 100644 --- a/chromium/extensions/browser/extension_registrar.cc +++ b/chromium/extensions/browser/extension_registrar.cc @@ -25,6 +25,7 @@ #include "extensions/browser/renderer_startup_helper.h" #include "extensions/browser/runtime_data.h" #include "extensions/browser/service_worker_task_queue.h" +#include "extensions/browser/task_queue_util.h" #include "extensions/common/manifest_handlers/background_info.h" using content::DevToolsAgentHost; @@ -437,10 +438,7 @@ void ExtensionRegistrar::ActivateExtension(const Extension* extension, // TODO(lazyboy): We should move all logic that is required to start up an // extension to a separate class, instead of calling adhoc methods like // service worker ones below. - if (BackgroundInfo::IsServiceWorkerBased(extension)) { - DCHECK(extension->is_extension()); - ServiceWorkerTaskQueue::Get(browser_context_)->ActivateExtension(extension); - } + ActivateTaskQueueForExtension(browser_context_, extension); // Tell subsystems that use the ExtensionRegistryObserver::OnExtensionLoaded // about the new extension. @@ -465,10 +463,8 @@ void ExtensionRegistrar::DeactivateExtension(const Extension* extension, renderer_helper_->OnExtensionUnloaded(*extension); extension_system_->UnregisterExtensionWithRequestContexts(extension->id(), reason); - if (BackgroundInfo::IsServiceWorkerBased(extension)) { - ServiceWorkerTaskQueue::Get(browser_context_) - ->DeactivateExtension(extension); - } + DeactivateTaskQueueForExtension(browser_context_, extension); + delegate_->PostDeactivateExtension(extension); } diff --git a/chromium/extensions/browser/extension_registry.h b/chromium/extensions/browser/extension_registry.h index 2d2514bc0a9..ac8948125de 100644 --- a/chromium/extensions/browser/extension_registry.h +++ b/chromium/extensions/browser/extension_registry.h @@ -45,6 +45,11 @@ class ExtensionRegistry : public KeyedService { TERMINATED = 1 << 2, BLACKLISTED = 1 << 3, BLOCKED = 1 << 4, + // Used for compatibility with ExtensionService::GetExtensionById. + // DO NOT USE THIS FOR NEW CODE! + // TODO(489687): Analyze uses of this enum and replace them with either a + // more-specific one, or EVERYTHING as appropriate. + COMPATIBILITY = ENABLED | DISABLED | BLACKLISTED | BLOCKED, EVERYTHING = (1 << 5) - 1, }; diff --git a/chromium/extensions/browser/extension_user_script_loader.cc b/chromium/extensions/browser/extension_user_script_loader.cc index 483767bd1f6..06fde25aa35 100644 --- a/chromium/extensions/browser/extension_user_script_loader.cc +++ b/chromium/extensions/browser/extension_user_script_loader.cc @@ -29,7 +29,6 @@ #include "extensions/browser/component_extension_resource_manager.h" #include "extensions/browser/content_verifier.h" #include "extensions/browser/extension_file_task_runner.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/common/file_util.h" @@ -78,8 +77,8 @@ void VerifyContent(const VerifyContentInfo& info) { void ForwardVerifyContentToIO(const VerifyContentInfo& info) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&VerifyContent, info)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&VerifyContent, info)); } // Loads user scripts from the extension who owns these scripts. @@ -116,7 +115,7 @@ bool LoadScriptContent(const HostID& host_id, if (verifier.get()) { // Call VerifyContent() after yielding on UI thread so it is ensured that // ContentVerifierIOData is populated at the time we call VerifyContent(). - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &ForwardVerifyContentToIO, @@ -194,10 +193,9 @@ void LoadScriptsOnFileTaskRunner( LoadUserScripts(user_scripts.get(), hosts_info, added_script_ids, verifier); base::ReadOnlySharedMemoryRegion memory = UserScriptLoader::Serialize(*user_scripts); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(callback), std::move(user_scripts), - std::move(memory))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(std::move(callback), std::move(user_scripts), + std::move(memory))); } } // namespace @@ -208,8 +206,7 @@ ExtensionUserScriptLoader::ExtensionUserScriptLoader( bool listen_for_extension_system_loaded) : UserScriptLoader(browser_context, host_id), content_verifier_( - ExtensionSystem::Get(browser_context)->content_verifier()), - extension_registry_observer_(this) { + ExtensionSystem::Get(browser_context)->content_verifier()) { extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context)); if (listen_for_extension_system_loaded) { ExtensionSystem::Get(browser_context) diff --git a/chromium/extensions/browser/extension_user_script_loader.h b/chromium/extensions/browser/extension_user_script_loader.h index eb5a4ec42b7..479d7e53652 100644 --- a/chromium/extensions/browser/extension_user_script_loader.h +++ b/chromium/extensions/browser/extension_user_script_loader.h @@ -6,6 +6,7 @@ #define EXTENSIONS_BROWSER_EXTENSION_USER_SCRIPT_LOADER_H_ #include "base/macros.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/browser/user_script_loader.h" #include "extensions/common/extension.h" @@ -17,7 +18,6 @@ class BrowserContext; namespace extensions { class ContentVerifier; -class ExtensionRegistry; // UserScriptLoader for extensions. class ExtensionUserScriptLoader : public UserScriptLoader, @@ -65,7 +65,7 @@ class ExtensionUserScriptLoader : public UserScriptLoader, scoped_refptr<ContentVerifier> content_verifier_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; base::WeakPtrFactory<ExtensionUserScriptLoader> weak_factory_{this}; diff --git a/chromium/extensions/browser/extension_util.cc b/chromium/extensions/browser/extension_util.cc index 854ea5aefe3..6077d4e2576 100644 --- a/chromium/extensions/browser/extension_util.cc +++ b/chromium/extensions/browser/extension_util.cc @@ -12,20 +12,12 @@ #include "extensions/common/features/feature.h" #include "extensions/common/features/feature_provider.h" #include "extensions/common/manifest.h" -#include "extensions/common/manifest_handlers/app_isolation_info.h" #include "extensions/common/manifest_handlers/incognito_info.h" +#include "extensions/common/manifest_handlers/shared_module_info.h" namespace extensions { namespace util { -bool SiteHasIsolatedStorage(const GURL& extension_site_url, - content::BrowserContext* context) { - const Extension* extension = ExtensionRegistry::Get(context)-> - enabled_extensions().GetExtensionOrAppByURL(extension_site_url); - - return extension && AppIsolationInfo::HasIsolatedStorage(extension); -} - bool CanBeIncognitoEnabled(const Extension* extension) { return IncognitoInfo::IsIncognitoAllowed(extension) && (!extension->is_platform_app() || @@ -77,5 +69,64 @@ content::StoragePartition* GetStoragePartitionForExtensionId( return storage_partition; } +// This function is security sensitive. Bugs could cause problems that break +// restrictions on local file access or NaCl's validation caching. If you modify +// this function, please get a security review from a NaCl person. +bool MapUrlToLocalFilePath(const ExtensionSet* extensions, + const GURL& file_url, + bool use_blocking_api, + base::FilePath* file_path) { + // Check that the URL is recognized by the extension system. + const Extension* extension = extensions->GetExtensionOrAppByURL(file_url); + if (!extension) + return false; + + // This is a short-cut which avoids calling a blocking file operation + // (GetFilePath()), so that this can be called on the non blocking threads. It + // only handles a subset of the urls. + if (!use_blocking_api) { + if (file_url.SchemeIs(extensions::kExtensionScheme)) { + std::string path = file_url.path(); + base::TrimString(path, "/", &path); // Remove first slash + *file_path = extension->path().AppendASCII(path); + return true; + } + return false; + } + + std::string path = file_url.path(); + ExtensionResource resource; + + if (SharedModuleInfo::IsImportedPath(path)) { + // Check if this is a valid path that is imported for this extension. + std::string new_extension_id; + std::string new_relative_path; + SharedModuleInfo::ParseImportedPath(path, &new_extension_id, + &new_relative_path); + const Extension* new_extension = extensions->GetByID(new_extension_id); + if (!new_extension) + return false; + + if (!SharedModuleInfo::ImportsExtensionById(extension, new_extension_id)) + return false; + + resource = new_extension->GetResource(new_relative_path); + } else { + // Check that the URL references a resource in the extension. + resource = extension->GetResource(path); + } + + if (resource.empty()) + return false; + + // GetFilePath is a blocking function call. + const base::FilePath resource_file_path = resource.GetFilePath(); + if (resource_file_path.empty()) + return false; + + *file_path = resource_file_path; + return true; +} + } // namespace util } // namespace extensions diff --git a/chromium/extensions/browser/extension_util.h b/chromium/extensions/browser/extension_util.h index d2a6531e1e8..d8138ede204 100644 --- a/chromium/extensions/browser/extension_util.h +++ b/chromium/extensions/browser/extension_util.h @@ -9,6 +9,10 @@ #include "url/gurl.h" +namespace base { +class FilePath; +} + namespace content { class BrowserContext; class StoragePartition; @@ -16,6 +20,7 @@ class StoragePartition; namespace extensions { class Extension; +class ExtensionSet; namespace util { @@ -23,11 +28,6 @@ namespace util { // chrome/browser/extensions/extension_util.h/cc that are only dependent on // extensions/ here. -// Returns true if the site URL corresponds to an extension or app and has -// isolated storage. -bool SiteHasIsolatedStorage(const GURL& extension_site_url, - content::BrowserContext* context); - // Returns true if the extension can be enabled in incognito mode. bool CanBeIncognitoEnabled(const Extension* extension); @@ -49,6 +49,17 @@ content::StoragePartition* GetStoragePartitionForExtensionId( const std::string& extension_id, content::BrowserContext* browser_context); +// Maps a |file_url| to a |file_path| on the local filesystem, including +// resources in extensions. Returns true on success. See NaClBrowserDelegate for +// full details. If |use_blocking_api| is false, only a subset of URLs will be +// handled. If |use_blocking_api| is true, blocking file operations may be used, +// and this must be called on threads that allow blocking. Otherwise this can be +// called on any thread. +bool MapUrlToLocalFilePath(const ExtensionSet* extensions, + const GURL& file_url, + bool use_blocking_api, + base::FilePath* file_path); + } // namespace util } // namespace extensions diff --git a/chromium/extensions/browser/extension_util_unittest.cc b/chromium/extensions/browser/extension_util_unittest.cc new file mode 100644 index 00000000000..6efa6e7c5aa --- /dev/null +++ b/chromium/extensions/browser/extension_util_unittest.cc @@ -0,0 +1,59 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "extensions/browser/extension_util.h" + +#include "base/path_service.h" +#include "extensions/common/extension_builder.h" +#include "extensions/common/extension_paths.h" +#include "extensions/common/extension_set.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace extensions { +namespace { +// Returns a barebones test Extension object with the given name. +static scoped_refptr<const Extension> CreateExtension(const std::string& name) { + base::FilePath path; + base::PathService::Get(DIR_TEST_DATA, &path); + + return ExtensionBuilder(name).SetPath(path.AppendASCII(name)).Build(); +} +} // namespace + +// Tests that extension URLs are properly mapped to local file paths. +TEST(ExtensionUtilTest, MapUrlToLocalFilePath) { + scoped_refptr<const Extension> app(CreateExtension("platform_app")); + ExtensionSet extensions; + extensions.Insert(app); + + // Non-extension URLs don't map to anything. + base::FilePath non_extension_path; + GURL non_extension_url("http://not-an-extension.com/"); + EXPECT_FALSE(util::MapUrlToLocalFilePath(&extensions, non_extension_url, + false, &non_extension_path)); + EXPECT_TRUE(non_extension_path.empty()); + + // Valid resources return a valid path. + base::FilePath valid_path; + GURL valid_url = app->GetResourceURL("manifest.json"); + EXPECT_TRUE(util::MapUrlToLocalFilePath( + &extensions, valid_url, true /* use_blocking_api */, &valid_path)); + EXPECT_FALSE(valid_path.empty()); + + // A file must exist to be mapped to a path using the blocking API. + base::FilePath does_not_exist_path; + GURL does_not_exist_url = app->GetResourceURL("does-not-exist.html"); + EXPECT_FALSE(util::MapUrlToLocalFilePath(&extensions, does_not_exist_url, + true /* use_blocking_api */, + &does_not_exist_path)); + EXPECT_TRUE(does_not_exist_path.empty()); + + // A file does not need to exist to be mapped to a path with the non-blocking + // API. This avoids hitting the disk to see if it exists. + EXPECT_TRUE(util::MapUrlToLocalFilePath(&extensions, does_not_exist_url, + false /* use_blocking_api */, + &does_not_exist_path)); + EXPECT_FALSE(does_not_exist_path.empty()); +} +} // namespace extensions diff --git a/chromium/extensions/browser/extension_web_contents_observer.cc b/chromium/extensions/browser/extension_web_contents_observer.cc index 6bfc6a537ec..d581d02ed75 100644 --- a/chromium/extensions/browser/extension_web_contents_observer.cc +++ b/chromium/extensions/browser/extension_web_contents_observer.cc @@ -47,10 +47,6 @@ void ExtensionWebContentsObserver::Initialize() { if (!rfh->IsRenderFrameLive()) continue; - // Initialize the FrameData for this frame here since we didn't receive the - // RenderFrameCreated notification for it. - ExtensionApiFrameIdMap::Get()->InitializeRenderFrameData(rfh); - InitializeRenderFrame(rfh); } } @@ -111,11 +107,6 @@ content::WebContents* ExtensionWebContentsObserver::GetAssociatedWebContents() void ExtensionWebContentsObserver::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { DCHECK(initialized_); - // Optimization: Look up the extension API frame ID to force the mapping to be - // cached. This minimizes the number of IO->UI->IO thread hops when the ID is - // looked up again on the IO thread for the webRequest API. - ExtensionApiFrameIdMap::Get()->InitializeRenderFrameData(render_frame_host); - InitializeRenderFrame(render_frame_host); const Extension* extension = GetExtensionFromFrame(render_frame_host, false); @@ -160,37 +151,14 @@ void ExtensionWebContentsObserver::RenderFrameDeleted( ExtensionApiFrameIdMap::Get()->OnRenderFrameDeleted(render_frame_host); } -void ExtensionWebContentsObserver::RenderFrameHostChanged( - content::RenderFrameHost* old_host, - content::RenderFrameHost* new_host) { - // TODO(karandeepb): The |new_host| here may correspond to a RenderFrameHost - // we haven't seen yet, which means it might also need some other - // initialization. See crbug.com/817205. - if (new_host->IsRenderFrameLive()) { - ExtensionApiFrameIdMap::Get()->InitializeRenderFrameData(new_host); - } -} - void ExtensionWebContentsObserver::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { URLLoaderFactoryManager::ReadyToCommitNavigation(navigation_handle); - - if (navigation_handle->IsInMainFrame() && - !navigation_handle->IsSameDocument()) { - ExtensionApiFrameIdMap::Get()->OnMainFrameReadyToCommitNavigation( - navigation_handle); - } } void ExtensionWebContentsObserver::DidFinishNavigation( content::NavigationHandle* navigation_handle) { DCHECK(initialized_); - if (navigation_handle->IsInMainFrame() && - !navigation_handle->IsSameDocument()) { - ExtensionApiFrameIdMap::Get()->OnMainFrameDidFinishNavigation( - navigation_handle); - } - if (!navigation_handle->HasCommitted()) return; diff --git a/chromium/extensions/browser/extension_web_contents_observer.h b/chromium/extensions/browser/extension_web_contents_observer.h index e2a32040278..4a78956aa21 100644 --- a/chromium/extensions/browser/extension_web_contents_observer.h +++ b/chromium/extensions/browser/extension_web_contents_observer.h @@ -89,8 +89,6 @@ class ExtensionWebContentsObserver // content::WebContentsObserver overrides. void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override; void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; - void RenderFrameHostChanged(content::RenderFrameHost* old_host, - content::RenderFrameHost* new_host) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( diff --git a/chromium/extensions/browser/extensions_browser_client.cc b/chromium/extensions/browser/extensions_browser_client.cc index 1dcae5284fc..14558364859 100644 --- a/chromium/extensions/browser/extensions_browser_client.cc +++ b/chromium/extensions/browser/extensions_browser_client.cc @@ -44,12 +44,6 @@ ExtensionsBrowserClient::CreateUpdateClient(content::BrowserContext* context) { return scoped_refptr<update_client::UpdateClient>(nullptr); } -std::unique_ptr<ExtensionApiFrameIdMapHelper> -ExtensionsBrowserClient::CreateExtensionApiFrameIdMapHelper( - ExtensionApiFrameIdMap* map) { - return nullptr; -} - std::unique_ptr<content::BluetoothChooser> ExtensionsBrowserClient::CreateBluetoothChooser( content::RenderFrameHost* frame, diff --git a/chromium/extensions/browser/extensions_browser_client.h b/chromium/extensions/browser/extensions_browser_client.h index 2f4890b5489..ed47ee5227a 100644 --- a/chromium/extensions/browser/extensions_browser_client.h +++ b/chromium/extensions/browser/extensions_browser_client.h @@ -55,8 +55,6 @@ class Extension; class ExtensionCache; class ExtensionError; class ExtensionHostDelegate; -class ExtensionApiFrameIdMap; -class ExtensionApiFrameIdMapHelper; class ExtensionSet; class ExtensionSystem; class ExtensionSystemProvider; @@ -249,7 +247,8 @@ class ExtensionsBrowserClient { virtual void BroadcastEventToRenderers( events::HistogramValue histogram_value, const std::string& event_name, - std::unique_ptr<base::ListValue> args) = 0; + std::unique_ptr<base::ListValue> args, + bool dispatch_to_off_the_record_profiles) = 0; // Gets the single ExtensionCache instance shared across the browser process. virtual ExtensionCache* GetExtensionCache() = 0; @@ -287,9 +286,6 @@ class ExtensionsBrowserClient { virtual scoped_refptr<update_client::UpdateClient> CreateUpdateClient( content::BrowserContext* context); - virtual std::unique_ptr<ExtensionApiFrameIdMapHelper> - CreateExtensionApiFrameIdMapHelper(ExtensionApiFrameIdMap* map); - virtual std::unique_ptr<content::BluetoothChooser> CreateBluetoothChooser( content::RenderFrameHost* frame, const content::BluetoothChooser::EventHandler& event_handler); diff --git a/chromium/extensions/browser/extensions_test.cc b/chromium/extensions/browser/extensions_test.cc index 99d29c16e4f..e4d57e229a5 100644 --- a/chromium/extensions/browser/extensions_test.cc +++ b/chromium/extensions/browser/extensions_test.cc @@ -45,8 +45,8 @@ class ExtensionTestBrowserContext : public content::TestBrowserContext { namespace extensions { ExtensionsTest::ExtensionsTest( - std::unique_ptr<content::TestBrowserThreadBundle> thread_bundle) - : thread_bundle_(std::move(thread_bundle)), + std::unique_ptr<content::BrowserTaskEnvironment> task_environment) + : task_environment_(std::move(task_environment)), rvh_test_enabler_( std::make_unique<content::RenderViewHostTestEnabler>()) {} @@ -54,7 +54,7 @@ ExtensionsTest::~ExtensionsTest() { // Destroy the task runners before nulling the browser/utility clients, as // posted tasks may use them. rvh_test_enabler_.reset(); - thread_bundle_.reset(); + task_environment_.reset(); content::SetUtilityClientForTesting(nullptr); } diff --git a/chromium/extensions/browser/extensions_test.h b/chromium/extensions/browser/extensions_test.h index 4634425df7e..cb742fa97d7 100644 --- a/chromium/extensions/browser/extensions_test.h +++ b/chromium/extensions/browser/extensions_test.h @@ -38,7 +38,7 @@ class ExtensionsTest : public testing::Test { template <typename... Args> constexpr ExtensionsTest(Args... args) : ExtensionsTest( - std::make_unique<content::TestBrowserThreadBundle>(args...)) {} + std::make_unique<content::BrowserTaskEnvironment>(args...)) {} ~ExtensionsTest() override; @@ -72,7 +72,7 @@ class ExtensionsTest : public testing::Test { // The template constructor has to be in the header but it delegates to this // constructor to initialize all other members out-of-line. explicit ExtensionsTest( - std::unique_ptr<content::TestBrowserThreadBundle> thread_bundle); + std::unique_ptr<content::BrowserTaskEnvironment> task_environment); content::TestContentClientInitializer content_client_initializer_; std::unique_ptr<content::ContentUtilityClient> content_utility_client_; @@ -84,7 +84,7 @@ class ExtensionsTest : public testing::Test { MockExtensionSystemFactory<MockExtensionSystem> extension_system_factory_; - std::unique_ptr<content::TestBrowserThreadBundle> thread_bundle_; + std::unique_ptr<content::BrowserTaskEnvironment> task_environment_; // The existence of this object enables tests via // RenderViewHostTester. diff --git a/chromium/extensions/browser/file_reader_unittest.cc b/chromium/extensions/browser/file_reader_unittest.cc index b839f5c8c71..ba5e1780ab3 100644 --- a/chromium/extensions/browser/file_reader_unittest.cc +++ b/chromium/extensions/browser/file_reader_unittest.cc @@ -10,7 +10,7 @@ #include "base/files/file_util.h" #include "base/path_service.h" #include "base/run_loop.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "components/crx_file/id_util.h" #include "extensions/common/extension_paths.h" #include "extensions/common/extension_resource.h" @@ -23,7 +23,7 @@ class FileReaderTest : public testing::Test { FileReaderTest() {} private: - base::test::ScopedTaskEnvironment task_environment_; + base::test::TaskEnvironment task_environment_; DISALLOW_COPY_AND_ASSIGN(FileReaderTest); }; diff --git a/chromium/extensions/browser/guest_view/extension_view/extension_view_constants.cc b/chromium/extensions/browser/guest_view/extension_view/extension_view_constants.cc deleted file mode 100644 index 49adead0f67..00000000000 --- a/chromium/extensions/browser/guest_view/extension_view/extension_view_constants.cc +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "extensions/browser/guest_view/extension_view/extension_view_constants.h" - -namespace extensionview { - -// API namespace. -const char kAPINamespace[] = "extensionViewInternal"; - -// Attributes. -const char kAttributeExtension[] = "extension"; -const char kAttributeSrc[] = "src"; - -// Events. -const char kEventLoadCommit[] = "extensionViewInternal.onLoadCommit"; - -} // namespace extensionview diff --git a/chromium/extensions/browser/guest_view/extension_view/extension_view_constants.h b/chromium/extensions/browser/guest_view/extension_view/extension_view_constants.h deleted file mode 100644 index cbfd7e2043a..00000000000 --- a/chromium/extensions/browser/guest_view/extension_view/extension_view_constants.h +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef EXTENSIONS_BROWSER_GUEST_VIEW_EXTENSION_VIEW_EXTENSION_VIEW_CONSTANTS_H_ -#define EXTENSIONS_BROWSER_GUEST_VIEW_EXTENSION_VIEW_EXTENSION_VIEW_CONSTANTS_H_ - -namespace extensionview { - -// API namespace. -extern const char kAPINamespace[]; - -// Attributes. -extern const char kAttributeExtension[]; -extern const char kAttributeSrc[]; - -// Events. -extern const char kEventLoadCommit[]; - -} // namespace extensionview - -#endif // EXTENSIONS_BROWSER_GUEST_VIEW_EXTENSION_VIEW_EXTENSION_VIEW_CONSTANTS_H_ diff --git a/chromium/extensions/browser/guest_view/extension_view/extension_view_guest.cc b/chromium/extensions/browser/guest_view/extension_view/extension_view_guest.cc deleted file mode 100644 index 7b6f20545e4..00000000000 --- a/chromium/extensions/browser/guest_view/extension_view/extension_view_guest.cc +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "extensions/browser/guest_view/extension_view/extension_view_guest.h" - -#include <memory> -#include <string> -#include <utility> - -#include "components/crx_file/id_util.h" -#include "components/guest_view/browser/guest_view_event.h" -#include "content/public/browser/navigation_handle.h" -#include "content/public/browser/render_frame_host.h" -#include "content/public/browser/render_process_host.h" -#include "content/public/common/result_codes.h" -#include "extensions/browser/api/extensions_api_client.h" -#include "extensions/browser/bad_message.h" -#include "extensions/browser/guest_view/extension_view/extension_view_constants.h" -#include "extensions/browser/guest_view/extension_view/whitelist/extension_view_whitelist.h" -#include "extensions/common/constants.h" -#include "extensions/common/extension_messages.h" -#include "extensions/strings/grit/extensions_strings.h" -#include "url/origin.h" - -using content::WebContents; -using guest_view::GuestViewBase; -using guest_view::GuestViewEvent; - -namespace extensions { - -// static -const char ExtensionViewGuest::Type[] = "extensionview"; - -ExtensionViewGuest::ExtensionViewGuest(WebContents* owner_web_contents) - : GuestView<ExtensionViewGuest>(owner_web_contents) {} - -ExtensionViewGuest::~ExtensionViewGuest() { -} - -// static -GuestViewBase* ExtensionViewGuest::Create(WebContents* owner_web_contents) { - return new ExtensionViewGuest(owner_web_contents); -} - -bool ExtensionViewGuest::NavigateGuest(const std::string& src, - bool force_navigation) { - GURL url = extension_url_.Resolve(src); - - // If the URL is not valid, about:blank, or the same origin as the extension, - // then navigate to about:blank. - bool url_not_allowed = - url != url::kAboutBlankURL && !url::IsSameOriginWith(url, extension_url_); - if (!url.is_valid() || url_not_allowed) - return NavigateGuest(url::kAboutBlankURL, true /* force_navigation */); - - if (!force_navigation && (url_ == url)) - return false; - - web_contents()->GetMainFrame()->GetProcess()->FilterURL(false, &url); - web_contents()->GetController().LoadURL(url, content::Referrer(), - ui::PAGE_TRANSITION_AUTO_TOPLEVEL, - std::string()); - - url_ = url; - return true; -} - -// GuestViewBase implementation. -void ExtensionViewGuest::CreateWebContents( - const base::DictionaryValue& create_params, - WebContentsCreatedCallback callback) { - // Gets the extension ID. - std::string extension_id; - create_params.GetString(extensionview::kAttributeExtension, &extension_id); - - if (!crx_file::id_util::IdIsValid(extension_id) || - !IsExtensionIdWhitelisted(extension_id)) { - std::move(callback).Run(nullptr); - return; - } - - // Gets the extension URL. - extension_url_ = - extensions::Extension::GetBaseURLFromExtensionId(extension_id); - - if (!extension_url_.is_valid()) { - std::move(callback).Run(nullptr); - return; - } - - WebContents::CreateParams params( - browser_context(), - content::SiteInstance::CreateForURL(browser_context(), extension_url_)); - params.guest_delegate = this; - // TODO(erikchen): Fix ownership semantics for guest views. - // https://crbug.com/832879. - std::move(callback).Run(WebContents::Create(params).release()); -} - -void ExtensionViewGuest::DidInitialize( - const base::DictionaryValue& create_params) { - ExtensionsAPIClient::Get()->AttachWebContentsHelpers(web_contents()); - - ApplyAttributes(create_params); -} - -void ExtensionViewGuest::DidAttachToEmbedder() { - ApplyAttributes(*attach_params()); -} - -const char* ExtensionViewGuest::GetAPINamespace() const { - return extensionview::kAPINamespace; -} - -int ExtensionViewGuest::GetTaskPrefix() const { - return IDS_EXTENSION_TASK_MANAGER_EXTENSIONVIEW_TAG_PREFIX; -} - -void ExtensionViewGuest::DidFinishNavigation( - content::NavigationHandle* navigation_handle) { - if (!navigation_handle->HasCommitted() || !navigation_handle->IsInMainFrame()) - return; - - url_ = navigation_handle->GetURL(); - - std::unique_ptr<base::DictionaryValue> args(new base::DictionaryValue()); - args->SetString(guest_view::kUrl, url_.spec()); - DispatchEventToView(std::make_unique<GuestViewEvent>( - extensionview::kEventLoadCommit, std::move(args))); -} - -void ExtensionViewGuest::ApplyAttributes(const base::DictionaryValue& params) { - std::string src; - params.GetString(extensionview::kAttributeSrc, &src); - NavigateGuest(src, false /* force_navigation */); -} - -} // namespace extensions diff --git a/chromium/extensions/browser/guest_view/extension_view/extension_view_guest.h b/chromium/extensions/browser/guest_view/extension_view/extension_view_guest.h deleted file mode 100644 index 2b32890f4f7..00000000000 --- a/chromium/extensions/browser/guest_view/extension_view/extension_view_guest.h +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef EXTENSIONS_BROWSER_GUEST_VIEW_EXTENSION_VIEW_EXTENSION_VIEW_GUEST_H_ -#define EXTENSIONS_BROWSER_GUEST_VIEW_EXTENSION_VIEW_EXTENSION_VIEW_GUEST_H_ - -#include "base/macros.h" -#include "components/guest_view/browser/guest_view.h" -#include "extensions/browser/extension_function_dispatcher.h" -#include "url/gurl.h" - -namespace extensions { - -class ExtensionViewGuest - : public guest_view::GuestView<ExtensionViewGuest> { - public: - static const char Type[]; - static guest_view::GuestViewBase* Create( - content::WebContents* owner_web_contents); - - // Request navigating the guest to the provided |src| URL. - // Returns true if the navigation is successful. - bool NavigateGuest(const std::string& src, bool force_navigation); - - private: - ExtensionViewGuest(content::WebContents* owner_web_contents); - ~ExtensionViewGuest() override; - - // GuestViewBase implementation. - void CreateWebContents(const base::DictionaryValue& create_params, - WebContentsCreatedCallback callback) final; - void DidInitialize(const base::DictionaryValue& create_params) final; - void DidAttachToEmbedder() final; - const char* GetAPINamespace() const final; - int GetTaskPrefix() const final; - - // content::WebContentsObserver implementation. - void DidFinishNavigation(content::NavigationHandle* navigation_handle) final; - - // Applies attributes to the extensionview. - void ApplyAttributes(const base::DictionaryValue& params); - - // The full URL that the extensionview is currently navigated to. - GURL url_; - - // The extension URL, including the extension scheme and extension ID. - GURL extension_url_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionViewGuest); -}; - -} // namespace extensions - -#endif // EXTENSIONS_BROWSER_GUEST_VIEW_EXTENSION_VIEW_EXTENSION_VIEW_GUEST_H_ diff --git a/chromium/extensions/browser/guest_view/extension_view/whitelist/OWNERS b/chromium/extensions/browser/guest_view/extension_view/whitelist/OWNERS deleted file mode 100644 index c7ff2564a44..00000000000 --- a/chromium/extensions/browser/guest_view/extension_view/whitelist/OWNERS +++ /dev/null @@ -1,8 +0,0 @@ -# Whitelisting new extension ids for ExtensionView use requires approval from -# chrome-eng-review@google.com. -set noparent - -file://ENG_REVIEW_OWNERS - -# TEAM: extensions-dev@chromium.org -# COMPONENT: Platform>Extensions diff --git a/chromium/extensions/browser/guest_view/extension_view/whitelist/extension_view_whitelist.cc b/chromium/extensions/browser/guest_view/extension_view/whitelist/extension_view_whitelist.cc deleted file mode 100644 index a83a4769d3d..00000000000 --- a/chromium/extensions/browser/guest_view/extension_view/whitelist/extension_view_whitelist.cc +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "extensions/browser/guest_view/extension_view/whitelist/extension_view_whitelist.h" - -#include <stddef.h> - -#include "base/logging.h" -#include "base/stl_util.h" - -namespace extensions { - -namespace { - -// ============================================================================= -// -// ADDING NEW EXTENSIONS REQUIRES APPROVAL from chrome-eng-review@google.com -// -// ============================================================================= - -const char* const kWhitelist[] = { - "pemeknaakobkocgmimdeamlcklioagkh", // Used in browser tests - "dppcjffonoklmpdmljnpdojmoaefcabf", // Used in browser tests - "enhhojjnijigcajfphajepfemndkmdlo", // Media Router Dev - "pkedcjkdefgpdelpbcmbmeomcjbeemfm", // Media Router Stable -}; - -} // namespace - -// static -bool IsExtensionIdWhitelisted(const std::string& extension_id) { - for (size_t i = 0; i < base::size(kWhitelist); ++i) { - if (extension_id == kWhitelist[i]) - return true; - } - - return false; -} - -} // namespace extensions diff --git a/chromium/extensions/browser/guest_view/extension_view/whitelist/extension_view_whitelist.h b/chromium/extensions/browser/guest_view/extension_view/whitelist/extension_view_whitelist.h deleted file mode 100644 index 512600b65d6..00000000000 --- a/chromium/extensions/browser/guest_view/extension_view/whitelist/extension_view_whitelist.h +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef EXTENSIONS_BROWSER_GUEST_VIEW_EXTENSION_VIEW_WHITELIST_EXTENSION_VIEW_WHITELIST_H_ -#define EXTENSIONS_BROWSER_GUEST_VIEW_EXTENSION_VIEW_WHITELIST_EXTENSION_VIEW_WHITELIST_H_ - -#include <string> - -namespace extensions { - -// Checks whether |extension_id| is whitelisted to be used by ExtensionView. -bool IsExtensionIdWhitelisted(const std::string& extension_id); - -} // namespace extensions - -#endif // EXTENSIONS_BROWSER_GUEST_VIEW_EXTENSION_VIEW_WHITELIST_EXTENSION_VIEW_WHITELIST_H_ diff --git a/chromium/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc b/chromium/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc index 8558d4aafd9..5fe69925ab9 100644 --- a/chromium/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc +++ b/chromium/extensions/browser/guest_view/extensions_guest_view_manager_delegate.cc @@ -19,7 +19,6 @@ #include "extensions/browser/event_router.h" #include "extensions/browser/guest_view/app_view/app_view_guest.h" #include "extensions/browser/guest_view/extension_options/extension_options_guest.h" -#include "extensions/browser/guest_view/extension_view/extension_view_guest.h" #include "extensions/browser/guest_view/guest_view_events.h" #include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h" #include "extensions/browser/guest_view/web_view/web_view_guest.h" @@ -114,7 +113,6 @@ void ExtensionsGuestViewManagerDelegate::RegisterAdditionalGuestViewTypes() { GuestViewManager* manager = GuestViewManager::FromBrowserContext(context_); manager->RegisterGuestViewType<AppViewGuest>(); manager->RegisterGuestViewType<ExtensionOptionsGuest>(); - manager->RegisterGuestViewType<ExtensionViewGuest>(); manager->RegisterGuestViewType<MimeHandlerViewGuest>(); manager->RegisterGuestViewType<WebViewGuest>(); } diff --git a/chromium/extensions/browser/guest_view/extensions_guest_view_message_filter.cc b/chromium/extensions/browser/guest_view/extensions_guest_view_message_filter.cc index 55c88acc4c1..c935537ef16 100644 --- a/chromium/extensions/browser/guest_view/extensions_guest_view_message_filter.cc +++ b/chromium/extensions/browser/guest_view/extensions_guest_view_message_filter.cc @@ -117,20 +117,19 @@ void ExtensionsGuestViewMessageFilter::CreateMimeHandlerViewGuest( int32_t element_instance_id, const gfx::Size& element_size, mime_handler::BeforeUnloadControlPtr before_unload_control) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ExtensionsGuestViewMessageFilter:: - CreateMimeHandlerViewGuestOnUIThread, - this, render_frame_id, view_id, element_instance_id, - element_size, before_unload_control.PassInterface(), - false)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ExtensionsGuestViewMessageFilter:: + CreateMimeHandlerViewGuestOnUIThread, + this, render_frame_id, view_id, + element_instance_id, element_size, + before_unload_control.PassInterface(), false)); } void ExtensionsGuestViewMessageFilter::ReadyToCreateMimeHandlerView( int32_t render_frame_id, bool success) { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &ExtensionsGuestViewMessageFilter::ReadyToCreateMimeHandlerView, @@ -203,13 +202,12 @@ void ExtensionsGuestViewMessageFilter::CreateEmbeddedMimeHandlerViewGuest( const gfx::Size& element_size, content::mojom::TransferrableURLLoaderPtr transferrable_url_loader) { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ExtensionsGuestViewMessageFilter:: - CreateEmbeddedMimeHandlerViewGuest, - this, render_frame_id, tab_id, original_url, - element_instance_id, element_size, - base::Passed(&transferrable_url_loader))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ExtensionsGuestViewMessageFilter:: + CreateEmbeddedMimeHandlerViewGuest, + this, render_frame_id, tab_id, original_url, + element_instance_id, element_size, + base::Passed(&transferrable_url_loader))); return; } diff --git a/chromium/extensions/browser/guest_view/guest_view_events.cc b/chromium/extensions/browser/guest_view/guest_view_events.cc index 36da97195e9..3b42d332081 100644 --- a/chromium/extensions/browser/guest_view/guest_view_events.cc +++ b/chromium/extensions/browser/guest_view/guest_view_events.cc @@ -10,7 +10,6 @@ #include "base/macros.h" #include "components/guest_view/common/guest_view_constants.h" #include "extensions/browser/guest_view/extension_options/extension_options_constants.h" -#include "extensions/browser/guest_view/extension_view/extension_view_constants.h" #include "extensions/browser/guest_view/web_view/web_view_constants.h" #include "extensions/common/api/extension_options_internal.h" @@ -34,8 +33,6 @@ class EventMap { events::EXTENSION_OPTIONS_INTERNAL_ON_LOAD}, {api::extension_options_internal::OnPreferredSizeChanged::kEventName, events::EXTENSION_OPTIONS_INTERNAL_ON_PREFERRED_SIZE_CHANGED}, - {extensionview::kEventLoadCommit, - events::EXTENSION_VIEW_INTERNAL_ON_LOAD_COMMIT}, {guest_view::kEventResize, events::GUEST_VIEW_INTERNAL_ON_RESIZE}, {webview::kEventAudioStateChanged, events::WEB_VIEW_INTERNAL_ON_AUDIO_STATE_CHANGED}, diff --git a/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_stream_manager.cc b/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_stream_manager.cc index 22cb5bb146c..2687f315d0b 100644 --- a/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_stream_manager.cc +++ b/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_stream_manager.cc @@ -12,7 +12,6 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h" @@ -110,12 +109,8 @@ class MimeHandlerStreamManager::EmbedderObserver content::RenderFrameHost* new_host_; }; -MimeHandlerStreamManager::MimeHandlerStreamManager() - : extension_registry_observer_(this) { -} - -MimeHandlerStreamManager::~MimeHandlerStreamManager() { -} +MimeHandlerStreamManager::MimeHandlerStreamManager() = default; +MimeHandlerStreamManager::~MimeHandlerStreamManager() = default; // static MimeHandlerStreamManager* MimeHandlerStreamManager::Get( @@ -194,10 +189,10 @@ void MimeHandlerStreamManager::EmbedderObserver::RenderFrameDeleted( if (!IsTrackedRenderFrameHost(render_frame_host)) return; - // PlzNavigate: the MimeHandlerStreamManager::EmbedderObserver is initialized - // before the final RenderFrameHost for the navigation has been chosen. When - // it is later picked, a specualtive RenderFrameHost might be deleted. Do not - // abort the stream in that case. + // The MimeHandlerStreamManager::EmbedderObserver is initialized before the + // final RenderFrameHost for the navigation has been chosen. When it is later + // picked, a specualtive RenderFrameHost might be deleted. Do not abort the + // stream in that case. if (frame_tree_node_id_ != -1 && !render_frame_host->IsCurrent()) return; diff --git a/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_stream_manager.h b/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_stream_manager.h index e7c7fdf0dc0..a9659edca6c 100644 --- a/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_stream_manager.h +++ b/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_stream_manager.h @@ -10,9 +10,11 @@ #include <string> #include "base/gtest_prod_util.h" +#include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/scoped_observer.h" #include "components/keyed_service/core/keyed_service.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" namespace content { @@ -37,9 +39,9 @@ class MimeHandlerStreamManager : public KeyedService, ~MimeHandlerStreamManager() override; static MimeHandlerStreamManager* Get(content::BrowserContext* context); - // The |frame_tree_node_id| parameter is used for PlzNavigate for the top - // level plugins case. (PDF, etc). If this parameter has a valid value then - // it overrides the |render_process_id| and |render_frame_id| parameters. + // The |frame_tree_node_id| parameter is used for the top level plugins case + // (PDF, etc). If this parameter has a valid value then it overrides the + // |render_process_id| and |render_frame_id| parameters. // The |render_process_id| is the id of the renderer process. // The |render_frame_id| is the routing id of the RenderFrameHost. void AddStream(const std::string& view_id, @@ -73,7 +75,9 @@ class MimeHandlerStreamManager : public KeyedService, std::map<std::string, std::unique_ptr<EmbedderObserver>> embedder_observers_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; + + DISALLOW_COPY_AND_ASSIGN(MimeHandlerStreamManager); }; } // namespace extensions diff --git a/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_view_attach_helper.cc b/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_view_attach_helper.cc index fd82f54e41e..e5c23717856 100644 --- a/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_view_attach_helper.cc +++ b/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_view_attach_helper.cc @@ -102,7 +102,7 @@ bool MimeHandlerViewAttachHelper::OverrideBodyForInterceptedResponse( SkColorGetB(color), mime_type.c_str(), token.c_str()); payload->assign(html_str); *data_pipe_size = kFullPageMimeHandlerViewDataPipeSize; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {BrowserThread::UI}, base::BindOnce(CreateFullPageMimeHandlerView, navigating_frame_tree_node_id, resource_url, mime_type, diff --git a/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc b/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc index b7cb9fc9df1..1578ad4f86b 100644 --- a/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc +++ b/chromium/extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.cc @@ -54,10 +54,10 @@ StreamContainer::StreamContainer( handler_url_(handler_url), extension_id_(extension_id), transferrable_loader_(std::move(transferrable_loader)), - mime_type_(transferrable_loader_->head.mime_type), + mime_type_(transferrable_loader_->head->mime_type), original_url_(original_url), stream_url_(transferrable_loader_->url), - response_headers_(transferrable_loader_->head.headers) {} + response_headers_(transferrable_loader_->head->headers) {} StreamContainer::~StreamContainer() { } diff --git a/chromium/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.cc b/chromium/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.cc index 533e711f570..1bff1925b5a 100644 --- a/chromium/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.cc +++ b/chromium/extensions/browser/guest_view/mime_handler_view/test_mime_handler_view_guest.cc @@ -45,7 +45,7 @@ void TestMimeHandlerViewGuest::CreateWebContents( // Delay the creation of the guest's WebContents if |delay_| is set. if (delay_) { auto delta = base::TimeDelta::FromMilliseconds(delay_); - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&TestMimeHandlerViewGuest::CallBaseCreateWebContents, weak_ptr_factory_.GetWeakPtr(), diff --git a/chromium/extensions/browser/guest_view/web_view/web_ui/web_ui_url_fetcher.cc b/chromium/extensions/browser/guest_view/web_view/web_ui/web_ui_url_fetcher.cc index ad27ff69a2d..bc6ec53e1d5 100644 --- a/chromium/extensions/browser/guest_view/web_view/web_ui/web_ui_url_fetcher.cc +++ b/chromium/extensions/browser/guest_view/web_view/web_ui/web_ui_url_fetcher.cc @@ -56,8 +56,7 @@ void WebUIURLFetcher::Start() { })"); auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = url_; - resource_request->load_flags = - net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES; + resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; fetcher_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); fetcher_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( diff --git a/chromium/extensions/browser/guest_view/web_view/web_view_apitest.cc b/chromium/extensions/browser/guest_view/web_view/web_view_apitest.cc index 6ca4eebe87a..55e4c7db0da 100644 --- a/chromium/extensions/browser/guest_view/web_view/web_view_apitest.cc +++ b/chromium/extensions/browser/guest_view/web_view/web_view_apitest.cc @@ -466,7 +466,7 @@ IN_PROC_BROWSER_TEST_F(WebViewAPITest, TestContextMenu) { // Ensure the webview's surface is ready for hit testing. content::WebContents* guest_web_contents = GetGuestWebContents(); - content::WaitForHitTestDataOrGuestSurfaceReady(guest_web_contents); + content::WaitForHitTestData(guest_web_contents); // Register a ContextMenuFilter to wait for the context menu event to be sent. content::RenderProcessHost* guest_process_host = diff --git a/chromium/extensions/browser/guest_view/web_view/web_view_find_helper.cc b/chromium/extensions/browser/guest_view/web_view/web_view_find_helper.cc index 5c74ebe8892..defb854a1a7 100644 --- a/chromium/extensions/browser/guest_view/web_view/web_view_find_helper.cc +++ b/chromium/extensions/browser/guest_view/web_view/web_view_find_helper.cc @@ -6,6 +6,7 @@ #include <utility> +#include "base/memory/scoped_refptr.h" #include "components/guest_view/browser/guest_view_event.h" #include "extensions/browser/api/guest_view/web_view/web_view_internal_api.h" #include "extensions/browser/guest_view/web_view/web_view_constants.h" @@ -96,9 +97,9 @@ void WebViewFindHelper::Find( // function can be called when the find results are available. std::pair<FindInfoMap::iterator, bool> insert_result = find_info_map_.insert(std::make_pair( - current_find_request_id_, base::WrapRefCounted(new FindInfo( - current_find_request_id_, search_text, - options.Clone(), find_function)))); + current_find_request_id_, + base::MakeRefCounted<FindInfo>(current_find_request_id_, search_text, + options.Clone(), find_function))); // No duplicate insertions. DCHECK(insert_result.second); diff --git a/chromium/extensions/browser/guest_view/web_view/web_view_guest.cc b/chromium/extensions/browser/guest_view/web_view/web_view_guest.cc index db1017ed931..78786fa4d6a 100644 --- a/chromium/extensions/browser/guest_view/web_view/web_view_guest.cc +++ b/chromium/extensions/browser/guest_view/web_view/web_view_guest.cc @@ -863,9 +863,8 @@ void WebViewGuest::DidFinishNavigation( LoadAbort(navigation_handle->IsInMainFrame(), navigation_handle->GetURL(), error_code); } - // The old behavior, before PlzNavigate, was that on failed navigations the - // webview would fire a loadabort (for the failed navigation) and a - // loadcommit (for the error page). + // Originally, on failed navigations the webview we would fire a loadabort + // (for the failed navigation) and a loadcommit (for the error page). if (!navigation_handle->IsErrorPage()) return; } diff --git a/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper.cc b/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper.cc index 985550c131b..ab68297ccf5 100644 --- a/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper.cc +++ b/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper.cc @@ -279,9 +279,9 @@ void WebViewPermissionHelper::CancelGeolocationPermissionRequest( void WebViewPermissionHelper::RequestFileSystemPermission( const GURL& url, bool allowed_by_default, - const base::Callback<void(bool)>& callback) { + base::OnceCallback<void(bool)> callback) { web_view_permission_helper_delegate_->RequestFileSystemPermission( - url, allowed_by_default, callback); + url, allowed_by_default, std::move(callback)); } void WebViewPermissionHelper::FileSystemAccessedAsync(int render_process_id, diff --git a/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper.h b/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper.h index d368a2211e2..33cb12efa39 100644 --- a/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper.h +++ b/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper.h @@ -82,7 +82,7 @@ class WebViewPermissionHelper void RequestFileSystemPermission(const GURL& url, bool allowed_by_default, - const base::Callback<void(bool)>& callback); + base::OnceCallback<void(bool)> callback); // Called when file system access is requested by the guest content using the // asynchronous HTML5 file system API. The request is plumbed through the diff --git a/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper_delegate.h b/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper_delegate.h index 925bf95c81f..0aaecd8a884 100644 --- a/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper_delegate.h +++ b/chromium/extensions/browser/guest_view/web_view/web_view_permission_helper_delegate.h @@ -42,7 +42,7 @@ class WebViewPermissionHelperDelegate : public content::WebContentsObserver { virtual void RequestFileSystemPermission( const GURL& url, bool allowed_by_default, - const base::Callback<void(bool)>& callback) {} + base::OnceCallback<void(bool)> callback) {} // Called when file system access is requested by the guest content using the // asynchronous HTML5 file system API. The request is plumbed through the diff --git a/chromium/extensions/browser/image_loader.cc b/chromium/extensions/browser/image_loader.cc index d5e674cfb1e..7c58a7e0896 100644 --- a/chromium/extensions/browser/image_loader.cc +++ b/chromium/extensions/browser/image_loader.cc @@ -263,8 +263,9 @@ void ImageLoader::LoadImagesAsync( const std::vector<ImageRepresentation>& info_list, ImageLoaderImageCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(LoadImagesBlocking, info_list, LoadResourceBitmaps(extension, info_list)), base::BindOnce(&ImageLoader::ReplyBack, weak_ptr_factory_.GetWeakPtr(), @@ -276,8 +277,9 @@ void ImageLoader::LoadImageFamilyAsync( const std::vector<ImageRepresentation>& info_list, ImageLoaderImageFamilyCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(LoadImagesBlocking, info_list, LoadResourceBitmaps(extension, info_list)), base::BindOnce(&ImageLoader::ReplyBackWithImageFamily, diff --git a/chromium/extensions/browser/image_sanitizer_unittest.cc b/chromium/extensions/browser/image_sanitizer_unittest.cc index a14e2b6cfe5..3c233a8c1aa 100644 --- a/chromium/extensions/browser/image_sanitizer_unittest.cc +++ b/chromium/extensions/browser/image_sanitizer_unittest.cc @@ -16,7 +16,7 @@ #include "base/strings/string_number_conversions.h" #include "base/task/post_task.h" #include "build/build_config.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "services/data_decoder/public/cpp/test_data_decoder_service.h" #include "services/data_decoder/public/mojom/constants.mojom.h" #include "testing/gtest/include/gtest/gtest.h" @@ -189,7 +189,7 @@ class ImageSanitizerTest : public testing::Test { decoded_image_callback_called_ = true; } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; service_manager::TestConnectorFactory connector_factory_; std::unique_ptr<service_manager::Connector> connector_; std::unique_ptr<service_manager::Service> test_data_decoder_service_; diff --git a/chromium/extensions/browser/info_map.cc b/chromium/extensions/browser/info_map.cc index 39c077a3ed2..497e73e42dd 100644 --- a/chromium/extensions/browser/info_map.cc +++ b/chromium/extensions/browser/info_map.cc @@ -12,7 +12,6 @@ #include "extensions/common/extension_resource.h" #include "extensions/common/extension_set.h" #include "extensions/common/manifest_handlers/incognito_info.h" -#include "extensions/common/manifest_handlers/shared_module_info.h" #include "extensions/common/permissions/permissions_data.h" #include "url/gurl.h" @@ -138,64 +137,6 @@ void InfoMap::UnregisterAllExtensionsInProcess(int process_id) { process_map_.RemoveAllFromProcess(process_id); } -// This function is security sensitive. Bugs could cause problems that break -// restrictions on local file access or NaCl's validation caching. If you modify -// this function, please get a security review from a NaCl person. -bool InfoMap::MapUrlToLocalFilePath(const GURL& file_url, - bool use_blocking_api, - base::FilePath* file_path) { - // Check that the URL is recognized by the extension system. - const Extension* extension = extensions_.GetExtensionOrAppByURL(file_url); - if (!extension) - return false; - - // This is a short-cut which avoids calling a blocking file operation - // (GetFilePath()), so that this can be called on the IO thread. It only - // handles a subset of the urls. - if (!use_blocking_api) { - if (file_url.SchemeIs(extensions::kExtensionScheme)) { - std::string path = file_url.path(); - base::TrimString(path, "/", &path); // Remove first slash - *file_path = extension->path().AppendASCII(path); - return true; - } - return false; - } - - std::string path = file_url.path(); - ExtensionResource resource; - - if (SharedModuleInfo::IsImportedPath(path)) { - // Check if this is a valid path that is imported for this extension. - std::string new_extension_id; - std::string new_relative_path; - SharedModuleInfo::ParseImportedPath( - path, &new_extension_id, &new_relative_path); - const Extension* new_extension = extensions_.GetByID(new_extension_id); - if (!new_extension) - return false; - - if (!SharedModuleInfo::ImportsExtensionById(extension, new_extension_id)) - return false; - - resource = new_extension->GetResource(new_relative_path); - } else { - // Check that the URL references a resource in the extension. - resource = extension->GetResource(path); - } - - if (resource.empty()) - return false; - - // GetFilePath is a blocking function call. - const base::FilePath resource_file_path = resource.GetFilePath(); - if (resource_file_path.empty()) - return false; - - *file_path = resource_file_path; - return true; -} - QuotaService* InfoMap::GetQuotaService() { CheckOnValidThread(); if (!quota_service_) diff --git a/chromium/extensions/browser/info_map.h b/chromium/extensions/browser/info_map.h index 414cebabcff..e56bf890d88 100644 --- a/chromium/extensions/browser/info_map.h +++ b/chromium/extensions/browser/info_map.h @@ -16,10 +16,6 @@ #include "extensions/common/extension_set.h" #include "extensions/common/permissions/api_permission.h" -namespace base { -class FilePath; -} - namespace extensions { class ContentVerifier; class Extension; @@ -72,13 +68,6 @@ class InfoMap : public base::RefCountedThreadSafe< int site_instance_id); void UnregisterAllExtensionsInProcess(int process_id); - // Maps a |file_url| to a |file_path| on the local filesystem, including - // resources in extensions. Returns true on success. See NaClBrowserDelegate - // for full details. - bool MapUrlToLocalFilePath(const GURL& file_url, - bool use_blocking_api, - base::FilePath* file_path); - // Returns the IO thread QuotaService. Creates the instance on first call. QuotaService* GetQuotaService(); diff --git a/chromium/extensions/browser/info_map_unittest.cc b/chromium/extensions/browser/info_map_unittest.cc index 5a8d6e094b5..c3d9ea8d73c 100644 --- a/chromium/extensions/browser/info_map_unittest.cc +++ b/chromium/extensions/browser/info_map_unittest.cc @@ -5,7 +5,7 @@ #include "extensions/browser/info_map.h" #include "base/path_service.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" #include "extensions/common/extension_paths.h" @@ -21,7 +21,7 @@ class InfoMapTest : public testing::Test { InfoMapTest() = default; private: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; // Returns a barebones test Extension object with the given name. @@ -79,38 +79,4 @@ TEST_F(InfoMapTest, Properties) { EXPECT_EQ(extension2.get(), info_map->extensions().GetByID(extension2->id())); } -// Tests that extension URLs are properly mapped to local file paths. -TEST_F(InfoMapTest, MapUrlToLocalFilePath) { - scoped_refptr<InfoMap> info_map(new InfoMap()); - scoped_refptr<const Extension> app(CreateExtension("platform_app")); - info_map->AddExtension(app.get(), base::Time(), false, false); - - // Non-extension URLs don't map to anything. - base::FilePath non_extension_path; - GURL non_extension_url("http://not-an-extension.com/"); - EXPECT_FALSE(info_map->MapUrlToLocalFilePath( - non_extension_url, false, &non_extension_path)); - EXPECT_TRUE(non_extension_path.empty()); - - // Valid resources return a valid path. - base::FilePath valid_path; - GURL valid_url = app->GetResourceURL("manifest.json"); - EXPECT_TRUE(info_map->MapUrlToLocalFilePath( - valid_url, true /* use_blocking_api */, &valid_path)); - EXPECT_FALSE(valid_path.empty()); - - // A file must exist to be mapped to a path using the blocking API. - base::FilePath does_not_exist_path; - GURL does_not_exist_url = app->GetResourceURL("does-not-exist.html"); - EXPECT_FALSE(info_map->MapUrlToLocalFilePath( - does_not_exist_url, true /* use_blocking_api */, &does_not_exist_path)); - EXPECT_TRUE(does_not_exist_path.empty()); - - // A file does not need to exist to be mapped to a path with the non-blocking - // API. This avoids hitting the disk to see if it exists. - EXPECT_TRUE(info_map->MapUrlToLocalFilePath( - does_not_exist_url, false /* use_blocking_api */, &does_not_exist_path)); - EXPECT_FALSE(does_not_exist_path.empty()); -} - } // namespace extensions diff --git a/chromium/extensions/browser/io_thread_extension_message_filter.cc b/chromium/extensions/browser/io_thread_extension_message_filter.cc index 7f6190e49f2..02dce5693da 100644 --- a/chromium/extensions/browser/io_thread_extension_message_filter.cc +++ b/chromium/extensions/browser/io_thread_extension_message_filter.cc @@ -6,10 +6,6 @@ #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/resource_dispatcher_host.h" -#include "extensions/browser/extension_function_dispatcher.h" -#include "extensions/browser/extension_system.h" -#include "extensions/browser/info_map.h" #include "extensions/common/extension_messages.h" #include "ipc/ipc_message_macros.h" @@ -17,13 +13,8 @@ using content::BrowserThread; namespace extensions { -IOThreadExtensionMessageFilter::IOThreadExtensionMessageFilter( - int render_process_id, - content::BrowserContext* context) - : BrowserMessageFilter(ExtensionMsgStart), - render_process_id_(render_process_id), - browser_context_id_(context), - extension_info_map_(ExtensionSystem::Get(context)->info_map()) { +IOThreadExtensionMessageFilter::IOThreadExtensionMessageFilter() + : BrowserMessageFilter(ExtensionMsgStart) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } @@ -43,10 +34,6 @@ bool IOThreadExtensionMessageFilter::OnMessageReceived( IPC_BEGIN_MESSAGE_MAP(IOThreadExtensionMessageFilter, message) IPC_MESSAGE_HANDLER(ExtensionHostMsg_GenerateUniqueID, OnExtensionGenerateUniqueID) - IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestForIOThread, - OnExtensionRequestForIOThread) - IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestWorkerForIOThread, - OnExtensionRequestWorkerForIOThread) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; @@ -58,21 +45,4 @@ void IOThreadExtensionMessageFilter::OnExtensionGenerateUniqueID( *unique_id = ++next_unique_id; } -void IOThreadExtensionMessageFilter::OnExtensionRequestForIOThread( - int routing_id, - const ExtensionHostMsg_Request_Params& params) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - ExtensionFunctionDispatcher::DispatchOnIOThread( - extension_info_map_.get(), browser_context_id_, render_process_id_, - weak_ptr_factory_.GetWeakPtr(), routing_id, params); -} - -void IOThreadExtensionMessageFilter::OnExtensionRequestWorkerForIOThread( - const ExtensionHostMsg_Request_Params& params) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - ExtensionFunctionDispatcher::DispatchOnIOThreadForServiceWorker( - extension_info_map_.get(), browser_context_id_, render_process_id_, - weak_ptr_factory_.GetWeakPtr(), params); -} - } // namespace extensions diff --git a/chromium/extensions/browser/io_thread_extension_message_filter.h b/chromium/extensions/browser/io_thread_extension_message_filter.h index 091dad9f627..4b67c55ae17 100644 --- a/chromium/extensions/browser/io_thread_extension_message_filter.h +++ b/chromium/extensions/browser/io_thread_extension_message_filter.h @@ -5,30 +5,16 @@ #ifndef EXTENSIONS_BROWSER_IO_THREAD_EXTENSION_MESSAGE_FILTER_H_ #define EXTENSIONS_BROWSER_IO_THREAD_EXTENSION_MESSAGE_FILTER_H_ -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" #include "content/public/browser/browser_message_filter.h" -struct ExtensionHostMsg_Request_Params; - -namespace content { -class BrowserContext; -} - namespace extensions { -class InfoMap; - // This class filters out incoming extension-specific IPC messages from the // renderer process. It is created on the UI thread, but handles messages on the // IO thread and is destroyed there. class IOThreadExtensionMessageFilter : public content::BrowserMessageFilter { public: - IOThreadExtensionMessageFilter(int render_process_id, - content::BrowserContext* context); - - int render_process_id() { return render_process_id_; } + IOThreadExtensionMessageFilter(); private: friend class base::DeleteHelper<IOThreadExtensionMessageFilter>; @@ -42,22 +28,6 @@ class IOThreadExtensionMessageFilter : public content::BrowserMessageFilter { // Message handlers on the IO thread. void OnExtensionGenerateUniqueID(int* unique_id); - void OnExtensionRequestForIOThread( - int routing_id, - const ExtensionHostMsg_Request_Params& params); - void OnExtensionRequestWorkerForIOThread( - const ExtensionHostMsg_Request_Params& params); - - const int render_process_id_; - - // The browser context as a void pointer, for use as an identifier on the IO - // thread. - void* browser_context_id_; - - scoped_refptr<extensions::InfoMap> extension_info_map_; - - // Weak pointers produced by this factory are bound to the IO thread. - base::WeakPtrFactory<IOThreadExtensionMessageFilter> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(IOThreadExtensionMessageFilter); }; diff --git a/chromium/extensions/browser/json_file_sanitizer_unittest.cc b/chromium/extensions/browser/json_file_sanitizer_unittest.cc index a6c31cbdec1..eca53b8468b 100644 --- a/chromium/extensions/browser/json_file_sanitizer_unittest.cc +++ b/chromium/extensions/browser/json_file_sanitizer_unittest.cc @@ -11,7 +11,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "services/data_decoder/public/cpp/test_data_decoder_service.h" #include "services/data_decoder/public/mojom/constants.mojom.h" #include "testing/gtest/include/gtest/gtest.h" @@ -77,7 +77,7 @@ class JsonFileSanitizerTest : public testing::Test { std::move(done_callback_).Run(); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; data_decoder::TestDataDecoderService test_data_decoder_service_; JsonFileSanitizer::Status last_status_; std::string last_error_; diff --git a/chromium/extensions/browser/lazy_background_task_queue.cc b/chromium/extensions/browser/lazy_background_task_queue.cc index 523134fd464..b97fba12ce3 100644 --- a/chromium/extensions/browser/lazy_background_task_queue.cc +++ b/chromium/extensions/browser/lazy_background_task_queue.cc @@ -13,7 +13,6 @@ #include "content/public/browser/site_instance.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/extension_host.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/lazy_background_task_queue_factory.h" #include "extensions/browser/lazy_context_id.h" @@ -43,7 +42,7 @@ bool CreateLazyBackgroundHost(ProcessManager* pm, const Extension* extension) { LazyBackgroundTaskQueue::LazyBackgroundTaskQueue( content::BrowserContext* browser_context) - : browser_context_(browser_context), extension_registry_observer_(this) { + : browser_context_(browser_context) { registrar_.Add(this, extensions::NOTIFICATION_EXTENSION_HOST_DID_STOP_FIRST_LOAD, content::NotificationService::AllBrowserContextsAndSources()); diff --git a/chromium/extensions/browser/lazy_background_task_queue.h b/chromium/extensions/browser/lazy_background_task_queue.h index bf9f15c7393..8606ebca832 100644 --- a/chromium/extensions/browser/lazy_background_task_queue.h +++ b/chromium/extensions/browser/lazy_background_task_queue.h @@ -18,6 +18,7 @@ #include "components/keyed_service/core/keyed_service.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/browser/lazy_context_id.h" #include "extensions/browser/lazy_context_task_queue.h" @@ -30,7 +31,6 @@ class BrowserContext; namespace extensions { class Extension; class ExtensionHost; -class ExtensionRegistry; // This class maintains a queue of tasks that should execute when an // extension's lazy background page is loaded. It is also in charge of loading @@ -114,7 +114,7 @@ class LazyBackgroundTaskQueue : public KeyedService, PendingTasksMap pending_tasks_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; DISALLOW_COPY_AND_ASSIGN(LazyBackgroundTaskQueue); }; diff --git a/chromium/extensions/browser/lazy_background_task_queue_unittest.cc b/chromium/extensions/browser/lazy_background_task_queue_unittest.cc index f7c4cee8743..97e81e6be7d 100644 --- a/chromium/extensions/browser/lazy_background_task_queue_unittest.cc +++ b/chromium/extensions/browser/lazy_background_task_queue_unittest.cc @@ -92,7 +92,8 @@ class LazyBackgroundTaskQueueTest : public ExtensionsTest { scoped_refptr<const Extension> CreateLazyBackgroundExtension() { scoped_refptr<const Extension> extension = ExtensionBuilder("Lazy background") - .SetBackgroundPage(ExtensionBuilder::BackgroundPage::EVENT) + .SetBackgroundContext( + ExtensionBuilder::BackgroundContext::EVENT_PAGE) .SetID("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") .Build(); ExtensionRegistry::Get(browser_context())->AddEnabled(extension); @@ -222,7 +223,7 @@ TEST_F(LazyBackgroundTaskQueueTest, CreateLazyBackgroundPageOnExtensionLoaded) { scoped_refptr<const Extension> lazy_background = ExtensionBuilder("Lazy background") - .SetBackgroundPage(ExtensionBuilder::BackgroundPage::EVENT) + .SetBackgroundContext(ExtensionBuilder::BackgroundContext::EVENT_PAGE) .SetID("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") .Build(); diff --git a/chromium/extensions/browser/lazy_context_id.cc b/chromium/extensions/browser/lazy_context_id.cc index f829a546082..e360ff7fa96 100644 --- a/chromium/extensions/browser/lazy_context_id.cc +++ b/chromium/extensions/browser/lazy_context_id.cc @@ -6,6 +6,7 @@ #include "extensions/browser/lazy_background_task_queue.h" #include "extensions/browser/service_worker_task_queue.h" +#include "extensions/browser/task_queue_util.h" namespace extensions { @@ -22,10 +23,7 @@ LazyContextId::LazyContextId(content::BrowserContext* context, service_worker_scope_(service_worker_scope) {} LazyContextTaskQueue* LazyContextId::GetTaskQueue() const { - if (is_for_event_page()) - return LazyBackgroundTaskQueue::Get(context_); - DCHECK(is_for_service_worker()); - return ServiceWorkerTaskQueue::Get(context_); + return GetTaskQueueForLazyContextId(*this); } } // namespace extensions diff --git a/chromium/extensions/browser/mojo/keep_alive_impl.cc b/chromium/extensions/browser/mojo/keep_alive_impl.cc index 9de0d43cbb7..c4b3577c7ef 100644 --- a/chromium/extensions/browser/mojo/keep_alive_impl.cc +++ b/chromium/extensions/browser/mojo/keep_alive_impl.cc @@ -8,7 +8,6 @@ #include "base/bind.h" #include "content/public/browser/browser_context.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/process_manager.h" namespace extensions { @@ -27,7 +26,6 @@ KeepAliveImpl::KeepAliveImpl(content::BrowserContext* context, KeepAliveRequest request) : context_(context), extension_(extension), - extension_registry_observer_(this), binding_(this, std::move(request)) { ProcessManager::Get(context_)->IncrementLazyKeepaliveCount( extension_, Activity::MOJO, std::string()); diff --git a/chromium/extensions/browser/mojo/keep_alive_impl.h b/chromium/extensions/browser/mojo/keep_alive_impl.h index a65517bde5b..98d2e79f978 100644 --- a/chromium/extensions/browser/mojo/keep_alive_impl.h +++ b/chromium/extensions/browser/mojo/keep_alive_impl.h @@ -8,6 +8,7 @@ #include "base/callback.h" #include "base/macros.h" #include "base/scoped_observer.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/common/mojom/keep_alive.mojom.h" #include "mojo/public/cpp/bindings/binding.h" @@ -48,7 +49,8 @@ class KeepAliveImpl : public KeepAlive, public ExtensionRegistryObserver { content::BrowserContext* context_; const Extension* extension_; - ScopedObserver<ExtensionRegistry, KeepAliveImpl> extension_registry_observer_; + ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> + extension_registry_observer_{this}; mojo::Binding<KeepAlive> binding_; DISALLOW_COPY_AND_ASSIGN(KeepAliveImpl); diff --git a/chromium/extensions/browser/pref_names.cc b/chromium/extensions/browser/pref_names.cc index 896f1358d30..4f139e55cb1 100644 --- a/chromium/extensions/browser/pref_names.cc +++ b/chromium/extensions/browser/pref_names.cc @@ -33,8 +33,6 @@ const char kAllowedTypes[] = "extensions.allowed_types"; const char kAppFullscreenAllowed[] = "apps.fullscreen.allowed"; const char kExtensions[] = "extensions.settings"; const char kExtensionManagement[] = "extensions.management"; -const char kInsecureExtensionUpdatesEnabled[] = - "extension_updates.insecure_extension_updates_enabled"; const char kInstallAllowList[] = "extensions.install.allowlist"; const char kInstallDenyList[] = "extensions.install.denylist"; const char kInstallForceList[] = "extensions.install.forcelist"; diff --git a/chromium/extensions/browser/preload_check_group_unittest.cc b/chromium/extensions/browser/preload_check_group_unittest.cc index c0810f99df2..c0d31dcbca2 100644 --- a/chromium/extensions/browser/preload_check_group_unittest.cc +++ b/chromium/extensions/browser/preload_check_group_unittest.cc @@ -5,7 +5,7 @@ #include <memory> #include <vector> -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "extensions/browser/preload_check_group.h" #include "extensions/browser/preload_check_test_util.h" #include "testing/gmock/include/gmock/gmock.h" @@ -51,7 +51,7 @@ class PreloadCheckGroupTest : public testing::Test { private: // Required for the asynchronous tests. - base::test::ScopedTaskEnvironment scoped_task_environment_; + base::test::SingleThreadTaskEnvironment task_environment_; }; // Tests multiple succeeding checks. diff --git a/chromium/extensions/browser/process_manager.cc b/chromium/extensions/browser/process_manager.cc index e0f053ce45b..55dcd62be9f 100644 --- a/chromium/extensions/browser/process_manager.cc +++ b/chromium/extensions/browser/process_manager.cc @@ -27,7 +27,6 @@ #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_frame_host.h" -#include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" @@ -255,11 +254,10 @@ ProcessManager::ProcessManager(BrowserContext* context, : extension_registry_(extension_registry), site_instance_(content::SiteInstance::Create(context)), browser_context_(context), - worker_task_runner_(base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})), + worker_task_runner_( + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO})), startup_background_hosts_created_(false), - last_background_close_sequence_id_(0), - process_observer_(this) { + last_background_close_sequence_id_(0) { // ExtensionRegistry is shared between incognito and regular contexts. DCHECK_EQ(original_context, extension_registry_->browser_context()); extension_registry_->AddObserver(this); diff --git a/chromium/extensions/browser/process_manager.h b/chromium/extensions/browser/process_manager.h index 70b0a1a74ec..7a436011189 100644 --- a/chromium/extensions/browser/process_manager.h +++ b/chromium/extensions/browser/process_manager.h @@ -24,6 +24,7 @@ #include "content/public/browser/devtools_agent_host_observer.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" +#include "content/public/browser/render_process_host.h" #include "content/public/browser/render_process_host_observer.h" #include "extensions/browser/activity.h" #include "extensions/browser/event_page_tracker.h" @@ -387,7 +388,7 @@ class ProcessManager : public KeyedService, // Observers of Service Worker RPH this ProcessManager manages. ScopedObserver<content::RenderProcessHost, content::RenderProcessHostObserver> - process_observer_; + process_observer_{this}; // Maps render render_process_id -> extension_id for all Service Workers this // ProcessManager manages. std::map<int, std::set<ExtensionId>> worker_process_to_extension_ids_; diff --git a/chromium/extensions/browser/quota_service_unittest.cc b/chromium/extensions/browser/quota_service_unittest.cc index c5a69012a2e..e6d0cb1ce96 100644 --- a/chromium/extensions/browser/quota_service_unittest.cc +++ b/chromium/extensions/browser/quota_service_unittest.cc @@ -8,7 +8,7 @@ #include "base/process/process.h" #include "base/run_loop.h" #include "base/strings/string_util.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/extension_function.h" #include "extensions/browser/quota_service.h" #include "testing/gtest/include/gtest/gtest.h" @@ -61,7 +61,6 @@ class MockFunction : public ExtensionFunction { public: explicit MockFunction(const char* name) { set_name(name); } - void Destruct() const override { delete this; } ResponseAction Run() override { return RespondLater(); } protected: @@ -110,7 +109,7 @@ class QuotaServiceTest : public testing::Test { std::string extension_b_; std::string extension_c_; std::unique_ptr<QuotaService> service_; - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; class QuotaLimitHeuristicTest : public testing::Test { diff --git a/chromium/extensions/browser/requirements_checker.cc b/chromium/extensions/browser/requirements_checker.cc index 307ba79571f..f2858eb5028 100644 --- a/chromium/extensions/browser/requirements_checker.cc +++ b/chromium/extensions/browser/requirements_checker.cc @@ -77,9 +77,9 @@ void RequirementsChecker::PostRunCallback() { // to maintain the assumption in // ExtensionService::LoadExtensionsFromCommandLineFlag(). Remove these helper // functions after crbug.com/708354 is addressed. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&RequirementsChecker::RunCallback, - weak_ptr_factory_.GetWeakPtr())); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&RequirementsChecker::RunCallback, + weak_ptr_factory_.GetWeakPtr())); } void RequirementsChecker::RunCallback() { diff --git a/chromium/extensions/browser/runtime_data_unittest.cc b/chromium/extensions/browser/runtime_data_unittest.cc index afc5f3c6bbe..f7355d12ba1 100644 --- a/chromium/extensions/browser/runtime_data_unittest.cc +++ b/chromium/extensions/browser/runtime_data_unittest.cc @@ -20,7 +20,8 @@ namespace { // Creates a very simple extension with a background page. scoped_refptr<const Extension> CreateExtensionWithBackgroundPage() { return ExtensionBuilder("test") - .SetBackgroundPage(ExtensionBuilder::BackgroundPage::PERSISTENT) + .SetBackgroundContext( + ExtensionBuilder::BackgroundContext::BACKGROUND_PAGE) .SetID("id2") .Build(); } diff --git a/chromium/extensions/browser/sandboxed_unpacker.cc b/chromium/extensions/browser/sandboxed_unpacker.cc index 5e60ac96251..17f70a1e7d4 100644 --- a/chromium/extensions/browser/sandboxed_unpacker.cc +++ b/chromium/extensions/browser/sandboxed_unpacker.cc @@ -26,7 +26,6 @@ #include "base/task/post_task.h" #include "build/build_config.h" #include "components/crx_file/crx_verifier.h" -#include "components/services/unzip/public/cpp/unzip.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/api/declarative_net_request/constants.h" @@ -218,8 +217,7 @@ base::Optional<crx_file::VerifierFormat> g_verifier_format_override_for_test; SandboxedUnpackerClient::SandboxedUnpackerClient() : RefCountedDeleteOnSequence<SandboxedUnpackerClient>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI})) { + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI})) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } diff --git a/chromium/extensions/browser/sandboxed_unpacker_unittest.cc b/chromium/extensions/browser/sandboxed_unpacker_unittest.cc index 2583203eff4..8c276cff6fe 100644 --- a/chromium/extensions/browser/sandboxed_unpacker_unittest.cc +++ b/chromium/extensions/browser/sandboxed_unpacker_unittest.cc @@ -17,11 +17,10 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "components/crx_file/id_util.h" -#include "components/services/unzip/public/cpp/test_unzip_service.h" -#include "components/services/unzip/public/mojom/constants.mojom.h" -#include "components/services/unzip/unzip_service.h" +#include "components/services/unzip/content/unzip_service.h" +#include "components/services/unzip/in_process_unzipper.h" #include "content/public/browser/browser_thread.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/extensions_test.h" #include "extensions/browser/install/crx_install_error.h" @@ -141,7 +140,7 @@ class MockSandboxedUnpackerClient : public SandboxedUnpackerClient { class SandboxedUnpackerTest : public ExtensionsTest { public: SandboxedUnpackerTest() - : ExtensionsTest(content::TestBrowserThreadBundle::IO_MAINLOOP) { + : ExtensionsTest(content::BrowserTaskEnvironment::IO_MAINLOOP) { test_connector_factory_.set_ignore_quit_requests(true); } @@ -153,13 +152,17 @@ class SandboxedUnpackerTest : public ExtensionsTest { // It will delete itself. client_ = new MockSandboxedUnpackerClient; - InitSanboxedUnpacker(/*data_decode_service=*/nullptr, - /*unzip_service=*/nullptr); + InitSanboxedUnpacker(/*data_decode_service=*/nullptr); + + // By default, we host an in-process UnzipperImpl to support any service + // clients. Tests may explicitly override the launch callback to prevent + // this. + unzip::SetUnzipperLaunchOverrideForTesting( + base::BindRepeating(&unzip::LaunchInProcessUnzipper)); } void InitSanboxedUnpacker( - std::unique_ptr<service_manager::Service> data_decoder_service, - std::unique_ptr<service_manager::Service> unzip_service) { + std::unique_ptr<service_manager::Service> data_decoder_service) { if (data_decoder_service) { data_decoder_service_ = std::move(data_decoder_service); } else { @@ -168,13 +171,6 @@ class SandboxedUnpackerTest : public ExtensionsTest { RegisterDataDecoder()); } - if (unzip_service) { - unzip_service_ = std::move(unzip_service); - } else { - unzip_service_ = - std::make_unique<unzip::UnzipService>(RegisterUnzipService()); - } - connector_ = test_connector_factory_.CreateConnector(); sandboxed_unpacker_ = @@ -188,11 +184,8 @@ class SandboxedUnpackerTest : public ExtensionsTest { data_decoder::mojom::kServiceName); } - service_manager::mojom::ServiceRequest RegisterUnzipService() { - return test_connector_factory_.RegisterInstance(unzip::mojom::kServiceName); - } - void TearDown() override { + unzip::SetUnzipperLaunchOverrideForTesting(base::NullCallback()); // Need to destruct SandboxedUnpacker before the message loop since // it posts a task to it. sandboxed_unpacker_ = nullptr; @@ -285,7 +278,6 @@ class SandboxedUnpackerTest : public ExtensionsTest { std::unique_ptr<service_manager::Connector> connector_; std::unique_ptr<service_manager::Service> data_decoder_service_; - std::unique_ptr<service_manager::Service> unzip_service_; }; TEST_F(SandboxedUnpackerTest, EmptyDefaultLocale) { @@ -475,9 +467,15 @@ TEST_F(SandboxedUnpackerTest, SkipHashCheck) { // The following tests simulate the utility services failling. TEST_F(SandboxedUnpackerTest, UnzipperServiceFails) { - InitSanboxedUnpacker( - /*data_decoder_service=*/nullptr, - std::make_unique<unzip::CrashyUnzipService>(RegisterUnzipService())); + // We override the Unzipper's launching behavior to drop the interface + // receiver, effectively simulating a crashy service process. + unzip::SetUnzipperLaunchOverrideForTesting(base::BindRepeating([]() -> auto { + mojo::PendingRemote<unzip::mojom::Unzipper> remote; + ignore_result(remote.InitWithNewPipeAndPassReceiver()); + return remote; + })); + + InitSanboxedUnpacker(/*data_decoder_service=*/nullptr); SetupUnpacker("good_package.crx", ""); EXPECT_FALSE(InstallSucceeded()); EXPECT_FALSE(GetInstallErrorMessage().empty()); @@ -488,10 +486,8 @@ TEST_F(SandboxedUnpackerTest, UnzipperServiceFails) { } TEST_F(SandboxedUnpackerTest, JsonParserFails) { - InitSanboxedUnpacker( - std::make_unique<data_decoder::CrashyDataDecoderService>( - RegisterDataDecoder(), /*crash_json=*/true, /*crash_image=*/false), - /*unzip_service=*/nullptr); + InitSanboxedUnpacker(std::make_unique<data_decoder::CrashyDataDecoderService>( + RegisterDataDecoder(), /*crash_json=*/true, /*crash_image=*/false)); SetupUnpacker("good_package.crx", ""); EXPECT_FALSE(InstallSucceeded()); EXPECT_FALSE(GetInstallErrorMessage().empty()); @@ -500,10 +496,8 @@ TEST_F(SandboxedUnpackerTest, JsonParserFails) { } TEST_F(SandboxedUnpackerTest, ImageDecoderFails) { - InitSanboxedUnpacker( - std::make_unique<data_decoder::CrashyDataDecoderService>( - RegisterDataDecoder(), /*crash_json=*/false, /*crash_image=*/true), - /*unzip_service=*/nullptr); + InitSanboxedUnpacker(std::make_unique<data_decoder::CrashyDataDecoderService>( + RegisterDataDecoder(), /*crash_json=*/false, /*crash_image=*/true)); SetupUnpacker("good_package.crx", ""); EXPECT_FALSE(InstallSucceeded()); EXPECT_FALSE(GetInstallErrorMessage().empty()); diff --git a/chromium/extensions/browser/service_worker_manager.cc b/chromium/extensions/browser/service_worker_manager.cc index 9fa18be96bc..cc809658c38 100644 --- a/chromium/extensions/browser/service_worker_manager.cc +++ b/chromium/extensions/browser/service_worker_manager.cc @@ -9,13 +9,12 @@ #include "content/public/browser/browser_context.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/storage_partition.h" -#include "extensions/browser/extension_registry.h" namespace extensions { ServiceWorkerManager::ServiceWorkerManager( content::BrowserContext* browser_context) - : browser_context_(browser_context), registry_observer_(this) { + : browser_context_(browser_context) { registry_observer_.Add(ExtensionRegistry::Get(browser_context_)); } diff --git a/chromium/extensions/browser/service_worker_manager.h b/chromium/extensions/browser/service_worker_manager.h index 48889f5d818..2fa6e6112f4 100644 --- a/chromium/extensions/browser/service_worker_manager.h +++ b/chromium/extensions/browser/service_worker_manager.h @@ -7,6 +7,7 @@ #include "base/macros.h" #include "base/scoped_observer.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" namespace content { @@ -35,7 +36,7 @@ class ServiceWorkerManager : public ExtensionRegistryObserver { content::BrowserContext* browser_context_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - registry_observer_; + registry_observer_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerManager); }; diff --git a/chromium/extensions/browser/service_worker_task_queue.cc b/chromium/extensions/browser/service_worker_task_queue.cc index 7f43eb3e986..b4754609045 100644 --- a/chromium/extensions/browser/service_worker_task_queue.cc +++ b/chromium/extensions/browser/service_worker_task_queue.cc @@ -70,11 +70,10 @@ void ServiceWorkerTaskQueue::DidStartWorkerForScopeOnIO( int process_id, int thread_id) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ServiceWorkerTaskQueue::DidStartWorkerForScope, - task_queue, context_id, version_id, process_id, - thread_id)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ServiceWorkerTaskQueue::DidStartWorkerForScope, + task_queue, context_id, version_id, process_id, + thread_id)); } // static @@ -241,8 +240,7 @@ void ServiceWorkerTaskQueue::RunTasksAfterStartWorker( partition->GetServiceWorkerContext(); content::ServiceWorkerContext::RunTask( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}), FROM_HERE, service_worker_context, base::BindOnce(&ServiceWorkerTaskQueue::StartServiceWorkerOnIOToRunTasks, weak_factory_.GetWeakPtr(), context_id, @@ -290,14 +288,20 @@ void ServiceWorkerTaskQueue::DidUnregisterServiceWorker( base::Version ServiceWorkerTaskQueue::RetrieveRegisteredServiceWorkerVersion( const ExtensionId& extension_id) { + std::string version_string; + if (browser_context_->IsOffTheRecord()) { + auto it = off_the_record_registrations_.find(extension_id); + return it != off_the_record_registrations_.end() ? it->second + : base::Version(); + } const base::DictionaryValue* info = nullptr; - if (!ExtensionPrefs::Get(browser_context_) - ->ReadPrefAsDictionary(extension_id, - kPrefServiceWorkerRegistrationInfo, &info)) { - return base::Version(); + ExtensionPrefs::Get(browser_context_) + ->ReadPrefAsDictionary(extension_id, kPrefServiceWorkerRegistrationInfo, + &info); + if (info != nullptr) { + info->GetString(kServiceWorkerVersion, &version_string); } - std::string version_string; - info->GetString(kServiceWorkerVersion, &version_string); + return base::Version(version_string); } @@ -305,18 +309,26 @@ void ServiceWorkerTaskQueue::SetRegisteredServiceWorkerInfo( const ExtensionId& extension_id, const base::Version& version) { DCHECK(version.IsValid()); - auto info = std::make_unique<base::DictionaryValue>(); - info->SetString(kServiceWorkerVersion, version.GetString()); - ExtensionPrefs::Get(browser_context_) - ->UpdateExtensionPref(extension_id, kPrefServiceWorkerRegistrationInfo, - std::move(info)); + if (browser_context_->IsOffTheRecord()) { + off_the_record_registrations_[extension_id] = version; + } else { + auto info = std::make_unique<base::DictionaryValue>(); + info->SetString(kServiceWorkerVersion, version.GetString()); + ExtensionPrefs::Get(browser_context_) + ->UpdateExtensionPref(extension_id, kPrefServiceWorkerRegistrationInfo, + std::move(info)); + } } void ServiceWorkerTaskQueue::RemoveRegisteredServiceWorkerInfo( const ExtensionId& extension_id) { - ExtensionPrefs::Get(browser_context_) - ->UpdateExtensionPref(extension_id, kPrefServiceWorkerRegistrationInfo, - nullptr); + if (browser_context_->IsOffTheRecord()) { + off_the_record_registrations_.erase(extension_id); + } else { + ExtensionPrefs::Get(browser_context_) + ->UpdateExtensionPref(extension_id, kPrefServiceWorkerRegistrationInfo, + nullptr); + } } void ServiceWorkerTaskQueue::RunPendingTasksIfWorkerReady( diff --git a/chromium/extensions/browser/service_worker_task_queue.h b/chromium/extensions/browser/service_worker_task_queue.h index c1475959465..d487afd5bed 100644 --- a/chromium/extensions/browser/service_worker_task_queue.h +++ b/chromium/extensions/browser/service_worker_task_queue.h @@ -7,6 +7,7 @@ #include <map> #include <set> +#include <unordered_map> #include <vector> #include "base/memory/weak_ptr.h" @@ -151,6 +152,13 @@ class ServiceWorkerTaskQueue : public KeyedService, content::BrowserContext* const browser_context_ = nullptr; + // A map of Service Worker registrations if this instance is for an + // off-the-record BrowserContext. These are stored in the ExtensionPrefs + // for a regular profile. + // TODO(crbug.com/939664): Make this better by passing in something that + // will manage storing and retrieving this data. + std::unordered_map<ExtensionId, base::Version> off_the_record_registrations_; + base::WeakPtrFactory<ServiceWorkerTaskQueue> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerTaskQueue); diff --git a/chromium/extensions/browser/service_worker_task_queue_factory.cc b/chromium/extensions/browser/service_worker_task_queue_factory.cc index 82704f428a9..b62d2c1c1e3 100644 --- a/chromium/extensions/browser/service_worker_task_queue_factory.cc +++ b/chromium/extensions/browser/service_worker_task_queue_factory.cc @@ -6,7 +6,6 @@ #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/extension_registry_factory.h" -#include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/service_worker_task_queue.h" using content::BrowserContext; @@ -40,8 +39,7 @@ KeyedService* ServiceWorkerTaskQueueFactory::BuildServiceInstanceFor( BrowserContext* ServiceWorkerTaskQueueFactory::GetBrowserContextToUse( BrowserContext* context) const { - // Redirected in incognito. - return ExtensionsBrowserClient::Get()->GetOriginalContext(context); + return context; } } // namespace extensions diff --git a/chromium/extensions/browser/shared_user_script_master.cc b/chromium/extensions/browser/shared_user_script_master.cc index b0cda1695db..9d573c7d116 100644 --- a/chromium/extensions/browser/shared_user_script_master.cc +++ b/chromium/extensions/browser/shared_user_script_master.cc @@ -4,7 +4,6 @@ #include "extensions/browser/shared_user_script_master.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_util.h" #include "extensions/common/host_id.h" #include "extensions/common/manifest_handlers/content_scripts_handler.h" @@ -16,8 +15,7 @@ SharedUserScriptMaster::SharedUserScriptMaster( : loader_(browser_context, HostID(), true /* listen_for_extension_system_loaded */), - browser_context_(browser_context), - extension_registry_observer_(this) { + browser_context_(browser_context) { extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_)); } diff --git a/chromium/extensions/browser/shared_user_script_master.h b/chromium/extensions/browser/shared_user_script_master.h index 8c4462229c2..3a5b005cafd 100644 --- a/chromium/extensions/browser/shared_user_script_master.h +++ b/chromium/extensions/browser/shared_user_script_master.h @@ -10,6 +10,7 @@ #include "base/macros.h" #include "base/scoped_observer.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/browser/extension_user_script_loader.h" #include "extensions/common/extension.h" @@ -21,8 +22,6 @@ class BrowserContext; namespace extensions { -class ExtensionRegistry; - // Manages statically-defined user scripts for all extensions. Owns a // UserScriptLoader to which file loading and shared memory management // operations are delegated. @@ -53,7 +52,7 @@ class SharedUserScriptMaster : public ExtensionRegistryObserver { content::BrowserContext* browser_context_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; DISALLOW_COPY_AND_ASSIGN(SharedUserScriptMaster); }; diff --git a/chromium/extensions/browser/state_store.cc b/chromium/extensions/browser/state_store.cc index 8944c3a07ee..7516687481b 100644 --- a/chromium/extensions/browser/state_store.cc +++ b/chromium/extensions/browser/state_store.cc @@ -15,7 +15,6 @@ #include "content/public/browser/browser_context.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/value_store/value_store_factory.h" #include "extensions/common/extension.h" @@ -76,8 +75,7 @@ StateStore::StateStore(content::BrowserContext* context, ValueStoreFrontend::BackendType backend_type, bool deferred_load) : store_(new ValueStoreFrontend(store_factory, backend_type)), - task_queue_(new DelayedTaskQueue()), - extension_registry_observer_(this) { + task_queue_(new DelayedTaskQueue()) { extension_registry_observer_.Add(ExtensionRegistry::Get(context)); if (deferred_load) { diff --git a/chromium/extensions/browser/state_store.h b/chromium/extensions/browser/state_store.h index af44a32b136..db881acdf3a 100644 --- a/chromium/extensions/browser/state_store.h +++ b/chromium/extensions/browser/state_store.h @@ -15,6 +15,7 @@ #include "base/scoped_observer.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/browser/value_store/value_store_frontend.h" @@ -24,7 +25,6 @@ class BrowserContext; namespace extensions { -class ExtensionRegistry; class ValueStoreFactory; // A storage area for per-extension state that needs to be persisted to disk. @@ -123,7 +123,7 @@ class StateStore : public base::SupportsWeakPtr<StateStore>, content::NotificationRegistrar registrar_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; DISALLOW_COPY_AND_ASSIGN(StateStore); }; diff --git a/chromium/extensions/browser/task_queue_util.cc b/chromium/extensions/browser/task_queue_util.cc new file mode 100644 index 00000000000..5ab77e6b38e --- /dev/null +++ b/chromium/extensions/browser/task_queue_util.cc @@ -0,0 +1,128 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "extensions/browser/task_queue_util.h" + +#include "content/public/browser/browser_context.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/extensions_browser_client.h" +#include "extensions/browser/lazy_background_task_queue.h" +#include "extensions/browser/lazy_context_id.h" +#include "extensions/browser/service_worker_task_queue.h" +#include "extensions/common/extension.h" +#include "extensions/common/extension_id.h" +#include "extensions/common/manifest_handlers/background_info.h" +#include "extensions/common/manifest_handlers/incognito_info.h" + +namespace extensions { + +namespace { + +// Get the ServiceWorkerTaskQueue instance for the BrowserContext. +// +ServiceWorkerTaskQueue* GetServiceWorkerTaskQueueForBrowserContext( + content::BrowserContext* browser_context, + bool is_split_mode) { + content::BrowserContext* context_to_use = browser_context; + // Incognito extensions in split mode use their own task queue, while those + // in spanning mode use the task queue of the original BrowserContext. + if (browser_context->IsOffTheRecord() && !is_split_mode) { + context_to_use = + ExtensionsBrowserClient::Get()->GetOriginalContext(browser_context); + } + return ServiceWorkerTaskQueue::Get(context_to_use); +} + +// Get the ServiceWorkerTaskQueue instance for the extension. +// +// Only call this for a SW-based extension. +ServiceWorkerTaskQueue* GetServiceWorkerTaskQueueForExtension( + content::BrowserContext* browser_context, + const Extension* extension) { + DCHECK(BackgroundInfo::IsServiceWorkerBased(extension)); + return GetServiceWorkerTaskQueueForBrowserContext( + browser_context, IncognitoInfo::IsSplitMode(extension)); +} + +// Get the ServiceWorkerTaskQueue instance for the extension ID. +// +// Only call this for a SW-based extension. +ServiceWorkerTaskQueue* GetServiceWorkerTaskQueueForExtensionId( + content::BrowserContext* browser_context, + const ExtensionId& extension_id) { + // Incognito extensions in split mode use their own task queue, while those + // in spanning mode use the task queue of the original BrowserContext. + // This is an optimization to avoid looking up an Extension instance, + // since we only need it for the off-the-record case. + if (!browser_context->IsOffTheRecord()) { + return ServiceWorkerTaskQueue::Get(browser_context); + } + + const Extension* extension = ExtensionRegistry::Get(browser_context) + ->enabled_extensions() + .GetByID(extension_id); + DCHECK(extension); + return GetServiceWorkerTaskQueueForExtension(browser_context, extension); +} + +// Use a pointer-to-member function so we can use the same logic for the +// activation and deactivation paths. +using TaskQueueFunction = void (ServiceWorkerTaskQueue::*)(const Extension*); + +void DoTaskQueueFunction(content::BrowserContext* browser_context, + const Extension* extension, + TaskQueueFunction function) { + // This is only necessary for service worker-based extensions. + if (!BackgroundInfo::IsServiceWorkerBased(extension)) + return; + + ServiceWorkerTaskQueue* const queue = + ServiceWorkerTaskQueue::Get(browser_context); + (queue->*function)(extension); + + // There is a separate task queue for the off-the-record context + // for any extension running in split mode. + if (!ExtensionsBrowserClient::Get()->HasOffTheRecordContext( + browser_context) || + !IncognitoInfo::IsSplitMode(extension) || + !ExtensionsBrowserClient::Get()->IsExtensionIncognitoEnabled( + extension->id(), browser_context)) { + return; + } + + content::BrowserContext* off_the_record_context = + ExtensionsBrowserClient::Get()->GetOffTheRecordContext(browser_context); + DCHECK(off_the_record_context); + ServiceWorkerTaskQueue* const off_the_record_queue = + ServiceWorkerTaskQueue::Get(off_the_record_context); + (off_the_record_queue->*function)(extension); +} + +} // anonymous namespace + +LazyContextTaskQueue* GetTaskQueueForLazyContextId( + const LazyContextId& context_id) { + if (context_id.is_for_event_page()) + return LazyBackgroundTaskQueue::Get(context_id.browser_context()); + + DCHECK(context_id.is_for_service_worker()); + return GetServiceWorkerTaskQueueForExtensionId(context_id.browser_context(), + context_id.extension_id()); +} + +void ActivateTaskQueueForExtension(content::BrowserContext* browser_context, + const Extension* extension) { + DCHECK(!browser_context->IsOffTheRecord()); + DoTaskQueueFunction(browser_context, extension, + &ServiceWorkerTaskQueue::ActivateExtension); +} + +void DeactivateTaskQueueForExtension(content::BrowserContext* browser_context, + const Extension* extension) { + DCHECK(!browser_context->IsOffTheRecord()); + DoTaskQueueFunction(browser_context, extension, + &ServiceWorkerTaskQueue::DeactivateExtension); +} + +} // namespace extensions diff --git a/chromium/extensions/browser/task_queue_util.h b/chromium/extensions/browser/task_queue_util.h new file mode 100644 index 00000000000..1ebbec19b40 --- /dev/null +++ b/chromium/extensions/browser/task_queue_util.h @@ -0,0 +1,42 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef EXTENSIONS_BROWSER_TASK_QUEUE_UTIL_H_ +#define EXTENSIONS_BROWSER_TASK_QUEUE_UTIL_H_ + +namespace content { +class BrowserContext; +} // namespace content + +namespace extensions { +class Extension; +class LazyContextId; +class LazyContextTaskQueue; + +// Determines the correct task queue for |context_id|. +LazyContextTaskQueue* GetTaskQueueForLazyContextId( + const LazyContextId& context_id); + +// Activates the service worker task queue for |browser_context| and +// |extension|. This must be called only once when an extension is loaded +// and before queueing any tasks. +// +// This is called for all extensions, not just for service worker-based +// ones. +void ActivateTaskQueueForExtension(content::BrowserContext* browser_context, + const Extension* extension); + +// Deactivates the service worker task queue for |browser_context| and +// |extension|. This should be called when the extension is unloaded. Once +// it completes, it's safe to call ActivateTaskQueueForExtension if the +// extension is reloaded. +// +// This is called for all extensions, not just for service worker-based +// ones. +void DeactivateTaskQueueForExtension(content::BrowserContext* browser_context, + const Extension* extension); + +} // namespace extensions + +#endif // EXTENSIONS_BROWSER_TASK_QUEUE_UTIL_H_ diff --git a/chromium/extensions/browser/test_extension_registry_observer.cc b/chromium/extensions/browser/test_extension_registry_observer.cc index 35ceb3a6fde..9ac3d1d13c0 100644 --- a/chromium/extensions/browser/test_extension_registry_observer.cc +++ b/chromium/extensions/browser/test_extension_registry_observer.cc @@ -8,7 +8,6 @@ #include "base/macros.h" #include "base/run_loop.h" -#include "extensions/browser/extension_registry.h" namespace extensions { @@ -27,12 +26,12 @@ class TestExtensionRegistryObserver::Waiter { extension_ = extension; } - const Extension* extension() const { return extension_; } + const Extension* extension() const { return extension_.get(); } private: bool observed_; base::RunLoop run_loop_; - const Extension* extension_; + scoped_refptr<const Extension> extension_; DISALLOW_COPY_AND_ASSIGN(Waiter); }; @@ -51,7 +50,6 @@ TestExtensionRegistryObserver::TestExtensionRegistryObserver( loaded_waiter_(std::make_unique<Waiter>()), ready_waiter_(std::make_unique<Waiter>()), unloaded_waiter_(std::make_unique<Waiter>()), - extension_registry_observer_(this), extension_id_(extension_id) { extension_registry_observer_.Add(registry); } @@ -59,7 +57,8 @@ TestExtensionRegistryObserver::TestExtensionRegistryObserver( TestExtensionRegistryObserver::~TestExtensionRegistryObserver() { } -const Extension* TestExtensionRegistryObserver::WaitForExtensionUninstalled() { +scoped_refptr<const Extension> +TestExtensionRegistryObserver::WaitForExtensionUninstalled() { return Wait(&uninstalled_waiter_); } @@ -76,7 +75,8 @@ const Extension* TestExtensionRegistryObserver::WaitForExtensionLoaded() { return Wait(&loaded_waiter_); } -const Extension* TestExtensionRegistryObserver::WaitForExtensionUnloaded() { +scoped_refptr<const Extension> +TestExtensionRegistryObserver::WaitForExtensionUnloaded() { return Wait(&unloaded_waiter_); } diff --git a/chromium/extensions/browser/test_extension_registry_observer.h b/chromium/extensions/browser/test_extension_registry_observer.h index 04a80449b51..bfec3dde479 100644 --- a/chromium/extensions/browser/test_extension_registry_observer.h +++ b/chromium/extensions/browser/test_extension_registry_observer.h @@ -10,10 +10,10 @@ #include "base/macros.h" #include "base/scoped_observer.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" namespace extensions { -class ExtensionRegistry; // A helper class that listen for ExtensionRegistry notifications. class TestExtensionRegistryObserver : public ExtensionRegistryObserver { @@ -27,12 +27,14 @@ class TestExtensionRegistryObserver : public ExtensionRegistryObserver { ~TestExtensionRegistryObserver() override; // Waits for the notification, and returns the extension that caused it. + // TODO(lazyboy): Return scoped_refptr<const Extension> from all of these + // methods for consistency. const Extension* WaitForExtensionWillBeInstalled(); const Extension* WaitForExtensionInstalled(); - const Extension* WaitForExtensionUninstalled(); + scoped_refptr<const Extension> WaitForExtensionUninstalled(); const Extension* WaitForExtensionLoaded(); const Extension* WaitForExtensionReady(); - const Extension* WaitForExtensionUnloaded(); + scoped_refptr<const Extension> WaitForExtensionUnloaded(); private: class Waiter; @@ -66,7 +68,7 @@ class TestExtensionRegistryObserver : public ExtensionRegistryObserver { std::unique_ptr<Waiter> unloaded_waiter_; ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; std::string extension_id_; diff --git a/chromium/extensions/browser/test_extensions_browser_client.cc b/chromium/extensions/browser/test_extensions_browser_client.cc index 8e5048ce79b..b51e4c6710b 100644 --- a/chromium/extensions/browser/test_extensions_browser_client.cc +++ b/chromium/extensions/browser/test_extensions_browser_client.cc @@ -226,7 +226,8 @@ TestExtensionsBrowserClient::GetComponentExtensionResourceManager() { void TestExtensionsBrowserClient::BroadcastEventToRenderers( events::HistogramValue histogram_value, const std::string& event_name, - std::unique_ptr<base::ListValue> args) {} + std::unique_ptr<base::ListValue> args, + bool dispatch_to_off_the_record_profiles) {} ExtensionCache* TestExtensionsBrowserClient::GetExtensionCache() { return extension_cache_.get(); diff --git a/chromium/extensions/browser/test_extensions_browser_client.h b/chromium/extensions/browser/test_extensions_browser_client.h index 6ae3ab8ae08..859ce90624a 100644 --- a/chromium/extensions/browser/test_extensions_browser_client.h +++ b/chromium/extensions/browser/test_extensions_browser_client.h @@ -128,7 +128,8 @@ class TestExtensionsBrowserClient : public ExtensionsBrowserClient { void BroadcastEventToRenderers( events::HistogramValue histogram_value, const std::string& event_name, - std::unique_ptr<base::ListValue> args) override; + std::unique_ptr<base::ListValue> args, + bool dispatch_to_off_the_record_profiles) override; ExtensionCache* GetExtensionCache() override; bool IsBackgroundUpdateAllowed() override; bool IsMinBrowserVersionSupported(const std::string& min_version) override; diff --git a/chromium/extensions/browser/uninstall_ping_sender.cc b/chromium/extensions/browser/uninstall_ping_sender.cc index 6b224dd76b2..865c01cd1d6 100644 --- a/chromium/extensions/browser/uninstall_ping_sender.cc +++ b/chromium/extensions/browser/uninstall_ping_sender.cc @@ -5,14 +5,13 @@ #include "extensions/browser/uninstall_ping_sender.h" #include "base/version.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/updater/update_service.h" namespace extensions { UninstallPingSender::UninstallPingSender(ExtensionRegistry* registry, const Filter& filter) - : filter_(filter), observer_(this) { + : filter_(filter) { observer_.Add(registry); } diff --git a/chromium/extensions/browser/uninstall_ping_sender.h b/chromium/extensions/browser/uninstall_ping_sender.h index a349d5c0e8c..6a02028156c 100644 --- a/chromium/extensions/browser/uninstall_ping_sender.h +++ b/chromium/extensions/browser/uninstall_ping_sender.h @@ -8,6 +8,7 @@ #include "base/callback.h" #include "base/macros.h" #include "base/scoped_observer.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" namespace content { @@ -37,12 +38,12 @@ class UninstallPingSender : public ExtensionRegistryObserver { const Extension* extension, UninstallReason reason) override; + private: // Callback for determining whether to send uninstall pings. Filter filter_; - ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> observer_; + ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> observer_{this}; - private: DISALLOW_COPY_AND_ASSIGN(UninstallPingSender); }; diff --git a/chromium/extensions/browser/updater/extension_downloader.cc b/chromium/extensions/browser/updater/extension_downloader.cc index 79fe4b38d2d..4fe20bda00d 100644 --- a/chromium/extensions/browser/updater/extension_downloader.cc +++ b/chromium/extensions/browser/updater/extension_downloader.cc @@ -119,8 +119,8 @@ ExtensionDownloaderTestDelegate* g_test_delegate = nullptr; bool ShouldRetryRequest(const network::SimpleURLLoader* loader) { DCHECK(loader); - // Since HTTP errors are now presented as ERR_FAILED by default, this will - // let both network and HTTP errors through. + // Since HTTP errors are now presented as ERR_HTTP_RESPONSE_CODE_FAILURE + // by default, this will let both network and HTTP errors through. if (loader->NetError() == net::OK) return false; @@ -572,9 +572,8 @@ void ExtensionDownloader::CreateManifestLoader() { })"); auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = active_request->full_url(), - resource_request->load_flags = net::LOAD_DO_NOT_SEND_COOKIES | - net::LOAD_DO_NOT_SAVE_COOKIES | - net::LOAD_DISABLE_CACHE; + resource_request->load_flags = net::LOAD_DISABLE_CACHE; + resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; // Send traffic-management headers to the webstore. // https://bugs.chromium.org/p/chromium/issues/detail?id=647516 @@ -955,7 +954,7 @@ void ExtensionDownloader::NotifyDelegateDownloadFinished( const std::set<int>& request_ids = fetch_data->request_ids; const crx_file::VerifierFormat required_format = extension_urls::IsWebstoreUpdateUrl(fetch_data->url) - ? GetWebstoreVerifierFormat() + ? GetWebstoreVerifierFormat(false) : crx_format_requirement_; delegate_->OnExtensionDownloadFinished( CRXFileInfo(id, crx_path, package_hash, required_format), @@ -988,10 +987,11 @@ void ExtensionDownloader::CreateExtensionLoader() { int load_flags = net::LOAD_DISABLE_CACHE; bool is_secure = fetch->url.SchemeIsCryptographic(); + extension_loader_resource_request_->load_flags = load_flags; if (fetch->credentials != ExtensionFetch::CREDENTIALS_COOKIES || !is_secure) { - load_flags |= net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES; + extension_loader_resource_request_->credentials_mode = + network::mojom::CredentialsMode::kOmit; } - extension_loader_resource_request_->load_flags = load_flags; if (fetch->credentials == ExtensionFetch::CREDENTIALS_OAUTH2_TOKEN && is_secure) { diff --git a/chromium/extensions/browser/updater/extension_downloader_unittest.cc b/chromium/extensions/browser/updater/extension_downloader_unittest.cc index 32dcbc14d45..ef1dfe5f900 100644 --- a/chromium/extensions/browser/updater/extension_downloader_unittest.cc +++ b/chromium/extensions/browser/updater/extension_downloader_unittest.cc @@ -5,7 +5,7 @@ #include "extensions/browser/updater/extension_downloader.h" #include "base/sequenced_task_runner.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/extensions_test.h" #include "extensions/browser/updater/extension_downloader_test_helper.h" diff --git a/chromium/extensions/browser/updater/extension_installer.cc b/chromium/extensions/browser/updater/extension_installer.cc index ea5d3d7700f..902c29191e3 100644 --- a/chromium/extensions/browser/updater/extension_installer.cc +++ b/chromium/extensions/browser/updater/extension_installer.cc @@ -42,8 +42,8 @@ void ExtensionInstaller::OnUpdateError(int error) { void ExtensionInstaller::Install(const base::FilePath& unpack_path, const std::string& public_key, UpdateClientCallback update_client_callback) { - auto ui_thread = base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}); + auto ui_thread = + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}); DCHECK(ui_thread); DCHECK(!extension_installer_callback_.is_null()); if (base::PathExists(unpack_path)) { diff --git a/chromium/extensions/browser/updater/safe_manifest_parser_unittest.cc b/chromium/extensions/browser/updater/safe_manifest_parser_unittest.cc index fc25304cb49..05a80ca2378 100644 --- a/chromium/extensions/browser/updater/safe_manifest_parser_unittest.cc +++ b/chromium/extensions/browser/updater/safe_manifest_parser_unittest.cc @@ -6,7 +6,7 @@ #include "base/bind.h" #include "base/run_loop.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/updater/safe_manifest_parser.h" #include "services/data_decoder/public/cpp/test_data_decoder_service.h" #include "testing/gtest/include/gtest/gtest.h" @@ -43,7 +43,7 @@ class ExtensionUpdateManifestTest : public testing::Test { std::move(quit_loop).Run(); } - content::TestBrowserThreadBundle browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<UpdateManifestResults> results_; base::Optional<std::string> error_; data_decoder::TestDataDecoderService test_data_decoder_service_; diff --git a/chromium/extensions/browser/updater/update_data_provider.cc b/chromium/extensions/browser/updater/update_data_provider.cc index f653bd5c783..4a5a84cefa8 100644 --- a/chromium/extensions/browser/updater/update_data_provider.cc +++ b/chromium/extensions/browser/updater/update_data_provider.cc @@ -105,10 +105,8 @@ UpdateDataProvider::GetData(bool install_immediately, crx_component->allows_background_download = false; crx_component->requires_network_encryption = true; crx_component->crx_format_requirement = - extension->from_webstore() - ? GetWebstoreVerifierFormat() - : GetPolicyVerifierFormat( - extension_prefs->InsecureExtensionUpdatesEnabled()); + extension->from_webstore() ? GetWebstoreVerifierFormat(false) + : GetPolicyVerifierFormat(); crx_component->installer = base::MakeRefCounted<ExtensionInstaller>( id, extension->path(), install_immediately, base::BindOnce(&UpdateDataProvider::RunInstallCallback, this)); @@ -143,14 +141,15 @@ void UpdateDataProvider::RunInstallCallback( << public_key; if (!browser_context_) { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), unpacked_dir, true)); return; } - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask( FROM_HERE, base::BindOnce(InstallUpdateCallback, browser_context_, extension_id, diff --git a/chromium/extensions/browser/updater/update_service_unittest.cc b/chromium/extensions/browser/updater/update_service_unittest.cc index 63958a8d634..6fd7b4aa344 100644 --- a/chromium/extensions/browser/updater/update_service_unittest.cc +++ b/chromium/extensions/browser/updater/update_service_unittest.cc @@ -21,7 +21,7 @@ #include "components/update_client/crx_update_item.h" #include "components/update_client/update_client.h" #include "content/public/browser/notification_service.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_test.h" diff --git a/chromium/extensions/browser/url_loader_factory_manager.cc b/chromium/extensions/browser/url_loader_factory_manager.cc index e56a734beda..fabb40eb708 100644 --- a/chromium/extensions/browser/url_loader_factory_manager.cc +++ b/chromium/extensions/browser/url_loader_factory_manager.cc @@ -59,7 +59,6 @@ enum class FactoryUser { // Migration plan for extension developers is described at // https://chromium.org/Home/chromium-security/extension-content-script-fetches const char* kHardcodedPartOfCorbAllowlist[] = { - "0149C10F1124F1ED6ACAD85C45E87A76A9DDC667", "039F93DD1DF836F1D4E2084C1BEFDB46A854A9D1", "03E5D80A49C309F7B55ED6BD2B0EDEB38021ED4E", "072D729E856B1F2C9894AEEC3A5DF65E519D6BEE", @@ -87,7 +86,6 @@ const char* kHardcodedPartOfCorbAllowlist[] = { "28A9EDFD65BC27B5048E516AA7165339F5ACBB30", "2A661509BCE9F8384B00CFC96807597D71DFE94C", "2AA94E2D3F4DA33F0D3BCF5DD48F69B8BDB26F52", - "2C116B242B7425D359E188AB053B3F88DB78F78D", "2E2D8A405430172AB15ADCC09740F3EEE990D605", "30E95BD31B11118CE488EB4FC5FF7135E0C59425", "31E6100DC7B4EAB4ABF6CA2A4E191D3945D3C731", @@ -136,7 +134,6 @@ const char* kHardcodedPartOfCorbAllowlist[] = { "68F43E671577CF03AE901A5780DC07879331A3A9", "6A113D4E2F96997D9BA4B391B90ED51058B37EFF", "6AE81EF3B13B15080A2DDB23A205A24C65CCC10B", - "6BA5F75FFF75B69507BC4B09B7094926EF93DBD2", "6D3A671DABC1F87910A1AA67EE85C02095D35624", "6E49449D56D031B87835CC767734AF5A064E1A13", "6FD56FE5B3831B17ED5301EE2EF949CEE5BFA871", @@ -170,11 +167,9 @@ const char* kHardcodedPartOfCorbAllowlist[] = { "93934B0B87347437699EB62A8921F59F40C36D7A", "93BBF911E8871F6FCC8170448FD2DF5B9EF233E5", "95E78675D2DB61DC688586CD7A24202A260907A4", - "965A185A30475F208A7365E134F48C64CF08C997", "973E35633030AD27DABEC99609424A61386C7309", "9784343657207FE88A629E8EAA7A4A19C7C8CBE0", "97E04C5632954E778306CAC40B3F95C470B463B6", - "98EF7B1601119AEE1FCC28EE5CE247DED5676539", "999BD8D1929F9ABB817E9368480D93BAB2A0983D", "99E06C364BBB2D1F82A9D20BC1645BF21E478259", "9C6A186F8D3C5FD0CC8DCF49682FA726BD8A7705", @@ -187,7 +182,6 @@ const char* kHardcodedPartOfCorbAllowlist[] = { "A733063124AC9E1E6E1E331FFBAAE32D81AC2581", "A8FB3967ADE404B77AC3FB5815A399C0660C3C63", "A9A4B26C2387BA2A5861C790B0FF39F230427AC8", - "A9F78610B717B3992F92F490E82FC63FFF46C5FA", "AA3DE48E23B2465B21F5D33E993FD959F611DD10", "ADD14F4517B9A87D4E841369417E5BDB5FDFF263", "AE063CF9FF5D718AD6F1CF242FABAC39B57ADEBA", @@ -206,7 +200,6 @@ const char* kHardcodedPartOfCorbAllowlist[] = { "CC32A0FD1D88B403308EACBE4DE3CA5AC54B93EB", "CD8AF9C47DDE6327F8D9A3EFA81F34C6B6C26EBB", "CF40F6289951CBFA3B83B792EFA774E2EA06E4C0", - "D0537B1BADCE856227CE76E31B3772F6B68F653C", "D347F78F32567E90BC32D9C16B085254EA269590", "D572BE31227F6D0BE95B9430BE2D5F21D7D9CF9A", "D7C3879A8898618E3A23B0E6BFB6A38D01606246", @@ -226,7 +219,6 @@ const char* kHardcodedPartOfCorbAllowlist[] = { "EC4A841BD03C8E5202043165188A9E060BF703A3", "EE4BE5F23D2E59E4713958465941EFB4A18166B7", "EE711E704D4A365C4644EE4637076C81DF454EA6", - "EF97543DC0DE66EF00D804A55DCF73E0BACB8773", "F1ACA279F460440E47078D91FE372212DD9B8709", "F273C23C616F5C56E8EDBAE24B21F5D408936A0D", "F566B33D62CE21415AF5B3F3FD8762B7454B8874", @@ -234,7 +226,6 @@ const char* kHardcodedPartOfCorbAllowlist[] = { "F608282162AD48CE45D5BC2F6F467B56E88EBFA4", "F73F9EF0207603992CA3C00A7A0CB223D5571B3F", "F9287A33E15038F2591F23E6E9C486717C7202DD", - "FCB9E071ACBA414EDA9AD90973B55062AE665827", "FCC2DC6574A3CA28ED77195926C67F612292C5C3", "FEE3DC8C722657A4A5B0F72CA48CF950DC956148", "FF0DA4BD87A88469B10709B99E79D4B0E11C0CA6", @@ -257,43 +248,20 @@ std::vector<std::string> CreateExtensionAllowlist() { return allowlist; } - // Make sure kHardcodedPartOfAllowlist will fit, but also leave some room - // for field trial params. - allowlist.reserve(base::size(kHardcodedPartOfCorbAllowlist) + 10); - // Append extensions from the hardcoded allowlist. + allowlist.reserve(base::size(kHardcodedPartOfCorbAllowlist)); for (const char* hash : kHardcodedPartOfCorbAllowlist) { DCHECK(IsValidHashedExtensionId(hash)); // It also validates the length. allowlist.push_back(std::string(hash, kHashedExtensionIdLength)); } - // Append extensions from the field trial param. - std::string field_trial_arg = base::GetFieldTrialParamValueByFeature( - extensions_features::kBypassCorbOnlyForExtensionsAllowlist, - extensions_features::kBypassCorbAllowlistParamName); - field_trial_arg = base::ToUpperASCII(field_trial_arg); - std::vector<std::string> field_trial_allowlist = base::SplitString( - field_trial_arg, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - base::EraseIf(field_trial_allowlist, [](const std::string& hash) { - // Filter out invalid data from |field_trial_allowlist|. - if (IsValidHashedExtensionId(hash)) - return false; // Don't remove. - - LOG(ERROR) << "Invalid extension hash: " << hash; - return true; // Remove. - }); - std::move(field_trial_allowlist.begin(), field_trial_allowlist.end(), - std::back_inserter(allowlist)); - return allowlist; } // Returns a set of HashedExtensionId of extensions that depend on relaxed CORB // behavior in their content scripts. -const base::flat_set<std::string>& GetExtensionsAllowlist() { - DCHECK(base::FeatureList::IsEnabled( - extensions_features::kBypassCorbOnlyForExtensionsAllowlist)); - static const base::NoDestructor<base::flat_set<std::string>> s_allowlist([] { +base::flat_set<std::string>& GetExtensionsAllowlist() { + static base::NoDestructor<base::flat_set<std::string>> s_allowlist([] { base::flat_set<std::string> result(CreateExtensionAllowlist()); result.shrink_to_fit(); return result; @@ -310,10 +278,6 @@ bool DoContentScriptsDependOnRelaxedCorb(const Extension& extension) { // Content scripts in the current version of extensions might depend on // relaxed CORB. if (extension.manifest_version() <= 2) { - if (!base::FeatureList::IsEnabled( - extensions_features::kBypassCorbOnlyForExtensionsAllowlist)) - return true; - const std::string& hash = extension.hashed_id().value(); DCHECK(IsValidHashedExtensionId(hash)); return base::Contains(GetExtensionsAllowlist(), hash); @@ -346,7 +310,8 @@ bool IsSpecialURLLoaderFactoryRequired(const Extension& extension, network::mojom::URLLoaderFactoryPtrInfo CreateURLLoaderFactory( content::RenderProcessHost* process, network::mojom::NetworkContext* network_context, - network::mojom::TrustedURLLoaderHeaderClientPtrInfo* header_client, + mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* + header_client, const Extension& extension) { // Compute relaxed CORB config to be used by |extension|. network::mojom::URLLoaderFactoryParamsPtr params = @@ -551,7 +516,8 @@ void URLLoaderFactoryManager::WillExecuteCode(content::RenderFrameHost* frame, network::mojom::URLLoaderFactoryPtrInfo URLLoaderFactoryManager::CreateFactory( content::RenderProcessHost* process, network::mojom::NetworkContext* network_context, - network::mojom::TrustedURLLoaderHeaderClientPtrInfo* header_client, + mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* + header_client, const url::Origin& initiator_origin) { content::BrowserContext* browser_context = process->GetBrowserContext(); const ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context); @@ -592,4 +558,16 @@ network::mojom::URLLoaderFactoryPtrInfo URLLoaderFactoryManager::CreateFactory( *extension); } +// static +void URLLoaderFactoryManager::AddExtensionToAllowlistForTesting( + const Extension& extension) { + GetExtensionsAllowlist().insert(extension.hashed_id().value()); +} + +// static +void URLLoaderFactoryManager::RemoveExtensionFromAllowlistForTesting( + const Extension& extension) { + GetExtensionsAllowlist().erase(extension.hashed_id().value()); +} + } // namespace extensions diff --git a/chromium/extensions/browser/url_loader_factory_manager.h b/chromium/extensions/browser/url_loader_factory_manager.h index b687582472f..3810ff7136f 100644 --- a/chromium/extensions/browser/url_loader_factory_manager.h +++ b/chromium/extensions/browser/url_loader_factory_manager.h @@ -65,9 +65,14 @@ class URLLoaderFactoryManager { static network::mojom::URLLoaderFactoryPtrInfo CreateFactory( content::RenderProcessHost* process, network::mojom::NetworkContext* network_context, - network::mojom::TrustedURLLoaderHeaderClientPtrInfo* header_client, + mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* + header_client, const url::Origin& initiator_origin); + static void AddExtensionToAllowlistForTesting(const Extension& extension); + static void RemoveExtensionFromAllowlistForTesting( + const Extension& extension); + private: // If |extension|'s manifest declares that it may inject JavaScript content // script into the |navigating_frame| / |navigation_target|, then diff --git a/chromium/extensions/browser/url_request_util.cc b/chromium/extensions/browser/url_request_util.cc index 566e708e44c..168a2f7f0aa 100644 --- a/chromium/extensions/browser/url_request_util.cc +++ b/chromium/extensions/browser/url_request_util.cc @@ -6,7 +6,6 @@ #include <string> -#include "content/public/browser/resource_request_info.h" #include "extensions/browser/extension_navigation_ui_data.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h" diff --git a/chromium/extensions/browser/value_store/lazy_leveldb.cc b/chromium/extensions/browser/value_store/lazy_leveldb.cc index 84538604ee7..dfa5daa83ce 100644 --- a/chromium/extensions/browser/value_store/lazy_leveldb.cc +++ b/chromium/extensions/browser/value_store/lazy_leveldb.cc @@ -85,7 +85,7 @@ LazyLevelDb::LazyLevelDb(const std::string& uma_client_name, LazyLevelDb::~LazyLevelDb() = default; ValueStore::Status LazyLevelDb::Read(const std::string& key, - std::unique_ptr<base::Value>* value) { + base::Optional<base::Value>* value) { DCHECK(value); std::string value_as_json; @@ -100,13 +100,13 @@ ValueStore::Status LazyLevelDb::Read(const std::string& key, if (!s.ok()) return ToValueStoreError(s); - std::unique_ptr<base::Value> val = - base::JSONReader().ReadToValueDeprecated(value_as_json); - if (!val) + base::Optional<base::Value> read_value = + base::JSONReader().ReadToValue(value_as_json); + if (!read_value) { return ValueStore::Status(ValueStore::CORRUPTION, FixCorruption(&key), kInvalidJson); - - *value = std::move(val); + } + *value = std::move(read_value); return ValueStore::Status(); } diff --git a/chromium/extensions/browser/value_store/lazy_leveldb.h b/chromium/extensions/browser/value_store/lazy_leveldb.h index c0098ae3488..2810bd1edbd 100644 --- a/chromium/extensions/browser/value_store/lazy_leveldb.h +++ b/chromium/extensions/browser/value_store/lazy_leveldb.h @@ -11,6 +11,8 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "base/metrics/histogram_base.h" +#include "base/optional.h" +#include "base/values.h" #include "extensions/browser/value_store/value_store.h" #include "third_party/leveldatabase/env_chromium.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" @@ -55,7 +57,7 @@ class LazyLevelDb { // be returned and value will be unchanged. Caller must ensure the database is // open before calling this method. ValueStore::Status Read(const std::string& key, - std::unique_ptr<base::Value>* value); + base::Optional<base::Value>* value); // Opens the underlying database if not yet open. If the open fails due to // corruption will attempt to repair the database. Failing that, will attempt diff --git a/chromium/extensions/browser/value_store/leveldb_scoped_database.cc b/chromium/extensions/browser/value_store/leveldb_scoped_database.cc index 4dcf307b95c..a87cec1f17f 100644 --- a/chromium/extensions/browser/value_store/leveldb_scoped_database.cc +++ b/chromium/extensions/browser/value_store/leveldb_scoped_database.cc @@ -49,7 +49,7 @@ LeveldbScopedDatabase::~LeveldbScopedDatabase() {} ValueStore::Status LeveldbScopedDatabase::Read( const std::string& scope, const std::string& key, - std::unique_ptr<base::Value>* value) { + base::Optional<base::Value>* value) { ValueStore::Status status = EnsureDbIsOpen(); if (!status.ok()) return status; diff --git a/chromium/extensions/browser/value_store/leveldb_scoped_database.h b/chromium/extensions/browser/value_store/leveldb_scoped_database.h index 46f59943ff4..e2b8b099c8c 100644 --- a/chromium/extensions/browser/value_store/leveldb_scoped_database.h +++ b/chromium/extensions/browser/value_store/leveldb_scoped_database.h @@ -46,7 +46,7 @@ class LeveldbScopedDatabase // Reads a single |value| from the database for the specified |key|. ValueStore::Status Read(const std::string& scope, const std::string& key, - std::unique_ptr<base::Value>* value); + base::Optional<base::Value>* value); // Reads all |values| from the database stored within the specified |scope|. ValueStore::Status Read(const std::string& scope, diff --git a/chromium/extensions/browser/value_store/leveldb_scoped_database_unittest.cc b/chromium/extensions/browser/value_store/leveldb_scoped_database_unittest.cc index c7b27ec7251..7ced8f16f1e 100644 --- a/chromium/extensions/browser/value_store/leveldb_scoped_database_unittest.cc +++ b/chromium/extensions/browser/value_store/leveldb_scoped_database_unittest.cc @@ -13,7 +13,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/memory/ref_counted.h" #include "base/values.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace { @@ -56,7 +56,7 @@ class LeveldbScopedDatabaseUnitTest : public testing::Test { return db_->ToValueStoreError(iterator->status()); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; base::ScopedTempDir database_dir_; scoped_refptr<LeveldbScopedDatabase> db_; }; @@ -160,11 +160,11 @@ TEST_F(LeveldbScopedDatabaseUnitTest, TestEmptyValue) { values.SetString("s1_key1", ""); EXPECT_TRUE(db_->Write("scope1", values).ok()); - std::unique_ptr<base::Value> value; + base::Optional<base::Value> value; ASSERT_TRUE(db_->Read("scope1", "s1_key1", &value).ok()); - std::string str; - EXPECT_TRUE(value->GetAsString(&str)); - EXPECT_EQ(str, ""); + ASSERT_TRUE(value.has_value()); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(value->GetString(), ""); } TEST_F(LeveldbScopedDatabaseUnitTest, TestValueContainingDelimiter) { @@ -172,11 +172,11 @@ TEST_F(LeveldbScopedDatabaseUnitTest, TestValueContainingDelimiter) { values.SetString("s1_key1", "with:delimiter"); EXPECT_TRUE(db_->Write("scope1", values).ok()); - std::unique_ptr<base::Value> value; + base::Optional<base::Value> value; ASSERT_TRUE(db_->Read("scope1", "s1_key1", &value).ok()); - std::string str; - EXPECT_TRUE(value->GetAsString(&str)); - EXPECT_EQ(str, "with:delimiter"); + ASSERT_TRUE(value.has_value()); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(value->GetString(), "with:delimiter"); } TEST_F(LeveldbScopedDatabaseUnitTest, TestDeleteValues) { diff --git a/chromium/extensions/browser/value_store/leveldb_value_store.cc b/chromium/extensions/browser/value_store/leveldb_value_store.cc index 5f46c960427..97a1933b5fa 100644 --- a/chromium/extensions/browser/value_store/leveldb_value_store.cc +++ b/chromium/extensions/browser/value_store/leveldb_value_store.cc @@ -83,12 +83,12 @@ ValueStore::ReadResult LeveldbValueStore::Get( std::unique_ptr<base::DictionaryValue> settings(new base::DictionaryValue()); for (const std::string& key : keys) { - std::unique_ptr<base::Value> setting; + base::Optional<base::Value> setting; status.Merge(Read(key, &setting)); if (!status.ok()) return ReadResult(std::move(status)); if (setting) - settings->SetWithoutPathExpansion(key, std::move(setting)); + settings->SetKey(key, std::move(*setting)); } return ReadResult(std::move(settings), std::move(status)); @@ -178,13 +178,14 @@ ValueStore::WriteResult LeveldbValueStore::Remove( std::unique_ptr<ValueStoreChangeList> changes(new ValueStoreChangeList()); for (const std::string& key : keys) { - std::unique_ptr<base::Value> old_value; + base::Optional<base::Value> old_value; status.Merge(Read(key, &old_value)); if (!status.ok()) return WriteResult(std::move(status)); if (old_value) { - changes->push_back(ValueStoreChange(key, std::move(old_value), nullptr)); + changes->push_back( + ValueStoreChange(key, std::move(old_value), base::nullopt)); batch.Delete(key); } } @@ -210,7 +211,7 @@ ValueStore::WriteResult LeveldbValueStore::Clear() { std::unique_ptr<base::Value> next_value; whole_db.RemoveWithoutPathExpansion(next_key, &next_value); changes->push_back( - ValueStoreChange(next_key, std::move(next_value), nullptr)); + ValueStoreChange(next_key, std::move(*next_value), base::nullopt)); } DeleteDbFile(); @@ -258,13 +259,13 @@ ValueStore::Status LeveldbValueStore::AddToBatch( bool write_new_value = true; if (!(options & NO_GENERATE_CHANGES)) { - std::unique_ptr<base::Value> old_value; + base::Optional<base::Value> old_value; Status status = Read(key, &old_value); if (!status.ok()) return status; - if (!old_value || !old_value->Equals(&value)) { + if (!old_value || *old_value != value) { changes->push_back( - ValueStoreChange(key, std::move(old_value), value.CreateDeepCopy())); + ValueStoreChange(key, std::move(old_value), value.Clone())); } else { write_new_value = false; } diff --git a/chromium/extensions/browser/value_store/leveldb_value_store_unittest.cc b/chromium/extensions/browser/value_store/leveldb_value_store_unittest.cc index c8cd2fcff9e..6acd6bfd590 100644 --- a/chromium/extensions/browser/value_store/leveldb_value_store_unittest.cc +++ b/chromium/extensions/browser/value_store/leveldb_value_store_unittest.cc @@ -11,7 +11,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/memory/ref_counted.h" #include "base/values.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/value_store/leveldb_value_store.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" @@ -64,7 +64,7 @@ class LeveldbValueStoreUnitTest : public testing::Test { std::unique_ptr<LeveldbValueStore> store_; base::ScopedTempDir database_dir_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; // Check that we can restore a single corrupted key in the LeveldbValueStore. diff --git a/chromium/extensions/browser/value_store/testing_value_store.cc b/chromium/extensions/browser/value_store/testing_value_store.cc index 72a292c8ce5..052293a988d 100644 --- a/chromium/extensions/browser/value_store/testing_value_store.cc +++ b/chromium/extensions/browser/value_store/testing_value_store.cc @@ -95,8 +95,10 @@ ValueStore::WriteResult TestingValueStore::Set( if (!storage_.GetWithoutPathExpansion(it.key(), &old_value) || !old_value->Equals(&it.value())) { changes->push_back(ValueStoreChange( - it.key(), old_value ? old_value->CreateDeepCopy() : nullptr, - it.value().CreateDeepCopy())); + it.key(), + old_value ? base::Optional<base::Value>(old_value->Clone()) + : base::nullopt, + it.value().Clone())); storage_.SetWithoutPathExpansion(it.key(), it.value().CreateDeepCopy()); } } @@ -117,7 +119,8 @@ ValueStore::WriteResult TestingValueStore::Remove( for (auto it = keys.cbegin(); it != keys.cend(); ++it) { std::unique_ptr<base::Value> old_value; if (storage_.RemoveWithoutPathExpansion(*it, &old_value)) { - changes->push_back(ValueStoreChange(*it, std::move(old_value), nullptr)); + changes->push_back( + ValueStoreChange(*it, std::move(*old_value), base::nullopt)); } } return WriteResult(std::move(changes), CreateStatusCopy(status_)); diff --git a/chromium/extensions/browser/value_store/value_store_change.cc b/chromium/extensions/browser/value_store/value_store_change.cc index dc5abce5fcf..ea6acdd94f5 100644 --- a/chromium/extensions/browser/value_store/value_store_change.cc +++ b/chromium/extensions/browser/value_store/value_store_change.cc @@ -12,17 +12,16 @@ // static std::string ValueStoreChange::ToJson( const ValueStoreChangeList& changes) { - base::DictionaryValue changes_value; - for (auto it = changes.cbegin(); it != changes.cend(); ++it) { - std::unique_ptr<base::DictionaryValue> change_value = - std::make_unique<base::DictionaryValue>(); - if (it->old_value()) { - change_value->SetKey("oldValue", it->old_value()->Clone()); + base::Value changes_value(base::Value::Type::DICTIONARY); + for (const auto& change : changes) { + base::Value change_value(base::Value::Type::DICTIONARY); + if (change.old_value()) { + change_value.SetKey("oldValue", change.old_value()->Clone()); } - if (it->new_value()) { - change_value->SetKey("newValue", it->new_value()->Clone()); + if (change.new_value()) { + change_value.SetKey("newValue", change.new_value()->Clone()); } - changes_value.SetWithoutPathExpansion(it->key(), std::move(change_value)); + changes_value.SetKey(change.key(), std::move(change_value)); } std::string json; bool success = base::JSONWriter::Write(changes_value, &json); @@ -31,8 +30,8 @@ std::string ValueStoreChange::ToJson( } ValueStoreChange::ValueStoreChange(const std::string& key, - std::unique_ptr<base::Value> old_value, - std::unique_ptr<base::Value> new_value) + base::Optional<base::Value> old_value, + base::Optional<base::Value> new_value) : inner_(new Inner(key, std::move(old_value), std::move(new_value))) {} ValueStoreChange::ValueStoreChange(const ValueStoreChange& other) = default; @@ -46,17 +45,17 @@ const std::string& ValueStoreChange::key() const { const base::Value* ValueStoreChange::old_value() const { DCHECK(inner_.get()); - return inner_->old_value_.get(); + return inner_->old_value_ ? &*inner_->old_value_ : nullptr; } const base::Value* ValueStoreChange::new_value() const { DCHECK(inner_.get()); - return inner_->new_value_.get(); + return inner_->new_value_ ? &*inner_->new_value_ : nullptr; } ValueStoreChange::Inner::Inner(const std::string& key, - std::unique_ptr<base::Value> old_value, - std::unique_ptr<base::Value> new_value) + base::Optional<base::Value> old_value, + base::Optional<base::Value> new_value) : key_(key), old_value_(std::move(old_value)), new_value_(std::move(new_value)) {} diff --git a/chromium/extensions/browser/value_store/value_store_change.h b/chromium/extensions/browser/value_store/value_store_change.h index 8645b574566..0719b38874d 100644 --- a/chromium/extensions/browser/value_store/value_store_change.h +++ b/chromium/extensions/browser/value_store/value_store_change.h @@ -5,11 +5,11 @@ #ifndef EXTENSIONS_BROWSER_VALUE_STORE_VALUE_STORE_CHANGE_H_ #define EXTENSIONS_BROWSER_VALUE_STORE_VALUE_STORE_CHANGE_H_ -#include <memory> #include <string> #include <vector> #include "base/memory/ref_counted.h" +#include "base/optional.h" #include "base/values.h" class ValueStoreChange; @@ -23,8 +23,8 @@ class ValueStoreChange { static std::string ToJson(const ValueStoreChangeList& changes); ValueStoreChange(const std::string& key, - std::unique_ptr<base::Value> old_value, - std::unique_ptr<base::Value> new_value); + base::Optional<base::Value> old_value, + base::Optional<base::Value> new_value); ValueStoreChange(const ValueStoreChange& other); @@ -45,12 +45,12 @@ class ValueStoreChange { class Inner : public base::RefCountedThreadSafe<Inner> { public: Inner(const std::string& key, - std::unique_ptr<base::Value> old_value, - std::unique_ptr<base::Value> new_value); + base::Optional<base::Value> old_value, + base::Optional<base::Value> new_value); const std::string key_; - const std::unique_ptr<base::Value> old_value_; - const std::unique_ptr<base::Value> new_value_; + const base::Optional<base::Value> old_value_; + const base::Optional<base::Value> new_value_; private: friend class base::RefCountedThreadSafe<Inner>; diff --git a/chromium/extensions/browser/value_store/value_store_change_unittest.cc b/chromium/extensions/browser/value_store/value_store_change_unittest.cc index 8b479e26602..7c6f82a6622 100644 --- a/chromium/extensions/browser/value_store/value_store_change_unittest.cc +++ b/chromium/extensions/browser/value_store/value_store_change_unittest.cc @@ -18,8 +18,7 @@ using extensions::ListBuilder; namespace { TEST(ValueStoreChangeTest, NullOldValue) { - ValueStoreChange change("key", nullptr, - std::make_unique<base::Value>("value")); + ValueStoreChange change("key", base::nullopt, base::Value("value")); EXPECT_EQ("key", change.key()); EXPECT_EQ(NULL, change.old_value()); @@ -30,8 +29,7 @@ TEST(ValueStoreChangeTest, NullOldValue) { } TEST(ValueStoreChangeTest, NullNewValue) { - ValueStoreChange change("key", std::make_unique<base::Value>("value"), - nullptr); + ValueStoreChange change("key", base::Value("value"), base::nullopt); EXPECT_EQ("key", change.key()); { @@ -42,8 +40,8 @@ TEST(ValueStoreChangeTest, NullNewValue) { } TEST(ValueStoreChangeTest, NonNullValues) { - ValueStoreChange change("key", std::make_unique<base::Value>("old_value"), - std::make_unique<base::Value>("new_value")); + ValueStoreChange change("key", base::Value("old_value"), + base::Value("new_value")); EXPECT_EQ("key", change.key()); { @@ -67,10 +65,10 @@ TEST(ValueStoreChangeTest, ToJson) { .Build(); ValueStoreChangeList change_list; - change_list.push_back(ValueStoreChange("key", value->CreateDeepCopy(), - value->CreateDeepCopy())); - change_list.push_back(ValueStoreChange( - "key.with.dots", value->CreateDeepCopy(), value->CreateDeepCopy())); + change_list.push_back( + ValueStoreChange("key", value->Clone(), value->Clone())); + change_list.push_back( + ValueStoreChange("key.with.dots", value->Clone(), value->Clone())); std::string json = ValueStoreChange::ToJson(change_list); base::Optional<base::Value> from_json = base::JSONReader::Read(json); diff --git a/chromium/extensions/browser/value_store/value_store_factory_impl.cc b/chromium/extensions/browser/value_store/value_store_factory_impl.cc index 3689421bdf9..09f3a948ece 100644 --- a/chromium/extensions/browser/value_store/value_store_factory_impl.cc +++ b/chromium/extensions/browser/value_store/value_store_factory_impl.cc @@ -4,6 +4,7 @@ #include "extensions/browser/value_store/value_store_factory_impl.h" +#include "base/memory/scoped_refptr.h" #include "extensions/browser/value_store/legacy_value_store_factory.h" namespace extensions { @@ -11,7 +12,8 @@ namespace extensions { using SettingsNamespace = settings_namespace::Namespace; ValueStoreFactoryImpl::ValueStoreFactoryImpl(const base::FilePath& profile_path) - : legacy_factory_(new LegacyValueStoreFactory(profile_path)) {} + : legacy_factory_( + base::MakeRefCounted<LegacyValueStoreFactory>(profile_path)) {} ValueStoreFactoryImpl::~ValueStoreFactoryImpl() = default; diff --git a/chromium/extensions/browser/value_store/value_store_frontend.cc b/chromium/extensions/browser/value_store/value_store_frontend.cc index f167cc55ab8..931c1f8861c 100644 --- a/chromium/extensions/browser/value_store/value_store_frontend.cc +++ b/chromium/extensions/browser/value_store/value_store_frontend.cc @@ -10,6 +10,7 @@ #include "base/files/file_path.h" #include "base/logging.h" #include "base/macros.h" +#include "base/memory/scoped_refptr.h" #include "base/task/post_task.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_task_traits.h" @@ -45,10 +46,9 @@ class ValueStoreFrontend::Backend : public base::RefCountedThreadSafe<Backend> { << " failed: " << result.status().message; } - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ValueStoreFrontend::Backend::RunCallback, this, - callback, std::move(value))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ValueStoreFrontend::Backend::RunCallback, + this, callback, std::move(value))); } void Set(const std::string& key, std::unique_ptr<base::Value> value) { @@ -114,7 +114,7 @@ class ValueStoreFrontend::Backend : public base::RefCountedThreadSafe<Backend> { ValueStoreFrontend::ValueStoreFrontend( const scoped_refptr<ValueStoreFactory>& store_factory, BackendType backend_type) - : backend_(new Backend(store_factory, backend_type)) { + : backend_(base::MakeRefCounted<Backend>(store_factory, backend_type)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } diff --git a/chromium/extensions/browser/value_store/value_store_frontend_unittest.cc b/chromium/extensions/browser/value_store/value_store_frontend_unittest.cc index 7813920fe55..32f29a685b0 100644 --- a/chromium/extensions/browser/value_store/value_store_frontend_unittest.cc +++ b/chromium/extensions/browser/value_store/value_store_frontend_unittest.cc @@ -11,7 +11,7 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/path_service.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/value_store/test_value_store_factory.h" #include "extensions/common/extension_paths.h" @@ -64,7 +64,7 @@ class ValueStoreFrontendTest : public testing::Test { std::unique_ptr<ValueStoreFrontend> storage_; base::ScopedTempDir temp_dir_; base::FilePath db_path_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; TEST_F(ValueStoreFrontendTest, GetExistingData) { diff --git a/chromium/extensions/browser/value_store/value_store_unittest.cc b/chromium/extensions/browser/value_store/value_store_unittest.cc index b797e438e55..644392f0fbf 100644 --- a/chromium/extensions/browser/value_store/value_store_unittest.cc +++ b/chromium/extensions/browser/value_store/value_store_unittest.cc @@ -180,8 +180,7 @@ TEST_P(ValueStoreTest, GetWhenEmpty) { TEST_P(ValueStoreTest, GetWithSingleValue) { { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key1_, nullptr, val1_->CreateDeepCopy())); + changes.push_back(ValueStoreChange(key1_, base::nullopt, val1_->Clone())); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Set(DEFAULTS, key1_, *val1_)); } @@ -197,10 +196,8 @@ TEST_P(ValueStoreTest, GetWithSingleValue) { TEST_P(ValueStoreTest, GetWithMultipleValues) { { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key1_, nullptr, val1_->CreateDeepCopy())); - changes.push_back( - ValueStoreChange(key2_, nullptr, val2_->CreateDeepCopy())); + changes.push_back(ValueStoreChange(key1_, base::nullopt, val1_->Clone())); + changes.push_back(ValueStoreChange(key2_, base::nullopt, val2_->Clone())); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Set(DEFAULTS, *dict12_)); } @@ -224,8 +221,7 @@ TEST_P(ValueStoreTest, RemoveWithSingleValue) { storage_->Set(DEFAULTS, *dict1_); { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key1_, val1_->CreateDeepCopy(), nullptr)); + changes.push_back(ValueStoreChange(key1_, val1_->Clone(), base::nullopt)); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Remove(key1_)); } @@ -240,8 +236,7 @@ TEST_P(ValueStoreTest, RemoveWithMultipleValues) { storage_->Set(DEFAULTS, *dict123_); { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key3_, val3_->CreateDeepCopy(), nullptr)); + changes.push_back(ValueStoreChange(key3_, val3_->Clone(), base::nullopt)); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Remove(key3_)); } @@ -256,10 +251,8 @@ TEST_P(ValueStoreTest, RemoveWithMultipleValues) { { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key1_, val1_->CreateDeepCopy(), nullptr)); - changes.push_back( - ValueStoreChange(key2_, val2_->CreateDeepCopy(), nullptr)); + changes.push_back(ValueStoreChange(key1_, val1_->Clone(), base::nullopt)); + changes.push_back(ValueStoreChange(key2_, val2_->Clone(), base::nullopt)); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Remove(list12_)); } @@ -277,10 +270,8 @@ TEST_P(ValueStoreTest, SetWhenOverwriting) { storage_->Set(DEFAULTS, key1_, *val2_); { ValueStoreChangeList changes; - changes.push_back(ValueStoreChange(key1_, val2_->CreateDeepCopy(), - val1_->CreateDeepCopy())); - changes.push_back( - ValueStoreChange(key2_, nullptr, val2_->CreateDeepCopy())); + changes.push_back(ValueStoreChange(key1_, val2_->Clone(), val1_->Clone())); + changes.push_back(ValueStoreChange(key2_, base::nullopt, val2_->Clone())); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Set(DEFAULTS, *dict12_)); } @@ -307,10 +298,8 @@ TEST_P(ValueStoreTest, ClearWhenNotEmpty) { storage_->Set(DEFAULTS, *dict12_); { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key1_, val1_->CreateDeepCopy(), nullptr)); - changes.push_back( - ValueStoreChange(key2_, val2_->CreateDeepCopy(), nullptr)); + changes.push_back(ValueStoreChange(key1_, val1_->Clone(), base::nullopt)); + changes.push_back(ValueStoreChange(key2_, val2_->Clone(), base::nullopt)); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Clear()); } @@ -335,7 +324,7 @@ TEST_P(ValueStoreTest, DotsInKeyNames) { { ValueStoreChangeList changes; changes.push_back( - ValueStoreChange(dot_key, nullptr, dot_value.CreateDeepCopy())); + ValueStoreChange(dot_key, base::nullopt, dot_value.Clone())); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Set(DEFAULTS, dot_key, dot_value)); } @@ -347,7 +336,7 @@ TEST_P(ValueStoreTest, DotsInKeyNames) { { ValueStoreChangeList changes; changes.push_back( - ValueStoreChange(dot_key, dot_value.CreateDeepCopy(), nullptr)); + ValueStoreChange(dot_key, dot_value.Clone(), base::nullopt)); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Remove(dot_key)); } EXPECT_PRED_FORMAT2(ChangesEq, @@ -355,7 +344,7 @@ TEST_P(ValueStoreTest, DotsInKeyNames) { { ValueStoreChangeList changes; changes.push_back( - ValueStoreChange(dot_key, nullptr, dot_value.CreateDeepCopy())); + ValueStoreChange(dot_key, base::nullopt, dot_value.Clone())); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Set(DEFAULTS, dot_dict)); } @@ -365,7 +354,7 @@ TEST_P(ValueStoreTest, DotsInKeyNames) { { ValueStoreChangeList changes; changes.push_back( - ValueStoreChange(dot_key, dot_value.CreateDeepCopy(), nullptr)); + ValueStoreChange(dot_key, dot_value.Clone(), base::nullopt)); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Remove(dot_list)); } @@ -382,7 +371,7 @@ TEST_P(ValueStoreTest, DotsInKeyNamesWithDicts) { { ValueStoreChangeList changes; changes.push_back( - ValueStoreChange("foo", nullptr, inner_dict.CreateDeepCopy())); + ValueStoreChange("foo", base::nullopt, inner_dict.Clone())); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Set(DEFAULTS, outer_dict)); } @@ -404,48 +393,41 @@ TEST_P(ValueStoreTest, ComplexChangedKeysScenarios) { ValueStoreChangeList(), storage_->Set(DEFAULTS, key1_, *val1_)); { ValueStoreChangeList changes; - changes.push_back(ValueStoreChange(key1_, val1_->CreateDeepCopy(), - val2_->CreateDeepCopy())); + changes.push_back(ValueStoreChange(key1_, val1_->Clone(), val2_->Clone())); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Set(DEFAULTS, key1_, *val2_)); } { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key1_, val2_->CreateDeepCopy(), nullptr)); + changes.push_back(ValueStoreChange(key1_, val2_->Clone(), base::nullopt)); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Remove(key1_)); EXPECT_PRED_FORMAT2(ChangesEq, ValueStoreChangeList(), storage_->Remove(key1_)); } { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key1_, nullptr, val1_->CreateDeepCopy())); + changes.push_back(ValueStoreChange(key1_, base::nullopt, val1_->Clone())); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Set(DEFAULTS, key1_, *val1_)); } { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key1_, val1_->CreateDeepCopy(), nullptr)); + changes.push_back(ValueStoreChange(key1_, val1_->Clone(), base::nullopt)); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Clear()); EXPECT_PRED_FORMAT2(ChangesEq, ValueStoreChangeList(), storage_->Clear()); } { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key1_, nullptr, val1_->CreateDeepCopy())); - changes.push_back( - ValueStoreChange(key2_, nullptr, val2_->CreateDeepCopy())); + changes.push_back(ValueStoreChange(key1_, base::nullopt, val1_->Clone())); + changes.push_back(ValueStoreChange(key2_, base::nullopt, val2_->Clone())); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Set(DEFAULTS, *dict12_)); EXPECT_PRED_FORMAT2(ChangesEq, ValueStoreChangeList(), storage_->Set(DEFAULTS, *dict12_)); } { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key3_, nullptr, val3_->CreateDeepCopy())); + changes.push_back(ValueStoreChange(key3_, base::nullopt, val3_->Clone())); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Set(DEFAULTS, *dict123_)); } { @@ -456,20 +438,16 @@ TEST_P(ValueStoreTest, ComplexChangedKeysScenarios) { to_set.Set("qwerty", val3_->CreateDeepCopy()); ValueStoreChangeList changes; - changes.push_back(ValueStoreChange(key1_, val1_->CreateDeepCopy(), - val2_->CreateDeepCopy())); + changes.push_back(ValueStoreChange(key1_, val1_->Clone(), val2_->Clone())); + changes.push_back(ValueStoreChange("asdf", base::nullopt, val1_->Clone())); changes.push_back( - ValueStoreChange("asdf", nullptr, val1_->CreateDeepCopy())); - changes.push_back( - ValueStoreChange("qwerty", nullptr, val3_->CreateDeepCopy())); + ValueStoreChange("qwerty", base::nullopt, val3_->Clone())); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Set(DEFAULTS, to_set)); } { ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange(key1_, val2_->CreateDeepCopy(), nullptr)); - changes.push_back( - ValueStoreChange(key2_, val2_->CreateDeepCopy(), nullptr)); + changes.push_back(ValueStoreChange(key1_, val2_->Clone(), base::nullopt)); + changes.push_back(ValueStoreChange(key2_, val2_->Clone(), base::nullopt)); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Remove(list12_)); } { @@ -478,16 +456,14 @@ TEST_P(ValueStoreTest, ComplexChangedKeysScenarios) { to_remove.push_back("asdf"); ValueStoreChangeList changes; - changes.push_back( - ValueStoreChange("asdf", val1_->CreateDeepCopy(), nullptr)); + changes.push_back(ValueStoreChange("asdf", val1_->Clone(), base::nullopt)); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Remove(to_remove)); } { ValueStoreChangeList changes; + changes.push_back(ValueStoreChange(key3_, val3_->Clone(), base::nullopt)); changes.push_back( - ValueStoreChange(key3_, val3_->CreateDeepCopy(), nullptr)); - changes.push_back( - ValueStoreChange("qwerty", val3_->CreateDeepCopy(), nullptr)); + ValueStoreChange("qwerty", val3_->Clone(), base::nullopt)); EXPECT_PRED_FORMAT2(ChangesEq, changes, storage_->Clear()); EXPECT_PRED_FORMAT2(ChangesEq, ValueStoreChangeList(), storage_->Clear()); } diff --git a/chromium/extensions/browser/value_store/value_store_unittest.h b/chromium/extensions/browser/value_store/value_store_unittest.h index aa579270b36..1f0dbd02e1c 100644 --- a/chromium/extensions/browser/value_store/value_store_unittest.h +++ b/chromium/extensions/browser/value_store/value_store_unittest.h @@ -9,7 +9,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/memory/ref_counted.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/value_store/value_store.h" #include "testing/gtest/include/gtest/gtest.h" @@ -63,7 +63,7 @@ class ValueStoreTest : public testing::TestWithParam<ValueStoreTestParam> { private: base::ScopedTempDir temp_dir_; - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; #endif // EXTENSIONS_BROWSER_VALUE_STORE_VALUE_STORE_UNITTEST_H_ diff --git a/chromium/extensions/browser/verified_contents.cc b/chromium/extensions/browser/verified_contents.cc index 8beeb151be5..942275f3544 100644 --- a/chromium/extensions/browser/verified_contents.cc +++ b/chromium/extensions/browser/verified_contents.cc @@ -11,13 +11,13 @@ #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/memory/ptr_util.h" -#include "base/metrics/histogram_macros.h" #include "base/strings/string_util.h" #include "base/timer/elapsed_timer.h" #include "base/values.h" #include "build/build_config.h" #include "components/crx_file/id_util.h" #include "crypto/signature_verifier.h" +#include "extensions/browser/content_verifier/scoped_uma_recorder.h" #include "extensions/common/extension.h" namespace { @@ -59,40 +59,10 @@ const base::Value* FindDictionaryWithValue(const base::Value& list, return nullptr; } -// Helper to record UMA for results of initializing verified_contents.json file. -// TODO(lazyboy): Merge this with ScopedUMARecorder in computed_hashes.cc. -class ScopedUMARecorder { - public: - ScopedUMARecorder() = default; - - ~ScopedUMARecorder() { - if (recorded_) - return; - RecordImpl(false); - } - - void RecordSuccess() { - recorded_ = true; - RecordImpl(true); - } - - private: - void RecordImpl(bool success) { - if (success) { - UMA_HISTOGRAM_TIMES( - "Extensions.ContentVerification.VerifiedContentsInitTime", - timer_.Elapsed()); - } - UMA_HISTOGRAM_BOOLEAN( - "Extensions.ContentVerification.VerifiedContentsInitResult", success); - } - - private: - base::ElapsedTimer timer_; - bool recorded_ = false; - - DISALLOW_COPY_AND_ASSIGN(ScopedUMARecorder); -}; +const char kUMAVerifiedContentsInitResult[] = + "Extensions.ContentVerification.VerifiedContentsInitResult"; +const char kUMAVerifiedContentsInitTime[] = + "Extensions.ContentVerification.VerifiedContentsInitTime"; #if defined(OS_WIN) // Returns true if |path| ends with (.| )+. @@ -144,7 +114,9 @@ VerifiedContents::~VerifiedContents() { std::unique_ptr<VerifiedContents> VerifiedContents::Create( base::span<const uint8_t> public_key, const base::FilePath& path) { - ScopedUMARecorder uma_recorder; + ScopedUMARecorder<kUMAVerifiedContentsInitTime, + kUMAVerifiedContentsInitResult> + uma_recorder; // Note: VerifiedContents constructor is private. auto verified_contents = base::WrapUnique(new VerifiedContents(public_key)); std::string payload; diff --git a/chromium/extensions/browser/warning_service.cc b/chromium/extensions/browser/warning_service.cc index ea53c8c47c7..45a9699370b 100644 --- a/chromium/extensions/browser/warning_service.cc +++ b/chromium/extensions/browser/warning_service.cc @@ -5,7 +5,6 @@ #include "extensions/browser/warning_service.h" #include "content/public/browser/browser_thread.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/warning_service_factory.h" #include "extensions/common/extension_set.h" @@ -15,7 +14,7 @@ using content::BrowserThread; namespace extensions { WarningService::WarningService(content::BrowserContext* browser_context) - : browser_context_(browser_context), extension_registry_observer_(this) { + : browser_context_(browser_context) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (browser_context_) { extension_registry_observer_.Add(ExtensionRegistry::Get( diff --git a/chromium/extensions/browser/warning_service.h b/chromium/extensions/browser/warning_service.h index 8c2bd948bd5..0e0d02bcdb6 100644 --- a/chromium/extensions/browser/warning_service.h +++ b/chromium/extensions/browser/warning_service.h @@ -9,9 +9,11 @@ #include <string> #include <vector> +#include "base/macros.h" #include "base/observer_list.h" #include "base/scoped_observer.h" #include "components/keyed_service/core/keyed_service.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/browser/warning_set.h" @@ -23,8 +25,6 @@ class BrowserContext; namespace extensions { -class ExtensionRegistry; - // Manages a set of warnings caused by extensions. These warnings (e.g. // conflicting modifications of network requests by extensions, slow extensions, // etc.) trigger a warning badge in the UI and and provide means to resolve @@ -85,9 +85,11 @@ class WarningService : public KeyedService, public ExtensionRegistryObserver { // Listen to extension unloaded notifications. ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> - extension_registry_observer_; + extension_registry_observer_{this}; base::ObserverList<Observer>::Unchecked observer_list_; + + DISALLOW_COPY_AND_ASSIGN(WarningService); }; } // namespace extensions diff --git a/chromium/extensions/browser/web_ui_user_script_loader.cc b/chromium/extensions/browser/web_ui_user_script_loader.cc index 4bd64d9c205..01f1af4efa3 100644 --- a/chromium/extensions/browser/web_ui_user_script_loader.cc +++ b/chromium/extensions/browser/web_ui_user_script_loader.cc @@ -154,9 +154,9 @@ void WebUIUserScriptLoader::OnSingleWebUIURLFetchComplete( } void WebUIUserScriptLoader::OnWebUIURLFetchComplete() { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, - base::BindOnce( - &SerializeOnBlockingTask, base::SequencedTaskRunnerHandle::Get(), - std::move(user_scripts_cache_), std::move(scripts_loaded_callback_))); + base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(&SerializeOnBlockingTask, + base::SequencedTaskRunnerHandle::Get(), + std::move(user_scripts_cache_), + std::move(scripts_loaded_callback_))); } diff --git a/chromium/extensions/browser/zipfile_installer.cc b/chromium/extensions/browser/zipfile_installer.cc index a25cbd6b617..380149d89db 100644 --- a/chromium/extensions/browser/zipfile_installer.cc +++ b/chromium/extensions/browser/zipfile_installer.cc @@ -9,6 +9,7 @@ #include "base/path_service.h" #include "base/task/post_task.h" #include "base/task_runner_util.h" +#include "components/services/unzip/content/unzip_service.h" #include "components/services/unzip/public/cpp/unzip.h" #include "components/services/unzip/public/mojom/unzipper.mojom.h" #include "extensions/browser/extension_file_task_runner.h" @@ -112,7 +113,7 @@ void ZipFileInstaller::Unzip(base::Optional<base::FilePath> unzip_dir) { } unzip::UnzipWithFilter( - connector_->Clone(), zip_file_, *unzip_dir, + unzip::LaunchUnzipper(), zip_file_, *unzip_dir, base::BindRepeating(&ZipFileInstaller::IsManifestFile), base::BindOnce(&ZipFileInstaller::ManifestUnzipped, this, *unzip_dir)); } @@ -172,7 +173,7 @@ void ZipFileInstaller::ManifestParsed(const base::FilePath& unzip_dir, // TODO(crbug.com/645263): This silently ignores blocked file types. // Add install warnings. unzip::UnzipWithFilter( - connector_->Clone(), zip_file_, unzip_dir, filter, + unzip::LaunchUnzipper(), zip_file_, unzip_dir, filter, base::BindOnce(&ZipFileInstaller::UnzipDone, this, unzip_dir)); } |
