diff options
Diffstat (limited to 'chromium/chrome/browser/extensions/api')
179 files changed, 2449 insertions, 1132 deletions
diff --git a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc index fe00902f063..4893fc3f2da 100644 --- a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc @@ -64,9 +64,9 @@ IN_PROC_BROWSER_TEST_F(ActivityLogApiTest, MAYBE_TriggerEvent) { ActivityLog::GetInstance(profile())->SetWatchdogAppActiveForTesting(true); host_resolver()->AddRule("*", "127.0.0.1"); - ASSERT_TRUE(StartEmbeddedTestServer()); embedded_test_server()->RegisterRequestHandler( base::Bind(&ActivityLogApiTest::HandleRequest, base::Unretained(this))); + ASSERT_TRUE(StartEmbeddedTestServer()); const Extension* friend_extension = LoadExtensionIncognito( test_data_dir_.AppendASCII("activity_log_private/friend")); diff --git a/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.h b/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.h index 704f843b81c..7dabff64058 100644 --- a/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.h +++ b/chromium/chrome/browser/extensions/api/autofill_private/autofill_util.h @@ -13,11 +13,6 @@ #include "chrome/common/extensions/api/autofill_private.h" #include "components/autofill/core/browser/personal_data_manager.h" -namespace autofill { -class AutofillProfile; -class CreditCard; -} - namespace extensions { namespace autofill_util { diff --git a/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc b/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc index 8d9d827dad5..b498453e2d3 100644 --- a/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc +++ b/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc @@ -83,7 +83,7 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, TestRendererAccessibilityEnabled) { content::WebContents* const tab = browser()->tab_strip_model()->GetWebContentsAt(0); ASSERT_FALSE(tab->IsFullAccessibilityModeForTesting()); - ASSERT_FALSE(tab->IsTreeOnlyAccessibilityModeForTesting()); + ASSERT_FALSE(tab->IsWebContentsOnlyAccessibilityModeForTesting()); base::FilePath extension_path = test_data_dir_.AppendASCII("automation/tests/basic"); @@ -92,7 +92,7 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, TestRendererAccessibilityEnabled) { ASSERT_TRUE(got_tree.WaitUntilSatisfied()); ASSERT_FALSE(tab->IsFullAccessibilityModeForTesting()); - ASSERT_TRUE(tab->IsTreeOnlyAccessibilityModeForTesting()); + ASSERT_TRUE(tab->IsWebContentsOnlyAccessibilityModeForTesting()); } IN_PROC_BROWSER_TEST_F(AutomationApiTest, SanityCheck) { @@ -145,6 +145,12 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, LineStartOffsets) { << message_; } +IN_PROC_BROWSER_TEST_F(AutomationApiTest, ImageData) { + StartEmbeddedTestServer(); + ASSERT_TRUE(RunExtensionSubtest("automation/tests/tabs", "image_data.html")) + << message_; +} + IN_PROC_BROWSER_TEST_F(AutomationApiTest, TabsAutomationBooleanPermissions) { StartEmbeddedTestServer(); ASSERT_TRUE(RunExtensionSubtest( diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h index be7fc766c2a..6edd9ec3281 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h +++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.h @@ -27,7 +27,6 @@ struct ExtensionMsg_AccessibilityLocationChangeParams; namespace extensions { struct AutomationListener; -class Extension; class AutomationEventRouter : public content::NotificationObserver { public: diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc index f1ff4d860a4..ccaf89d8936 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc +++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc @@ -28,6 +28,7 @@ #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_plugin_guest_manager.h" +#include "content/public/browser/media_session.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" @@ -222,12 +223,45 @@ class AutomationWebContentsObserver browser_context_); } + void MediaStartedPlaying(const MediaPlayerInfo& video_type, + const MediaPlayerId& id) override { + std::vector<content::AXEventNotificationDetails> details; + content::AXEventNotificationDetails detail; + detail.ax_tree_id = id.first->GetAXTreeID(); + detail.event_type = ui::AX_EVENT_MEDIA_STARTED_PLAYING; + details.push_back(detail); + AccessibilityEventReceived(details); + } + + void MediaStoppedPlaying(const MediaPlayerInfo& video_type, + const MediaPlayerId& id) override { + std::vector<content::AXEventNotificationDetails> details; + content::AXEventNotificationDetails detail; + detail.ax_tree_id = id.first->GetAXTreeID(); + detail.event_type = ui::AX_EVENT_MEDIA_STOPPED_PLAYING; + details.push_back(detail); + AccessibilityEventReceived(details); + } + private: friend class content::WebContentsUserData<AutomationWebContentsObserver>; explicit AutomationWebContentsObserver(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), - browser_context_(web_contents->GetBrowserContext()) {} + browser_context_(web_contents->GetBrowserContext()) { + if (web_contents->WasRecentlyAudible()) { + std::vector<content::AXEventNotificationDetails> details; + content::RenderFrameHost* rfh = web_contents->GetMainFrame(); + if (!rfh) + return; + + content::AXEventNotificationDetails detail; + detail.ax_tree_id = rfh->GetAXTreeID(); + detail.event_type = ui::AX_EVENT_MEDIA_STARTED_PLAYING; + details.push_back(detail); + AccessibilityEventReceived(details); + } + } content::BrowserContext* browser_context_; @@ -271,7 +305,7 @@ AutomationInternalEnableTabFunction::Run() { } AutomationWebContentsObserver::CreateForWebContents(contents); - contents->EnableTreeOnlyAccessibilityMode(); + contents->EnableWebContentsOnlyAccessibilityMode(); int ax_tree_id = rfh->GetAXTreeID(); @@ -305,7 +339,7 @@ ExtensionFunction::ResponseAction AutomationInternalEnableFrameFunction::Run() { // Only call this if this is the root of a frame tree, to avoid resetting // the accessibility state multiple times. if (!rfh->GetParent()) - contents->EnableTreeOnlyAccessibilityMode(); + contents->EnableWebContentsOnlyAccessibilityMode(); return RespondNow(NoArguments()); } @@ -334,13 +368,36 @@ AutomationInternalPerformActionFunction::Run() { if (!rfh) return RespondNow(Error("Ignoring action on destroyed node")); - const content::WebContents* contents = + content::WebContents* contents = content::WebContents::FromRenderFrameHost(rfh); if (!CanRequestAutomation(extension(), automation_info, contents)) { return RespondNow( Error(kCannotRequestAutomationOnPage, contents->GetURL().spec())); } + // These actions are handled directly for the WebContents. + if (params->args.action_type == + api::automation_internal::ACTION_TYPE_STARTDUCKINGMEDIA) { + content::MediaSession* session = content::MediaSession::Get(contents); + session->StartDucking(); + return RespondNow(NoArguments()); + } else if (params->args.action_type == + api::automation_internal::ACTION_TYPE_STOPDUCKINGMEDIA) { + content::MediaSession* session = content::MediaSession::Get(contents); + session->StopDucking(); + return RespondNow(NoArguments()); + } else if (params->args.action_type == + api::automation_internal::ACTION_TYPE_RESUMEMEDIA) { + content::MediaSession* session = content::MediaSession::Get(contents); + session->Resume(content::MediaSession::SuspendType::SYSTEM); + return RespondNow(NoArguments()); + } else if (params->args.action_type == + api::automation_internal::ACTION_TYPE_SUSPENDMEDIA) { + content::MediaSession* session = content::MediaSession::Get(contents); + session->Suspend(content::MediaSession::SuspendType::SYSTEM); + return RespondNow(NoArguments()); + } + RenderFrameHostActionAdapter adapter(rfh); return RouteActionToAdapter(params.get(), &adapter); } @@ -357,9 +414,21 @@ AutomationInternalPerformActionFunction::RouteActionToAdapter( adapter->PerformAction(action); break; case api::automation_internal::ACTION_TYPE_FOCUS: - action.action = ui::AX_ACTION_SET_FOCUS; + action.action = ui::AX_ACTION_FOCUS; + adapter->PerformAction(action); + break; + case api::automation_internal::ACTION_TYPE_GETIMAGEDATA: { + api::automation_internal::GetImageDataParams get_image_data_params; + EXTENSION_FUNCTION_VALIDATE( + api::automation_internal::GetImageDataParams::Populate( + params->opt_args.additional_properties, &get_image_data_params)); + action.action = ui::AX_ACTION_GET_IMAGE_DATA; + action.target_rect = gfx::Rect( + 0, 0, get_image_data_params.max_width, + get_image_data_params.max_height); adapter->PerformAction(action); break; + } case api::automation_internal::ACTION_TYPE_MAKEVISIBLE: action.action = ui::AX_ACTION_SCROLL_TO_MAKE_VISIBLE; adapter->PerformAction(action); diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.h b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.h index 5761d26cd41..9e65175160b 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.h +++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.h @@ -9,10 +9,6 @@ #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" -namespace content { -struct AXEventNotificationDetails; -} // namespace content - namespace extensions { class AutomationActionAdapter; @@ -25,10 +21,6 @@ struct Params; } // namespace api } // namespace extensions -namespace ui { -struct AXNodeData; -} - namespace extensions { // Implementation of the chrome.automation API. diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc index b15e0576bfe..9b4e4a186ec 100644 --- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc +++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc @@ -11,7 +11,6 @@ #include <string> #include <utility> -#include "base/strings/stringprintf.h" #include "base/values.h" #include "chrome/browser/browsing_data/browsing_data_helper.h" #include "chrome/browser/browsing_data/browsing_data_remover.h" @@ -21,6 +20,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" +#include "components/browsing_data/core/browsing_data_utils.h" #include "components/browsing_data/core/pref_names.h" #include "content/public/browser/browser_thread.h" #include "extensions/common/error_utils.h" @@ -65,8 +65,6 @@ const char kUnprotectedWebKey[] = "unprotectedWeb"; const char kBadDataTypeDetails[] = "Invalid value for data type '%s'."; const char kDeleteProhibitedError[] = "Browsing history and downloads are not " "permitted to be removed."; -const char kOneAtATimeError[] = "Only one 'browsingData' API call can run at " - "a time."; } // namespace extension_browsing_data_api_constants @@ -314,14 +312,7 @@ void BrowsingDataRemoverFunction::CheckRemovingPluginDataSupported( void BrowsingDataRemoverFunction::StartRemoving() { BrowsingDataRemover* remover = BrowsingDataRemoverFactory::GetForBrowserContext(GetProfile()); - // TODO(msramek): This restriction is no longer needed. Remove it. - if (remover->is_removing()) { - error_ = extension_browsing_data_api_constants::kOneAtATimeError; - SendResponse(false); - return; - } - - // If we're good to go, add a ref (Balanced in OnBrowsingDataRemoverDone) + // Add a ref (Balanced in OnBrowsingDataRemoverDone) AddRef(); // Create a BrowsingDataRemover, set the current object as an observer (so @@ -330,7 +321,7 @@ void BrowsingDataRemoverFunction::StartRemoving() { // remover is responsible for deleting itself once data removal is complete. observer_.Add(remover); remover->RemoveAndReply( - BrowsingDataRemover::TimeRange(remove_since_, base::Time::Max()), + remove_since_, base::Time::Max(), removal_mask_, origin_type_mask_, this); } diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h index b4c7594af54..40057174880 100644 --- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h +++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h @@ -51,7 +51,6 @@ extern const char kUnprotectedWebKey[]; // Errors! extern const char kBadDataTypeDetails[]; extern const char kDeleteProhibitedError[]; -extern const char kOneAtATimeError[]; } // namespace extension_browsing_data_api_constants diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc index 394a4f3b255..10efc181e6f 100644 --- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc +++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc @@ -9,7 +9,6 @@ #include "base/memory/ref_counted.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" #include "base/values.h" #include "chrome/browser/browsing_data/browsing_data_helper.h" #include "chrome/browser/browsing_data/browsing_data_remover.h" @@ -20,6 +19,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/browsing_data/core/browsing_data_utils.h" #include "components/browsing_data/core/pref_names.h" #include "components/prefs/pref_service.h" @@ -222,6 +222,7 @@ class ExtensionBrowsingDataTest : public InProcessBrowserTest { BrowsingDataRemover::REMOVE_WEBSQL) | GetAsMask(data_to_remove, "serverBoundCertificates", BrowsingDataRemover::REMOVE_CHANNEL_IDS); + EXPECT_EQ(expected_removal_mask, removal_mask); } @@ -250,22 +251,6 @@ class ExtensionBrowsingDataTest : public InProcessBrowserTest { } // namespace -IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, OneAtATime) { - BrowsingDataRemover* browsing_data_remover = - BrowsingDataRemoverFactory::GetForBrowserContext(browser()->profile()); - browsing_data_remover->SetRemoving(true); - scoped_refptr<BrowsingDataRemoveFunction> function = - new BrowsingDataRemoveFunction(); - EXPECT_TRUE(base::MatchPattern( - RunFunctionAndReturnError(function.get(), kRemoveEverythingArguments, - browser()), - extension_browsing_data_api_constants::kOneAtATimeError)); - browsing_data_remover->SetRemoving(false); - - EXPECT_EQ(base::Time(), GetBeginTime()); - EXPECT_EQ(-1, GetRemovalMask()); -} - IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, RemovalProhibited) { PrefService* prefs = browser()->profile()->GetPrefs(); prefs->SetBoolean(prefs::kAllowDeletingBrowserHistory, false); @@ -304,21 +289,25 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, RemoveBrowsingDataAll) { browser())); EXPECT_EQ(base::Time::FromDoubleT(1.0), GetBeginTime()); - EXPECT_EQ((BrowsingDataRemover::REMOVE_SITE_DATA | - BrowsingDataRemover::REMOVE_CACHE | - BrowsingDataRemover::REMOVE_DOWNLOADS | - BrowsingDataRemover::REMOVE_FORM_DATA | - BrowsingDataRemover::REMOVE_HISTORY | - BrowsingDataRemover::REMOVE_PASSWORDS) & - // TODO(benwells): implement clearing of site usage data via the - // browsing data API. https://crbug.com/500801. - ~BrowsingDataRemover::REMOVE_SITE_USAGE_DATA & - // TODO(dmurph): implement clearing of durable storage permission - // via the browsing data API. https://crbug.com/500801. - ~BrowsingDataRemover::REMOVE_DURABLE_PERMISSION & - // We can't remove plugin data inside a test profile. - ~BrowsingDataRemover::REMOVE_PLUGIN_DATA, - GetRemovalMask()); + EXPECT_EQ( + (BrowsingDataRemover::REMOVE_SITE_DATA | + BrowsingDataRemover::REMOVE_CACHE | + BrowsingDataRemover::REMOVE_DOWNLOADS | + BrowsingDataRemover::REMOVE_FORM_DATA | + BrowsingDataRemover::REMOVE_HISTORY | + BrowsingDataRemover::REMOVE_PASSWORDS) & + // TODO(benwells): implement clearing of site usage data via the + // browsing data API. https://crbug.com/500801. + ~BrowsingDataRemover::REMOVE_SITE_USAGE_DATA & + // TODO(dmurph): implement clearing of durable storage permission + // via the browsing data API. https://crbug.com/500801. + ~BrowsingDataRemover::REMOVE_DURABLE_PERMISSION & + // We can't remove plugin data inside a test profile. + ~BrowsingDataRemover::REMOVE_PLUGIN_DATA & + // TODO(ramyasharma): implement clearing of external protocol data + // via the browsing data API. https://crbug.com/692850. + ~BrowsingDataRemover::REMOVE_EXTERNAL_PROTOCOL_DATA, + GetRemovalMask()); } IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, BrowsingDataOriginTypeMask) { @@ -494,46 +483,46 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionSimple) { // Test cookie and app data settings. IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionSiteData) { - int site_data_no_durable_or_usage = + int site_data_no_durable_or_usage_or_external = BrowsingDataRemover::REMOVE_SITE_DATA & ~BrowsingDataRemover::REMOVE_SITE_USAGE_DATA & - ~BrowsingDataRemover::REMOVE_DURABLE_PERMISSION; - int site_data_no_plugins_durable_usage = - site_data_no_durable_or_usage & ~BrowsingDataRemover::REMOVE_PLUGIN_DATA; + ~BrowsingDataRemover::REMOVE_DURABLE_PERMISSION & + ~BrowsingDataRemover::REMOVE_EXTERNAL_PROTOCOL_DATA; + int site_data_no_plugins_durable_usage_external = + site_data_no_durable_or_usage_or_external & + ~BrowsingDataRemover::REMOVE_PLUGIN_DATA; SetPrefsAndVerifySettings(BrowsingDataRemover::REMOVE_COOKIES, UNPROTECTED_WEB, - site_data_no_plugins_durable_usage); + site_data_no_plugins_durable_usage_external); SetPrefsAndVerifySettings( - BrowsingDataRemover::REMOVE_HOSTED_APP_DATA_TESTONLY, - PROTECTED_WEB, - site_data_no_plugins_durable_usage); + BrowsingDataRemover::REMOVE_HOSTED_APP_DATA_TESTONLY, PROTECTED_WEB, + site_data_no_plugins_durable_usage_external); SetPrefsAndVerifySettings( BrowsingDataRemover::REMOVE_COOKIES | BrowsingDataRemover::REMOVE_HOSTED_APP_DATA_TESTONLY, PROTECTED_WEB | UNPROTECTED_WEB, - site_data_no_plugins_durable_usage); - SetPrefsAndVerifySettings( - BrowsingDataRemover::REMOVE_COOKIES | - BrowsingDataRemover::REMOVE_PLUGIN_DATA, - UNPROTECTED_WEB, - site_data_no_durable_or_usage); + site_data_no_plugins_durable_usage_external); + SetPrefsAndVerifySettings(BrowsingDataRemover::REMOVE_COOKIES | + BrowsingDataRemover::REMOVE_PLUGIN_DATA, + UNPROTECTED_WEB, + site_data_no_durable_or_usage_or_external); } // Test an arbitrary assortment of settings. IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionAssorted) { - int site_data_no_plugins_durable_usage = + int site_data_no_plugins_durable_usage_external = BrowsingDataRemover::REMOVE_SITE_DATA & ~BrowsingDataRemover::REMOVE_DURABLE_PERMISSION & ~BrowsingDataRemover::REMOVE_SITE_USAGE_DATA & - ~BrowsingDataRemover::REMOVE_PLUGIN_DATA; + ~BrowsingDataRemover::REMOVE_PLUGIN_DATA & + ~BrowsingDataRemover::REMOVE_EXTERNAL_PROTOCOL_DATA; - SetPrefsAndVerifySettings( - BrowsingDataRemover::REMOVE_COOKIES | - BrowsingDataRemover::REMOVE_HISTORY | - BrowsingDataRemover::REMOVE_DOWNLOADS, - UNPROTECTED_WEB, - site_data_no_plugins_durable_usage | - BrowsingDataRemover::REMOVE_HISTORY | - BrowsingDataRemover::REMOVE_DOWNLOADS); + SetPrefsAndVerifySettings(BrowsingDataRemover::REMOVE_COOKIES | + BrowsingDataRemover::REMOVE_HISTORY | + BrowsingDataRemover::REMOVE_DOWNLOADS, + UNPROTECTED_WEB, + site_data_no_plugins_durable_usage_external | + BrowsingDataRemover::REMOVE_HISTORY | + BrowsingDataRemover::REMOVE_DOWNLOADS); } diff --git a/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc b/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc index 81bf52b83ff..b66206af9d7 100644 --- a/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc +++ b/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc @@ -13,7 +13,6 @@ #include "base/strings/stringprintf.h" #include "base/test/trace_event_analyzer.h" #include "base/time/default_tick_clock.h" -#include "base/win/windows_version.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/tab_helper.h" @@ -54,6 +53,10 @@ #include "ui/compositor/compositor_switches.h" #include "ui/gl/gl_switches.h" +#if defined(OS_WIN) +#include "base/win/windows_version.h" +#endif + namespace { const char kExtensionId[] = "ddchlicdkolnonkihahngkmmmjnjlkkf"; diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc index cdf49c4a99b..917a7d88b37 100644 --- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc +++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc @@ -11,6 +11,7 @@ #include <vector> #include "base/logging.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h" #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h" #include "chrome/common/extensions/api/certificate_provider.h" @@ -19,10 +20,35 @@ #include "net/cert/x509_certificate.h" #include "net/ssl/ssl_private_key.h" -namespace extensions { +namespace api_cp = extensions::api::certificate_provider; +namespace api_cpi = extensions::api::certificate_provider_internal; -namespace api_cp = api::certificate_provider; -namespace api_cpi = api::certificate_provider_internal; +namespace { + +chromeos::RequestPinView::RequestPinErrorType GetErrorTypeForView( + api_cp::PinRequestErrorType error_type) { + switch (error_type) { + case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_INVALID_PIN: + return chromeos::RequestPinView::RequestPinErrorType::INVALID_PIN; + case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_INVALID_PUK: + return chromeos::RequestPinView::RequestPinErrorType::INVALID_PUK; + case api_cp::PinRequestErrorType:: + PIN_REQUEST_ERROR_TYPE_MAX_ATTEMPTS_EXCEEDED: + return chromeos::RequestPinView::RequestPinErrorType:: + MAX_ATTEMPTS_EXCEEDED; + case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_UNKNOWN_ERROR: + return chromeos::RequestPinView::RequestPinErrorType::UNKNOWN_ERROR; + case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_NONE: + return chromeos::RequestPinView::RequestPinErrorType::NONE; + } + + NOTREACHED(); + return chromeos::RequestPinView::RequestPinErrorType::NONE; +} + +} // namespace + +namespace extensions { namespace { @@ -33,8 +59,17 @@ const char kErrorUnknownKeyType[] = "Key type unknown."; const char kErrorAborted[] = "Request was aborted."; const char kErrorTimeout[] = "Request timed out, reply rejected."; +// requestPin constants. +const char kNoActiveDialog[] = "No active dialog from extension."; +const char kInvalidId[] = "Invalid signRequestId"; +const char kOtherFlowInProgress[] = "Other flow in progress"; +const char kPreviousDialogActive[] = "Previous request not finished"; +const char kNoUserInput[] = "No user input received"; + } // namespace +const int api::certificate_provider::kMaxClosedDialogsPer10Mins = 2; + CertificateProviderInternalReportCertificatesFunction:: ~CertificateProviderInternalReportCertificatesFunction() {} @@ -148,6 +183,152 @@ bool CertificateProviderInternalReportCertificatesFunction:: return true; } +CertificateProviderStopPinRequestFunction:: + ~CertificateProviderStopPinRequestFunction() {} + +ExtensionFunction::ResponseAction +CertificateProviderStopPinRequestFunction::Run() { + std::unique_ptr<api_cp::RequestPin::Params> params( + api_cp::RequestPin::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params); + + chromeos::CertificateProviderService* const service = + chromeos::CertificateProviderServiceFactory::GetForBrowserContext( + browser_context()); + DCHECK(service); + if (params->details.error_type == + api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_NONE) { + bool dialog_closed = + service->pin_dialog_manager()->CloseDialog(extension_id()); + if (!dialog_closed) { + // This might happen if the user closed the dialog while extension was + // processing the input. + return RespondNow(Error(kNoActiveDialog)); + } + + return RespondNow(NoArguments()); + } + + // Extension provided an error, which means it intends to notify the user with + // the error and not allow any more input. + chromeos::RequestPinView::RequestPinErrorType error_type = + GetErrorTypeForView(params->details.error_type); + chromeos::PinDialogManager::StopPinRequestResponse update_response = + service->pin_dialog_manager()->UpdatePinDialog( + extension()->id(), error_type, + false, // Don't accept any input. + base::Bind(&CertificateProviderStopPinRequestFunction::DialogClosed, + this)); + switch (update_response) { + case chromeos::PinDialogManager::StopPinRequestResponse::NO_ACTIVE_DIALOG: + return RespondNow(Error(kNoActiveDialog)); + case chromeos::PinDialogManager::StopPinRequestResponse::NO_USER_INPUT: + return RespondNow(Error(kNoUserInput)); + case chromeos::PinDialogManager::StopPinRequestResponse::STOPPED: + return RespondLater(); + } + + NOTREACHED(); + return RespondLater(); +} + +void CertificateProviderStopPinRequestFunction::DialogClosed( + const base::string16& value) { + chromeos::CertificateProviderService* const service = + chromeos::CertificateProviderServiceFactory::GetForBrowserContext( + browser_context()); + DCHECK(service); + + Respond(NoArguments()); + service->pin_dialog_manager()->OnPinDialogClosed(); +} + +CertificateProviderRequestPinFunction:: + ~CertificateProviderRequestPinFunction() {} + +bool CertificateProviderRequestPinFunction::ShouldSkipQuotaLimiting() const { + chromeos::CertificateProviderService* const service = + chromeos::CertificateProviderServiceFactory::GetForBrowserContext( + browser_context()); + DCHECK(service); + + return !service->pin_dialog_manager()->LastPinDialogClosed(extension_id()); +} + +void CertificateProviderRequestPinFunction::GetQuotaLimitHeuristics( + extensions::QuotaLimitHeuristics* heuristics) const { + QuotaLimitHeuristic::Config short_limit_config = { + api::certificate_provider::kMaxClosedDialogsPer10Mins, + base::TimeDelta::FromMinutes(10)}; + heuristics->push_back(base::MakeUnique<QuotaService::TimedLimit>( + short_limit_config, new QuotaLimitHeuristic::SingletonBucketMapper(), + "MAX_PIN_DIALOGS_CLOSED_PER_10_MINUTES")); +} + +ExtensionFunction::ResponseAction CertificateProviderRequestPinFunction::Run() { + std::unique_ptr<api_cp::RequestPin::Params> params( + api_cp::RequestPin::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params); + + api_cp::PinRequestType pin_request_type = + params->details.request_type == + api_cp::PinRequestType::PIN_REQUEST_TYPE_NONE + ? api_cp::PinRequestType::PIN_REQUEST_TYPE_PIN + : params->details.request_type; + + chromeos::RequestPinView::RequestPinErrorType error_type = + GetErrorTypeForView(params->details.error_type); + + chromeos::RequestPinView::RequestPinCodeType code_type = + (pin_request_type == api_cp::PinRequestType::PIN_REQUEST_TYPE_PIN) + ? chromeos::RequestPinView::RequestPinCodeType::PIN + : chromeos::RequestPinView::RequestPinCodeType::PUK; + + chromeos::CertificateProviderService* const service = + chromeos::CertificateProviderServiceFactory::GetForBrowserContext( + browser_context()); + DCHECK(service); + + int attempts_left = + params->details.attempts_left ? *params->details.attempts_left : -1; + chromeos::PinDialogManager::RequestPinResponse result = + service->pin_dialog_manager()->ShowPinDialog( + extension()->id(), extension()->name(), + params->details.sign_request_id, code_type, error_type, attempts_left, + base::Bind(&CertificateProviderRequestPinFunction::OnInputReceived, + this)); + switch (result) { + case chromeos::PinDialogManager::RequestPinResponse::SUCCESS: + return RespondLater(); + case chromeos::PinDialogManager::RequestPinResponse::INVALID_ID: + return RespondNow(Error(kInvalidId)); + case chromeos::PinDialogManager::RequestPinResponse::OTHER_FLOW_IN_PROGRESS: + return RespondNow(Error(kOtherFlowInProgress)); + case chromeos::PinDialogManager::RequestPinResponse:: + DIALOG_DISPLAYED_ALREADY: + return RespondNow(Error(kPreviousDialogActive)); + } + + NOTREACHED(); + return RespondNow(Error(kPreviousDialogActive)); +} + +void CertificateProviderRequestPinFunction::OnInputReceived( + const base::string16& value) { + std::unique_ptr<base::ListValue> create_results(new base::ListValue()); + chromeos::CertificateProviderService* const service = + chromeos::CertificateProviderServiceFactory::GetForBrowserContext( + browser_context()); + DCHECK(service); + if (!value.empty()) { + api::certificate_provider::PinResponseDetails details; + details.user_input.reset(new std::string(value.begin(), value.end())); + create_results->Append(details.ToValue()); + } + + Respond(ArgumentList(std::move(create_results))); +} + CertificateProviderInternalReportSignatureFunction:: ~CertificateProviderInternalReportSignatureFunction() {} diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h index bc4ec19752b..1f4686bb78b 100644 --- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h +++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h @@ -17,6 +17,10 @@ namespace extensions { namespace api { namespace certificate_provider { +// The maximum number of times per 10 minutes, extension is allowed to show PIN +// dialog again after user closed the previous one. +extern const int kMaxClosedDialogsPer10Mins; + struct CertificateInfo; } } @@ -45,6 +49,30 @@ class CertificateProviderInternalReportSignatureFunction CERTIFICATEPROVIDERINTERNAL_REPORTSIGNATURE); }; +class CertificateProviderRequestPinFunction : public UIThreadExtensionFunction { + private: + ~CertificateProviderRequestPinFunction() override; + ResponseAction Run() override; + bool ShouldSkipQuotaLimiting() const override; + void GetQuotaLimitHeuristics( + extensions::QuotaLimitHeuristics* heuristics) const override; + void OnInputReceived(const base::string16& value); + + DECLARE_EXTENSION_FUNCTION("certificateProvider.requestPin", + CERTIFICATEPROVIDER_REQUESTPIN); +}; + +class CertificateProviderStopPinRequestFunction + : public UIThreadExtensionFunction { + private: + ~CertificateProviderStopPinRequestFunction() override; + ResponseAction Run() override; + void DialogClosed(const base::string16& value); + + DECLARE_EXTENSION_FUNCTION("certificateProvider.stopPinRequest", + CERTIFICATEPROVIDER_STOPPINREQUEST); +}; + } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_CERTIFICATE_PROVIDER_CERTIFICATE_PROVIDER_API_H_ diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc index e6c94df4e2b..bd24b95add7 100644 --- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc +++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc @@ -18,6 +18,9 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" +#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h" +#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h" +#include "chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/ui_test_utils.h" @@ -32,11 +35,16 @@ #include "content/public/test/test_utils.h" #include "crypto/rsa_private_key.h" #include "extensions/common/extension.h" +#include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" #include "net/test/spawned_test_server/spawned_test_server.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/boringssl/src/include/openssl/evp.h" #include "third_party/boringssl/src/include/openssl/rsa.h" +#include "ui/views/controls/label.h" +#include "ui/views/controls/textfield/textfield.h" +#include "ui/views/widget/widget.h" +#include "ui/views/widget/widget_observer.h" using testing::Return; using testing::_; @@ -121,6 +129,41 @@ std::string JsUint8Array(const std::vector<uint8_t>& bytes) { return res; } +// Enters the code in the ShowPinDialog window and pushes the OK event. +void EnterCode(chromeos::CertificateProviderService* service, + const base::string16& code) { + chromeos::RequestPinView* view = + service->pin_dialog_manager()->active_view_for_testing(); + view->textfield_for_testing()->SetText(code); + view->Accept(); + base::RunLoop().RunUntilIdle(); +} + +// Enters the valid code for extensions from local example folders, in the +// ShowPinDialog window and waits for the window to close. The extension code +// is expected to send "Success" message after the validation and request to +// stopPinRequest is done. +void EnterCorrectPin(chromeos::CertificateProviderService* service) { + ExtensionTestMessageListener listener("Success", false); + EnterCode(service, base::ASCIIToUTF16("1234")); + ASSERT_TRUE(listener.WaitUntilSatisfied()); +} + +// Enters an invalid code for extensions from local example folders, in the +// ShowPinDialog window and waits for the window to update with the error. The +// extension code is expected to send "Invalid PIN" message after the validation +// and the new requestPin (with the error) is done. +void EnterWrongPin(chromeos::CertificateProviderService* service) { + ExtensionTestMessageListener listener("Invalid PIN", false); + EnterCode(service, base::ASCIIToUTF16("567")); + ASSERT_TRUE(listener.WaitUntilSatisfied()); + + // Check that we have an error message displayed. + chromeos::RequestPinView* view = + service->pin_dialog_manager()->active_view_for_testing(); + EXPECT_EQ(SK_ColorRED, view->error_label_for_testing()->enabled_color()); +} + class CertificateProviderApiTest : public ExtensionApiTest { public: CertificateProviderApiTest() {} @@ -134,6 +177,7 @@ class CertificateProviderApiTest : public ExtensionApiTest { } void SetUpOnMainThread() override { + ExtensionApiTest::SetUpOnMainThread(); // Set up the AutoSelectCertificateForUrls policy to avoid the client // certificate selection dialog. const std::string autoselect_pattern = @@ -156,6 +200,27 @@ class CertificateProviderApiTest : public ExtensionApiTest { policy::MockConfigurationPolicyProvider provider_; }; +class CertificateProviderRequestPinTest : public CertificateProviderApiTest { + public: + // Loads certificate_provider extension from |folder| and |file_name|. + // Returns the CertificateProviderService object from browser context. + chromeos::CertificateProviderService* LoadRequestPinExtension( + const std::string& folder, + const std::string& file_name) { + const base::FilePath extension_path = + test_data_dir_.AppendASCII("certificate_provider/" + folder); + const extensions::Extension* const extension = + LoadExtension(extension_path); + chromeos::CertificateProviderService* service = + chromeos::CertificateProviderServiceFactory::GetForBrowserContext( + profile()); + service->pin_dialog_manager()->AddSignRequestId(extension->id(), 123); + ui_test_utils::NavigateToURL(browser(), + extension->GetResourceURL(file_name)); + return service; + } +}; + } // namespace IN_PROC_BROWSER_TEST_F(CertificateProviderApiTest, Basic) { @@ -267,3 +332,99 @@ IN_PROC_BROWSER_TEST_F(CertificateProviderApiTest, Basic) { EXPECT_TRUE(result); } } + +// User enters the correct PIN. +IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, ShowPinDialogAccept) { + chromeos::CertificateProviderService* service = + LoadRequestPinExtension("request_pin", "basic.html"); + + // Enter the valid PIN. + EnterCorrectPin(service); + + // The view should be set to nullptr when the window is closed. + EXPECT_EQ(service->pin_dialog_manager()->active_view_for_testing(), nullptr); +} + +// User closes the dialog kMaxClosedDialogsPer10Mins times, and the extension +// should be blocked from showing it again. +IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, ShowPinDialogClose) { + chromeos::CertificateProviderService* service = + LoadRequestPinExtension("request_pin", "basic.html"); + + views::Widget* window = + service->pin_dialog_manager()->active_window_for_testing(); + for (int i = 0; + i < extensions::api::certificate_provider::kMaxClosedDialogsPer10Mins; + i++) { + ExtensionTestMessageListener listener("User closed the dialog", false); + window->Close(); + ASSERT_TRUE(listener.WaitUntilSatisfied()); + window = service->pin_dialog_manager()->active_window_for_testing(); + } + + ExtensionTestMessageListener close_listener("User closed the dialog", true); + window->Close(); + ASSERT_TRUE(close_listener.WaitUntilSatisfied()); + close_listener.Reply("GetLastError"); + ExtensionTestMessageListener last_error_listener( + "This request exceeds the MAX_PIN_DIALOGS_CLOSED_PER_10_MINUTES quota.", + false); + ASSERT_TRUE(last_error_listener.WaitUntilSatisfied()); + EXPECT_EQ(service->pin_dialog_manager()->active_view_for_testing(), nullptr); +} + +// User enters a wrong PIN first and a correct PIN on the second try. +IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, + ShowPinDialogWrongPin) { + chromeos::CertificateProviderService* service = + LoadRequestPinExtension("request_pin", "basic.html"); + EnterWrongPin(service); + + // The window should be active. + EXPECT_EQ( + service->pin_dialog_manager()->active_window_for_testing()->IsVisible(), + true); + EXPECT_NE(service->pin_dialog_manager()->active_view_for_testing(), nullptr); + + // Enter the valid PIN. + EnterCorrectPin(service); + + // The view should be set to nullptr when the window is closed. + EXPECT_EQ(service->pin_dialog_manager()->active_view_for_testing(), nullptr); +} + +// User enters wrong PIN three times. +IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, + ShowPinDialogWrongPinThreeTimes) { + chromeos::CertificateProviderService* service = + LoadRequestPinExtension("request_pin", "basic.html"); + for (int i = 0; i < 3; i++) { + EnterWrongPin(service); + } + + chromeos::RequestPinView* view = + service->pin_dialog_manager()->active_view_for_testing(); + + // The textfield has to be disabled, as extension does not allow input now. + EXPECT_EQ(view->textfield_for_testing()->enabled(), false); + + // Close the dialog. + ExtensionTestMessageListener listener("No attempt left", false); + service->pin_dialog_manager()->active_window_for_testing()->Close(); + ASSERT_TRUE(listener.WaitUntilSatisfied()); + EXPECT_EQ(service->pin_dialog_manager()->active_view_for_testing(), nullptr); +} + +// User closes the dialog while the extension is processing the request. +IN_PROC_BROWSER_TEST_F(CertificateProviderRequestPinTest, + ShowPinDialogCloseWhileProcessing) { + chromeos::CertificateProviderService* service = + LoadRequestPinExtension("request_pin", "basic_lock.html"); + + EnterCode(service, base::ASCIIToUTF16("123")); + service->pin_dialog_manager()->active_window_for_testing()->Close(); + base::RunLoop().RunUntilIdle(); + + // The view should be set to nullptr when the window is closed. + EXPECT_EQ(service->pin_dialog_manager()->active_view_for_testing(), nullptr); +} diff --git a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc index d65c7b41f03..b05a4df2de5 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc @@ -36,6 +36,7 @@ #if defined(OS_CHROMEOS) #include "chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h" +#include "chrome/browser/extensions/clipboard_extension_helper_chromeos.h" #endif #if BUILDFLAG(ENABLE_PRINTING) @@ -166,4 +167,17 @@ MetricsPrivateDelegate* ChromeExtensionsAPIClient::GetMetricsPrivateDelegate() { return metrics_private_delegate_.get(); } +#if defined(OS_CHROMEOS) +void ChromeExtensionsAPIClient::SaveImageDataToClipboard( + const std::vector<char>& image_data, + api::clipboard::ImageType type, + const base::Closure& success_callback, + const base::Callback<void(const std::string&)>& error_callback) { + if (!clipboard_extension_helper_) + clipboard_extension_helper_ = base::MakeUnique<ClipboardExtensionHelper>(); + clipboard_extension_helper_->DecodeAndSaveImageData( + image_data, type, success_callback, error_callback); +} +#endif + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h index 2d59b54ef2b..9a4d5e99e7c 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h @@ -12,6 +12,7 @@ namespace extensions { class ChromeMetricsPrivateDelegate; +class ClipboardExtensionHelper; // Extra support for extensions APIs in Chrome. class ChromeExtensionsAPIClient : public ExtensionsAPIClient { @@ -54,9 +55,21 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient { ManagementAPIDelegate* CreateManagementAPIDelegate() const override; MetricsPrivateDelegate* GetMetricsPrivateDelegate() override; +#if defined(OS_CHROMEOS) + void SaveImageDataToClipboard( + const std::vector<char>& image_data, + api::clipboard::ImageType type, + const base::Closure& success_callback, + const base::Callback<void(const std::string&)>& error_callback) override; +#endif + private: std::unique_ptr<ChromeMetricsPrivateDelegate> metrics_private_delegate_; +#if defined(OS_CHROMEOS) + std::unique_ptr<ClipboardExtensionHelper> clipboard_extension_helper_; +#endif + DISALLOW_COPY_AND_ASSIGN(ChromeExtensionsAPIClient); }; diff --git a/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_apitest.cc b/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_apitest.cc index 30c0f8c2ddb..7d3f5265a8d 100644 --- a/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_apitest.cc @@ -5,7 +5,6 @@ #include "chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h" #include "base/macros.h" -#include "base/strings/stringprintf.h" #include "build/build_config.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/profiles/profile.h" diff --git a/chromium/chrome/browser/extensions/api/commands/command_service.h b/chromium/chrome/browser/extensions/api/commands/command_service.h index f1d51316d56..ebff2853236 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service.h +++ b/chromium/chrome/browser/extensions/api/commands/command_service.h @@ -17,10 +17,6 @@ class Profile; -namespace base { -class DictionaryValue; -} - namespace content { class BrowserContext; } diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc index c5e4834a2f2..405ad5b0ecc 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc @@ -53,7 +53,7 @@ bool RemoveContentType(base::ListValue* args, return false; // We remove the ContentSettingsType parameter since this is added by the // renderer, and is not part of the JSON schema. - args->Remove(0, NULL); + args->Remove(0, nullptr); *content_type = extensions::content_settings_helpers::StringToContentSettingsType( content_type_str); @@ -154,9 +154,8 @@ ContentSettingsContentSettingGetFunction::Run() { ContentSetting setting; if (content_type == CONTENT_SETTINGS_TYPE_COOKIES) { // TODO(jochen): Do we return the value for setting or for reading cookies? - bool setting_cookie = false; - setting = cookie_settings->GetCookieSetting(primary_url, secondary_url, - setting_cookie, NULL); + cookie_settings->GetCookieSetting(primary_url, secondary_url, nullptr, + nullptr /* reading_setting */, &setting); } else { setting = map->GetContentSetting(primary_url, secondary_url, content_type, resource_identifier); diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h index 95563d01ddc..fa0fb0c3e11 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h @@ -8,8 +8,6 @@ #include "base/gtest_prod_util.h" #include "chrome/browser/extensions/chrome_extension_function.h" -class PluginFinder; - namespace content { struct WebPluginInfo; } diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc index 3df22217d4e..a3d28d9d303 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.cc @@ -4,15 +4,14 @@ #include "chrome/browser/extensions/api/content_settings/content_settings_store.h" +#include <algorithm> #include <memory> #include <set> #include <utility> -#include <vector> #include "base/debug/alias.h" #include "base/logging.h" #include "base/memory/ptr_util.h" -#include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/values.h" #include "chrome/browser/extensions/api/content_settings/content_settings_api_constants.h" @@ -36,8 +35,10 @@ namespace helpers = content_settings_helpers; namespace keys = content_settings_api_constants; struct ContentSettingsStore::ExtensionEntry { - // Extension id + // Extension id. std::string id; + // Installation time. + base::Time install_time; // Whether extension is enabled in the profile. bool enabled; // Content settings. @@ -53,7 +54,6 @@ ContentSettingsStore::ContentSettingsStore() { } ContentSettingsStore::~ContentSettingsStore() { - base::STLDeleteValues(&entries_); } std::unique_ptr<RuleIterator> ContentSettingsStore::GetRuleIterator( @@ -61,16 +61,14 @@ std::unique_ptr<RuleIterator> ContentSettingsStore::GetRuleIterator( const content_settings::ResourceIdentifier& identifier, bool incognito) const { std::vector<std::unique_ptr<RuleIterator>> iterators; - // Iterate the extensions based on install time (last installed extensions - // first). - ExtensionEntryMap::const_reverse_iterator entry_it; // The individual |RuleIterators| shouldn't lock; pass |lock_| to the // |ConcatenationIterator| in a locked state. std::unique_ptr<base::AutoLock> auto_lock(new base::AutoLock(lock_)); - for (entry_it = entries_.rbegin(); entry_it != entries_.rend(); ++entry_it) { - auto* entry = entry_it->second; + // Iterate the extensions based on install time (most-recently installed + // items first). + for (const auto& entry : entries_) { if (!entry->enabled) continue; @@ -128,13 +126,23 @@ void ContentSettingsStore::RegisterExtension( const base::Time& install_time, bool is_enabled) { base::AutoLock lock(lock_); - ExtensionEntryMap::iterator i = FindEntry(ext_id); - ExtensionEntry* entry; + auto i = FindIterator(ext_id); + ExtensionEntry* entry = nullptr; if (i != entries_.end()) { - entry = i->second; + entry = i->get(); } else { entry = new ExtensionEntry; - entries_.insert(std::make_pair(install_time, entry)); + entry->install_time = install_time; + + // Insert in reverse-chronological order to maintain the invariant. + auto unique_entry = base::WrapUnique(entry); + auto location = + std::upper_bound(entries_.begin(), entries_.end(), unique_entry, + [](const std::unique_ptr<ExtensionEntry>& a, + const std::unique_ptr<ExtensionEntry>& b) { + return a->install_time > b->install_time; + }); + entries_.insert(location, std::move(unique_entry)); } entry->id = ext_id; @@ -147,14 +155,13 @@ void ContentSettingsStore::UnregisterExtension( bool notify_incognito = false; { base::AutoLock lock(lock_); - ExtensionEntryMap::iterator i = FindEntry(ext_id); + auto i = FindIterator(ext_id); if (i == entries_.end()) return; - notify = !i->second->settings.empty(); - notify_incognito = !i->second->incognito_persistent_settings.empty() || - !i->second->incognito_session_only_settings.empty(); + notify = !(*i)->settings.empty(); + notify_incognito = !(*i)->incognito_persistent_settings.empty() || + !(*i)->incognito_session_only_settings.empty(); - delete i->second; entries_.erase(i); } if (notify) @@ -169,14 +176,15 @@ void ContentSettingsStore::SetExtensionState( bool notify_incognito = false; { base::AutoLock lock(lock_); - ExtensionEntryMap::const_iterator i = FindEntry(ext_id); - if (i == entries_.end()) + ExtensionEntry* entry = FindEntry(ext_id); + if (!entry) return; - notify = !i->second->settings.empty(); - notify_incognito = !i->second->incognito_persistent_settings.empty() || - !i->second->incognito_session_only_settings.empty(); - i->second->enabled = is_enabled; + notify = !entry->settings.empty(); + notify_incognito = !entry->incognito_persistent_settings.empty() || + !entry->incognito_session_only_settings.empty(); + + entry->enabled = is_enabled; } if (notify) NotifyOfContentSettingChanged(ext_id, false); @@ -187,46 +195,34 @@ void ContentSettingsStore::SetExtensionState( OriginIdentifierValueMap* ContentSettingsStore::GetValueMap( const std::string& ext_id, ExtensionPrefsScope scope) { - ExtensionEntryMap::const_iterator i = FindEntry(ext_id); - if (i != entries_.end()) { - switch (scope) { - case kExtensionPrefsScopeRegular: - return &(i->second->settings); - case kExtensionPrefsScopeRegularOnly: - // TODO(bauerb): Implement regular-only content settings. - NOTREACHED(); - return NULL; - case kExtensionPrefsScopeIncognitoPersistent: - return &(i->second->incognito_persistent_settings); - case kExtensionPrefsScopeIncognitoSessionOnly: - return &(i->second->incognito_session_only_settings); - } - } - return NULL; + const OriginIdentifierValueMap* result = + static_cast<const ContentSettingsStore*>(this)->GetValueMap(ext_id, + scope); + return const_cast<OriginIdentifierValueMap*>(result); } const OriginIdentifierValueMap* ContentSettingsStore::GetValueMap( const std::string& ext_id, ExtensionPrefsScope scope) const { - ExtensionEntryMap::const_iterator i = FindEntry(ext_id); - if (i == entries_.end()) - return NULL; + ExtensionEntry* entry = FindEntry(ext_id); + if (!entry) + return nullptr; switch (scope) { case kExtensionPrefsScopeRegular: - return &(i->second->settings); + return &(entry->settings); case kExtensionPrefsScopeRegularOnly: // TODO(bauerb): Implement regular-only content settings. NOTREACHED(); - return NULL; + return nullptr; case kExtensionPrefsScopeIncognitoPersistent: - return &(i->second->incognito_persistent_settings); + return &(entry->incognito_persistent_settings); case kExtensionPrefsScopeIncognitoSessionOnly: - return &(i->second->incognito_session_only_settings); + return &(entry->incognito_session_only_settings); } NOTREACHED(); - return NULL; + return nullptr; } void ContentSettingsStore::ClearContentSettingsForExtension( @@ -375,24 +371,22 @@ bool ContentSettingsStore::OnCorrectThread() { BrowserThread::CurrentlyOn(BrowserThread::UI); } -ContentSettingsStore::ExtensionEntryMap::iterator -ContentSettingsStore::FindEntry(const std::string& ext_id) { - ExtensionEntryMap::iterator i; - for (i = entries_.begin(); i != entries_.end(); ++i) { - if (i->second->id == ext_id) - return i; - } - return entries_.end(); +ContentSettingsStore::ExtensionEntry* ContentSettingsStore::FindEntry( + const std::string& ext_id) const { + auto iter = + std::find_if(entries_.begin(), entries_.end(), + [ext_id](const std::unique_ptr<ExtensionEntry>& entry) { + return entry->id == ext_id; + }); + return iter == entries_.end() ? nullptr : iter->get(); } -ContentSettingsStore::ExtensionEntryMap::const_iterator -ContentSettingsStore::FindEntry(const std::string& ext_id) const { - ExtensionEntryMap::const_iterator i; - for (i = entries_.begin(); i != entries_.end(); ++i) { - if (i->second->id == ext_id) - return i; - } - return entries_.end(); +ContentSettingsStore::ExtensionEntries::iterator +ContentSettingsStore::FindIterator(const std::string& ext_id) { + return std::find_if(entries_.begin(), entries_.end(), + [ext_id](const std::unique_ptr<ExtensionEntry>& entry) { + return entry->id == ext_id; + }); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h index f0f9e39bee2..0567613a172 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h @@ -6,7 +6,9 @@ #define CHROME_BROWSER_EXTENSIONS_API_CONTENT_SETTINGS_CONTENT_SETTINGS_STORE_H_ #include <map> +#include <memory> #include <string> +#include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" @@ -112,7 +114,9 @@ class ContentSettingsStore struct ExtensionEntry; - typedef std::multimap<base::Time, ExtensionEntry*> ExtensionEntryMap; + // A list of the entries, maintained in reverse-chronological order (most- + // recently installed items first) to facilitate search. + using ExtensionEntries = std::vector<std::unique_ptr<ExtensionEntry>>; virtual ~ContentSettingsStore(); @@ -129,10 +133,11 @@ class ContentSettingsStore bool OnCorrectThread(); - ExtensionEntryMap::iterator FindEntry(const std::string& ext_id); - ExtensionEntryMap::const_iterator FindEntry(const std::string& ext_id) const; + ExtensionEntry* FindEntry(const std::string& ext_id) const; + ExtensionEntries::iterator FindIterator(const std::string& ext_id); - ExtensionEntryMap entries_; + // The entries. + ExtensionEntries entries_; base::ObserverList<Observer, false> observers_; diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc index 549dd0e6551..3eb2efb08a7 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc @@ -146,7 +146,10 @@ void CookiesEventRouter::CookieChanged( // Report an inserted cookie as an "explicit" change cause. All other causes // only make sense for deletions. case net::CookieStore::ChangeCause::INSERTED: - case net::CookieStore::ChangeCause::EXPLICIT: + case net::CookieStore::ChangeCause::EXPLICIT_DELETE: + case net::CookieStore::ChangeCause::EXPLICIT_DUPLICATE_IN_BACKING_STORE: + case net::CookieStore::ChangeCause::EXPLICIT_DONT_RECORD: + case net::CookieStore::ChangeCause::EXPLICIT_LAST_ENTRY: cause = keys::kExplicitChangeCause; break; diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h index 08947411cd9..8d3b2d516b6 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h @@ -21,7 +21,6 @@ class Browser; class Profile; namespace base { -class DictionaryValue; class ListValue; } diff --git a/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h b/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h index 8a20cf8fa2a..846725adfa2 100644 --- a/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h +++ b/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h @@ -16,13 +16,8 @@ #include "chrome/common/extensions/api/dashboard_private.h" #include "extensions/browser/extension_function.h" -class GURL; class SkBitmap; -namespace chrome { -class BitmapFetcher; -} // namespace chrome - namespace extensions { class Extension; diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc index 6242e561ef4..88d7f073bde 100644 --- a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc +++ b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc @@ -341,13 +341,23 @@ ExtensionDevToolsClientHost::ExtensionDevToolsClientHost( // Attach to debugger and tell it we are ready. agent_host_->AttachClient(this); - if (!base::CommandLine::ForCurrentProcess()->HasSwitch( + if (base::CommandLine::ForCurrentProcess()->HasSwitch( ::switches::kSilentDebuggerExtensionAPI)) { - infobar_ = ExtensionDevToolsInfoBar::Create( - extension_id, extension_name, this, - base::Bind(&ExtensionDevToolsClientHost::InfoBarDismissed, - base::Unretained(this))); + return; } + + // We allow policy-installed extensions to circumvent the normal + // infobar warning. See crbug.com/693621. + const Extension* extension = + ExtensionRegistry::Get(profile)->enabled_extensions().GetByID( + extension_id); + if (extension && Manifest::IsPolicyLocation(extension->location())) + return; + + infobar_ = ExtensionDevToolsInfoBar::Create( + extension_id, extension_name, this, + base::Bind(&ExtensionDevToolsClientHost::InfoBarDismissed, + base::Unretained(this))); } ExtensionDevToolsClientHost::~ExtensionDevToolsClientHost() { @@ -432,7 +442,7 @@ void ExtensionDevToolsClientHost::DispatchProtocolMessage( return; std::unique_ptr<base::Value> result = base::JSONReader::Read(message); - if (!result || !result->IsType(base::Value::TYPE_DICTIONARY)) + if (!result || !result->IsType(base::Value::Type::DICTIONARY)) return; base::DictionaryValue* dictionary = static_cast<base::DictionaryValue*>(result.get()); diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_api.h b/chromium/chrome/browser/extensions/api/debugger/debugger_api.h index c9e7ef0cd39..8b6a9c4c1bc 100644 --- a/chromium/chrome/browser/extensions/api/debugger/debugger_api.h +++ b/chromium/chrome/browser/extensions/api/debugger/debugger_api.h @@ -23,10 +23,6 @@ namespace base { class DictionaryValue; } -namespace content { -class WebContents; -} - namespace extensions { class ExtensionDevToolsClientHost; diff --git a/chromium/chrome/browser/extensions/api/declarative_content/content_predicate_evaluator.h b/chromium/chrome/browser/extensions/api/declarative_content/content_predicate_evaluator.h index 1d8756a7fdc..283d41826b9 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/content_predicate_evaluator.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/content_predicate_evaluator.h @@ -20,8 +20,6 @@ class WebContents; namespace extensions { -class Extension; - // Creates and manages instances of an associated ContentPredicate subclass and // tracks the url and browser context state required to evaluate the predicates. // diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc index d4934900be0..484fd898bbc 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc @@ -522,8 +522,17 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, EXPECT_TRUE(incognito_page_action->GetIsVisible(incognito_tab_id)); } +// Frequently times out on ChromiumOS debug builders: https://crbug.com/512431. +#if defined(OS_CHROMEOS) && !defined(NDEBUG) +#define MAYBE_PRE_RulesPersistence DISABLED_PRE_RulesPersistence +#define MAYBE_RulesPersistence DISABLED_RulesPersistence +#else +#define MAYBE_PRE_RulesPersistence PRE_RulesPersistence +#define MAYBE_RulesPersistence RulesPersistence +#endif + // Sets up rules matching http://test1/ in a normal and incognito browser. -IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, PRE_RulesPersistence) { +IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, MAYBE_PRE_RulesPersistence) { ExtensionTestMessageListener ready("ready", false); ExtensionTestMessageListener ready_split("ready (split)", false); // An on-disk extension is required so that it can be reloaded later in the @@ -540,7 +549,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, PRE_RulesPersistence) { // Reloads the extension from PRE_RulesPersistence and checks that the rules // continue to work as expected after being persisted and reloaded. -IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, RulesPersistence) { +IN_PROC_BROWSER_TEST_F(DeclarativeContentApiTest, MAYBE_RulesPersistence) { ExtensionTestMessageListener ready("second run ready", false); ExtensionTestMessageListener ready_split("second run ready (split)", false); ASSERT_TRUE(ready.WaitUntilSatisfied()); diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.cc index 4494dce1dbe..e27faa05ac2 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.cc @@ -40,7 +40,7 @@ content::MockRenderProcessHost* DeclarativeContentConditionTrackerTest::GetMockRenderProcessHost( content::WebContents* contents) { return static_cast<content::MockRenderProcessHost*>( - contents->GetRenderViewHost()->GetProcess()); + contents->GetMainFrame()->GetProcess()); } const void* DeclarativeContentConditionTrackerTest::GeneratePredicateGroupID() { diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker_unittest.cc index 5b66eb099b9..d183f57760a 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker_unittest.cc @@ -92,8 +92,8 @@ class DeclarativeContentCssConditionTrackerTest void SendOnWatchedPageChangeMessage( content::WebContents* tab, const std::vector<std::string>& selectors) { - ExtensionHostMsg_OnWatchedPageChange page_change(tab->GetRoutingID(), - selectors); + ExtensionHostMsg_OnWatchedPageChange page_change( + tab->GetRenderViewHost()->GetRoutingID(), selectors); EXPECT_TRUE(GetMockRenderProcessHost(tab)->OnMessageReceived(page_change)); } diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc index e6f28293e37..3d120986991 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc @@ -188,8 +188,14 @@ IN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, MAYBE_ChooseDesktopMedia) { {false, true, false, false, content::DesktopMediaID()}, // tabOnly() {false, false, true, false, content::DesktopMediaID()}, - // audioShare() - {true, true, true, true, content::DesktopMediaID()}, + // audioShareNoApproval() + {true, true, true, true, + content::DesktopMediaID(content::DesktopMediaID::TYPE_WEB_CONTENTS, 123, + false)}, + // audioShareApproval() + {true, true, true, true, + content::DesktopMediaID(content::DesktopMediaID::TYPE_WEB_CONTENTS, 123, + true)}, // chooseMediaAndGetStream() {true, true, false, false, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc index da43435a1b9..a92d060ea89 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc @@ -240,7 +240,10 @@ void DesktopCaptureChooseDesktopMediaFunctionBase::OnPickerDialogResults( extension()->name()); } - SetResult(base::MakeUnique<base::StringValue>(result)); + api::desktop_capture::ChooseDesktopMedia::Results::Options options; + options.can_request_audio_track = source.audio_share; + results_ = api::desktop_capture::ChooseDesktopMedia::Results::Create(result, + options); SendResponse(true); } diff --git a/chromium/chrome/browser/extensions/api/developer_private/OWNERS b/chromium/chrome/browser/extensions/api/developer_private/OWNERS index 7a2454834cb..aad0b9203df 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/OWNERS +++ b/chromium/chrome/browser/extensions/api/developer_private/OWNERS @@ -1,2 +1 @@ -dvh@chromium.org -grv@chromium.org +rdevlin.cronin@chromium.org diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc index 02cf2f17dff..49392c4e416 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc @@ -164,9 +164,12 @@ std::unique_ptr<developer::ProfileInfo> CreateProfileInfo(Profile* profile) { std::unique_ptr<developer::ProfileInfo> info(new developer::ProfileInfo()); info->is_supervised = profile->IsSupervised(); PrefService* prefs = profile->GetPrefs(); + const PrefService::Preference* pref = + prefs->FindPreference(prefs::kExtensionsUIDeveloperMode); info->is_incognito_available = IncognitoModePrefs::GetAvailability(prefs) != IncognitoModePrefs::DISABLED; + info->is_developer_mode_controlled_by_policy = pref->IsManaged(); info->in_developer_mode = !info->is_supervised && prefs->GetBoolean(prefs::kExtensionsUIDeveloperMode); diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h index ecc6b05ddd3..607e3029d07 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h +++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h @@ -42,14 +42,10 @@ class EventRouter; class ExtensionError; class ExtensionInfoGenerator; class ExtensionRegistry; -class ExtensionSystem; -class ManagementPolicy; class ProcessManager; -class RequirementsChecker; namespace api { -class EntryPicker; class EntryPickerClient; } // namespace api diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc index 5961e214069..a03451c3f1f 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc @@ -25,6 +25,13 @@ #include "chrome/common/pref_names.h" #include "chrome/test/base/test_browser_window.h" #include "components/crx_file/id_util.h" +#include "components/policy/core/browser/browser_policy_connector.h" +#include "components/policy/core/common/mock_configuration_policy_provider.h" +#include "components/policy/core/common/policy_map.h" +#include "components/policy/core/common/policy_service_impl.h" +#include "components/policy/core/common/policy_types.h" +#include "components/policy/policy_constants.h" +#include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/web_contents_tester.h" #include "extensions/browser/event_router_factory.h" #include "extensions/browser/extension_error_test_util.h" @@ -40,6 +47,9 @@ #include "extensions/common/test_util.h" #include "extensions/common/value_builder.h" +using testing::Return; +using testing::_; + namespace extensions { namespace { @@ -95,6 +105,18 @@ class DeveloperPrivateApiUnitTest : public ExtensionServiceTestBase { api::developer_private::PackStatus expected_status, int expected_flags); + // Execute the updateProfileConfiguration API call with a specified + // dev_mode. This is done from the webui when the user checks the + // "Developer Mode" checkbox. + void UpdateProfileConfigurationDevMode(bool dev_mode); + + // Execute the getProfileConfiguration API and parse its result into a + // ProfileInfo structure for further verification in the calling test. + // Will reset the profile_info unique_ptr. + // Uses ASSERT_* inside - callers should use ASSERT_NO_FATAL_FAILURE. + void GetProfileConfiguration( + std::unique_ptr<api::developer_private::ProfileInfo>* profile_info); + Browser* browser() { return browser_.get(); } private: @@ -107,6 +129,7 @@ class DeveloperPrivateApiUnitTest : public ExtensionServiceTestBase { std::unique_ptr<Browser> browser_; std::vector<std::unique_ptr<TestExtensionDir>> test_extension_dirs_; + policy::MockConfigurationPolicyProvider mock_policy_provider_; DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateApiUnitTest); }; @@ -242,9 +265,43 @@ testing::AssertionResult DeveloperPrivateApiUnitTest::TestPackExtensionFunction( return testing::AssertionSuccess(); } +void DeveloperPrivateApiUnitTest::UpdateProfileConfigurationDevMode( + bool dev_mode) { + scoped_refptr<UIThreadExtensionFunction> function( + new api::DeveloperPrivateUpdateProfileConfigurationFunction()); + std::unique_ptr<base::ListValue> args = + ListBuilder() + .Append(DictionaryBuilder() + .SetBoolean("inDeveloperMode", dev_mode) + .Build()) + .Build(); + EXPECT_TRUE(RunFunction(function, *args)) << function->GetError(); +} + +void DeveloperPrivateApiUnitTest::GetProfileConfiguration( + std::unique_ptr<api::developer_private::ProfileInfo>* profile_info) { + scoped_refptr<UIThreadExtensionFunction> function( + new api::DeveloperPrivateGetProfileConfigurationFunction()); + base::ListValue args; + EXPECT_TRUE(RunFunction(function, args)) << function->GetError(); + + ASSERT_TRUE(function->GetResultList()); + ASSERT_EQ(1u, function->GetResultList()->GetSize()); + const base::Value* response_value = nullptr; + function->GetResultList()->Get(0u, &response_value); + *profile_info = + api::developer_private::ProfileInfo::FromValue(*response_value); +} + void DeveloperPrivateApiUnitTest::SetUp() { ExtensionServiceTestBase::SetUp(); - InitializeEmptyExtensionService(); + + // By not specifying a pref_file filepath, we get a + // sync_preferences::TestingPrefServiceSyncable + // - see BuildTestingProfile in extension_service_test_base.cc. + ExtensionServiceInitParams init_params = CreateDefaultInitParams(); + init_params.pref_file.clear(); + InitializeExtensionService(init_params); browser_window_.reset(new TestBrowserWindow()); Browser::CreateParams params(profile()); @@ -576,4 +633,38 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateDeleteExtensionErrors) { EXPECT_TRUE(error_console->GetErrorsForExtension(extension->id()).empty()); } +// Test developerPrivate.updateProfileConfiguration: Try to turn on devMode +// when DeveloperToolsDisabled policy is active. +TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateDevModeDisabledPolicy) { + testing_pref_service()->SetManagedPref(prefs::kExtensionsUIDeveloperMode, + new base::FundamentalValue(false)); + + UpdateProfileConfigurationDevMode(true); + + EXPECT_FALSE( + profile()->GetPrefs()->GetBoolean(prefs::kExtensionsUIDeveloperMode)); + + std::unique_ptr<api::developer_private::ProfileInfo> profile_info; + ASSERT_NO_FATAL_FAILURE(GetProfileConfiguration(&profile_info)); + EXPECT_FALSE(profile_info->in_developer_mode); + EXPECT_TRUE(profile_info->is_developer_mode_controlled_by_policy); +} + +// Test developerPrivate.updateProfileConfiguration: Try to turn on devMode +// (without DeveloperToolsDisabled policy). +TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateDevMode) { + EXPECT_FALSE( + profile()->GetPrefs()->GetBoolean(prefs::kExtensionsUIDeveloperMode)); + + UpdateProfileConfigurationDevMode(true); + + EXPECT_TRUE( + profile()->GetPrefs()->GetBoolean(prefs::kExtensionsUIDeveloperMode)); + + std::unique_ptr<api::developer_private::ProfileInfo> profile_info; + ASSERT_NO_FATAL_FAILURE(GetProfileConfiguration(&profile_info)); + EXPECT_TRUE(profile_info->in_developer_mode); + EXPECT_FALSE(profile_info->is_developer_mode_controlled_by_policy); +} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/dial/OWNERS b/chromium/chrome/browser/extensions/api/dial/OWNERS index 68dd516cf4a..8224bbf7e83 100644 --- a/chromium/chrome/browser/extensions/api/dial/OWNERS +++ b/chromium/chrome/browser/extensions/api/dial/OWNERS @@ -1,3 +1,3 @@ mfoltz@chromium.org imcheng@chromium.org - +wez@chromium.org diff --git a/chromium/chrome/browser/extensions/api/dial/device_description_fetcher.cc b/chromium/chrome/browser/extensions/api/dial/device_description_fetcher.cc new file mode 100644 index 00000000000..654fc3355c7 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/dial/device_description_fetcher.cc @@ -0,0 +1,150 @@ +// Copyright (c) 2017 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 "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "chrome/browser/extensions/api/dial/device_description_fetcher.h" +#include "chrome/browser/extensions/api/dial/dial_device_data.h" +#include "chrome/browser/profiles/profile.h" +#include "content/public/browser/browser_thread.h" +#include "net/base/load_flags.h" +#include "net/http/http_response_headers.h" +#include "net/http/http_status_code.h" +#include "net/http/http_util.h" +#include "net/url_request/url_fetcher.h" + +using content::BrowserThread; + +constexpr char kApplicationUrlHeaderName[] = "Application-URL"; +constexpr int kMaxRetries = 3; +// DIAL devices are unlikely to expose uPnP functions other than DIAL, so 256kb +// should be more than sufficient. +constexpr int kMaxDescriptionSizeBytes = 262144; + +namespace extensions { +namespace api { +namespace dial { + +DeviceDescriptionFetcher::DeviceDescriptionFetcher( + const GURL& device_description_url, + Profile* profile, + base::OnceCallback<void(const DialDeviceDescriptionData&)> success_cb, + base::OnceCallback<void(const std::string&)> error_cb) + : device_description_url_(device_description_url), + profile_(profile), + success_cb_(std::move(success_cb)), + error_cb_(std::move(error_cb)) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(profile_); + DCHECK(device_description_url_.is_valid()); +} + +DeviceDescriptionFetcher::~DeviceDescriptionFetcher() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); +} + +void DeviceDescriptionFetcher::Start() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(!fetcher_); + + // DIAL returns device descriptions via GET request. + fetcher_ = + net::URLFetcher::Create(kURLFetcherIDForTest, device_description_url_, + net::URLFetcher::GET, this); + + // net::LOAD_BYPASS_PROXY: Proxies almost certainly hurt more cases than they + // help. + // net::LOAD_DISABLE_CACHE: The request should not touch the cache. + // net::LOAD_DO_NOT_{SAVE,SEND}_COOKIES: The request should not touch cookies. + // net::LOAD_DO_NOT_SEND_AUTH_DATA: The request should not send auth data. + fetcher_->SetLoadFlags(net::LOAD_BYPASS_PROXY | net::LOAD_DISABLE_CACHE | + net::LOAD_DO_NOT_SAVE_COOKIES | + net::LOAD_DO_NOT_SEND_COOKIES | + net::LOAD_DO_NOT_SEND_AUTH_DATA); + + // Section 5.4 of the DIAL spec prohibits redirects. + fetcher_->SetStopOnRedirect(true); + + // Allow the fetcher to retry on 5XX responses and ERR_NETWORK_CHANGED. + fetcher_->SetMaxRetriesOn5xx(kMaxRetries); + fetcher_->SetAutomaticallyRetryOnNetworkChanges(kMaxRetries); + + fetcher_->SetRequestContext(profile_->GetRequestContext()); + fetcher_->Start(); +} + +void DeviceDescriptionFetcher::OnURLFetchComplete( + const net::URLFetcher* source) { + DCHECK_EQ(fetcher_.get(), source); + + if (source->GetResponseCode() != net::HTTP_OK) { + ReportError( + base::StringPrintf("HTTP %d: Unable to fetch device description", + source->GetResponseCode())); + return; + } + + const net::HttpResponseHeaders* headers = source->GetResponseHeaders(); + + // NOTE: The uPnP spec requires devices to set a Content-Type: header of + // text/xml; charset="utf-8" (sec 2.11). However Chromecast (and possibly + // other devices) do not comply, so specifically not checking this header. + std::string app_url_header; + if (!headers->GetNormalizedHeader(kApplicationUrlHeaderName, + &app_url_header) || + app_url_header.empty()) { + ReportError("Missing or empty Application-URL:"); + return; + } + + // Section 5.4 of the DIAL spec implies that the Application URL should not + // have path, query or fragment...unsure if that can be enforced. + GURL app_url(app_url_header); + if (!app_url.is_valid() || !app_url.SchemeIs("http") || + !app_url.HostIsIPAddress() || + app_url.host() != device_description_url_.host()) { + ReportError(base::StringPrintf("Invalid Application-URL: %s", + app_url_header.c_str())); + return; + } + + if (source->GetReceivedResponseContentLength() > kMaxDescriptionSizeBytes) { + ReportError("Response too large"); + return; + } + + std::string device_description; + if (!source->GetResponseAsString(&device_description) || + device_description.empty()) { + ReportError("Missing or empty response"); + return; + } + + if (!base::IsStringUTF8(device_description)) { + ReportError("Invalid response encoding"); + return; + } + + std::move(success_cb_) + .Run(DialDeviceDescriptionData(std::move(device_description), app_url)); +} + +void DeviceDescriptionFetcher::OnURLFetchDownloadProgress( + const net::URLFetcher* source, + int64_t current, + int64_t total, + int64_t current_network_bytes) {} + +void DeviceDescriptionFetcher::OnURLFetchUploadProgress( + const net::URLFetcher* source, + int64_t current, + int64_t total) {} + +void DeviceDescriptionFetcher::ReportError(const std::string& message) { + std::move(error_cb_).Run(message); +} + +} // namespace dial +} // namespace api +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/dial/device_description_fetcher.h b/chromium/chrome/browser/extensions/api/dial/device_description_fetcher.h new file mode 100644 index 00000000000..309dc88a600 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/dial/device_description_fetcher.h @@ -0,0 +1,73 @@ +// Copyright (c) 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_EXTENSIONS_API_DIAL_DEVICE_DESCRIPTION_FETCHER_H_ +#define CHROME_BROWSER_EXTENSIONS_API_DIAL_DEVICE_DESCRIPTION_FETCHER_H_ + +#include <memory> +#include <string> + +#include "base/callback.h" +#include "net/url_request/url_fetcher_delegate.h" +#include "url/gurl.h" + +class Profile; + +namespace net { +class URLFetcher; +} + +namespace extensions { +namespace api { +namespace dial { + +struct DialDeviceDescriptionData; + +// Used to make a single HTTP GET request with |device_description_url| to fetch +// a uPnP device description from a DIAL device. If successful, |success_cb| is +// invoked with the result; otherwise, |error_cb| is invoked with an error +// reason. This class is not thread safe and must be used on the UI thread. +class DeviceDescriptionFetcher : public net::URLFetcherDelegate { + public: + // Used to identify the net::URLFetcher instance for tests. + static constexpr int kURLFetcherIDForTest = 1; + + // |profile| is unowned; the caller must ensure that this object does not + // outlive it. + DeviceDescriptionFetcher( + const GURL& device_description_url, + Profile* profile, + base::OnceCallback<void(const DialDeviceDescriptionData&)> success_cb, + base::OnceCallback<void(const std::string&)> error_cb); + + ~DeviceDescriptionFetcher() override; + + void Start(); + + private: + // net::URLFetcherDelegate implementation. + void OnURLFetchComplete(const net::URLFetcher* source) override; + void OnURLFetchDownloadProgress(const net::URLFetcher* source, + int64_t current, + int64_t total, + int64_t current_network_bytes) override; + void OnURLFetchUploadProgress(const net::URLFetcher* source, + int64_t current, + int64_t total) override; + + // Runs |error_cb_| with |message| and clears it. + void ReportError(const std::string& message); + + const GURL device_description_url_; + Profile* const profile_; + base::OnceCallback<void(const DialDeviceDescriptionData&)> success_cb_; + base::OnceCallback<void(const std::string&)> error_cb_; + std::unique_ptr<net::URLFetcher> fetcher_; +}; + +} // namespace dial +} // namespace api +} // namespace extensions + +#endif // CHROME_BROWSER_EXTENSIONS_API_DIAL_DEVICE_DESCRIPTION_FETCHER_H_ diff --git a/chromium/chrome/browser/extensions/api/dial/device_description_fetcher_unittest.cc b/chromium/chrome/browser/extensions/api/dial/device_description_fetcher_unittest.cc new file mode 100644 index 00000000000..92b72c73a51 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/dial/device_description_fetcher_unittest.cc @@ -0,0 +1,178 @@ +// Copyright (c) 2016 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 <memory> +#include <string> + +#include "base/callback.h" +#include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "base/memory/ref_counted.h" +#include "chrome/browser/extensions/api/dial/device_description_fetcher.h" +#include "chrome/browser/extensions/api/dial/dial_device_data.h" +#include "chrome/test/base/testing_profile.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "net/http/http_response_headers.h" +#include "net/http/http_status_code.h" +#include "net/url_request/test_url_fetcher_factory.h" +#include "net/url_request/url_fetcher.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +namespace extensions { +namespace api { +namespace dial { + +class DeviceDescriptionFetcherTest : public testing::Test { + public: + DeviceDescriptionFetcherTest() : url_("http://127.0.0.1/description.xml") {} + + void TearDown() override { + EXPECT_FALSE(error_cb_); + EXPECT_FALSE(success_cb_); + } + + void ExpectSuccess(const GURL& expected_app_url, + const std::string& expected_description) { + success_cb_ = base::BindOnce(&DeviceDescriptionFetcherTest::OnSuccess, + base::Unretained(this), expected_app_url, + expected_description); + } + + void ExpectError(const std::string& expected_message) { + error_cb_ = base::BindOnce(&DeviceDescriptionFetcherTest::OnError, + base::Unretained(this), expected_message); + } + + net::TestURLFetcher* StartRequest() { + fetcher_ = base::MakeUnique<DeviceDescriptionFetcher>( + url_, &profile_, std::move(success_cb_), std::move(error_cb_)); + fetcher_->Start(); + return factory_.GetFetcherByID( + DeviceDescriptionFetcher::kURLFetcherIDForTest); + } + + protected: + const content::TestBrowserThreadBundle thread_bundle_; + TestingProfile profile_; + const net::TestURLFetcherFactory factory_; + const GURL url_; + base::OnceCallback<void(const DialDeviceDescriptionData&)> success_cb_; + base::OnceCallback<void(const std::string&)> error_cb_; + std::unique_ptr<DeviceDescriptionFetcher> fetcher_; + + private: + void OnSuccess(const GURL& expected_app_url, + const std::string& expected_description, + const DialDeviceDescriptionData& description) { + EXPECT_EQ(expected_app_url, description.app_url); + EXPECT_EQ(expected_description, description.device_description); + } + + void OnError(const std::string& expected_message, + const std::string& message) { + EXPECT_TRUE(message.find(expected_message) == 0); + } + + DISALLOW_COPY_AND_ASSIGN(DeviceDescriptionFetcherTest); +}; + +TEST_F(DeviceDescriptionFetcherTest, FetchSuccessful) { + ExpectSuccess(GURL("http://127.0.0.1/apps"), "<xml>description</xml>"); + net::TestURLFetcher* test_fetcher = StartRequest(); + + test_fetcher->set_response_code(net::HTTP_OK); + scoped_refptr<net::HttpResponseHeaders> headers = + new net::HttpResponseHeaders(""); + headers->AddHeader("Application-URL: http://127.0.0.1/apps"); + test_fetcher->set_response_headers(headers); + test_fetcher->SetResponseString("<xml>description</xml>"); + test_fetcher->delegate()->OnURLFetchComplete(test_fetcher); +} + +TEST_F(DeviceDescriptionFetcherTest, FetchFailsOnMissingDescription) { + ExpectError("HTTP 404:"); + net::TestURLFetcher* test_fetcher = StartRequest(); + + test_fetcher->set_response_code(net::HTTP_NOT_FOUND); + test_fetcher->delegate()->OnURLFetchComplete(test_fetcher); +} + +TEST_F(DeviceDescriptionFetcherTest, FetchFailsOnMissingAppUrl) { + ExpectError("Missing or empty Application-URL:"); + net::TestURLFetcher* test_fetcher = StartRequest(); + + test_fetcher->set_response_code(net::HTTP_OK); + scoped_refptr<net::HttpResponseHeaders> headers = + new net::HttpResponseHeaders(""); + test_fetcher->set_response_headers(headers); + test_fetcher->delegate()->OnURLFetchComplete(test_fetcher); +} + +TEST_F(DeviceDescriptionFetcherTest, FetchFailsOnEmptyAppUrl) { + ExpectError("Missing or empty Application-URL:"); + net::TestURLFetcher* test_fetcher = StartRequest(); + + test_fetcher->set_response_code(net::HTTP_OK); + scoped_refptr<net::HttpResponseHeaders> headers = + new net::HttpResponseHeaders(""); + headers->AddHeader("Application-URL:"); + test_fetcher->set_response_headers(headers); + test_fetcher->delegate()->OnURLFetchComplete(test_fetcher); +} + +TEST_F(DeviceDescriptionFetcherTest, FetchFailsOnInvalidAppUrl) { + ExpectError("Invalid Application-URL:"); + net::TestURLFetcher* test_fetcher = StartRequest(); + + test_fetcher->set_response_code(net::HTTP_OK); + scoped_refptr<net::HttpResponseHeaders> headers = + new net::HttpResponseHeaders(""); + headers->AddHeader("Application-URL: http://www.example.com"); + test_fetcher->set_response_headers(headers); + test_fetcher->delegate()->OnURLFetchComplete(test_fetcher); +} + +TEST_F(DeviceDescriptionFetcherTest, FetchFailsOnEmptyDescription) { + ExpectError("Missing or empty response"); + net::TestURLFetcher* test_fetcher = StartRequest(); + + test_fetcher->set_response_code(net::HTTP_OK); + scoped_refptr<net::HttpResponseHeaders> headers = + new net::HttpResponseHeaders(""); + headers->AddHeader("Application-URL: http://127.0.0.1/apps"); + test_fetcher->set_response_headers(headers); + test_fetcher->SetResponseString(""); + test_fetcher->delegate()->OnURLFetchComplete(test_fetcher); +} + +TEST_F(DeviceDescriptionFetcherTest, FetchFailsOnBadDescription) { + ExpectError("Invalid response encoding"); + net::TestURLFetcher* test_fetcher = StartRequest(); + + test_fetcher->set_response_code(net::HTTP_OK); + scoped_refptr<net::HttpResponseHeaders> headers = + new net::HttpResponseHeaders(""); + headers->AddHeader("Application-URL: http://127.0.0.1/apps"); + test_fetcher->set_response_headers(headers); + test_fetcher->SetResponseString("\xfc\x9c\xbf\x80\xbf\x80"); + test_fetcher->delegate()->OnURLFetchComplete(test_fetcher); +} + +TEST_F(DeviceDescriptionFetcherTest, FetchFailsOnResponseTooLarge) { + ExpectError("Response too large"); + net::TestURLFetcher* test_fetcher = StartRequest(); + + test_fetcher->set_response_code(net::HTTP_OK); + scoped_refptr<net::HttpResponseHeaders> headers = + new net::HttpResponseHeaders(""); + headers->AddHeader("Application-URL: http://127.0.0.1/apps"); + test_fetcher->set_response_headers(headers); + test_fetcher->SetResponseString(std::string(262145, 'd')); + test_fetcher->delegate()->OnURLFetchComplete(test_fetcher); +} + +} // namespace dial +} // namespace api +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/dial/dial_api.cc b/chromium/chrome/browser/extensions/api/dial/dial_api.cc index 6f43b17aaf0..783992bf2be 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_api.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_api.cc @@ -8,17 +8,26 @@ #include <utility> #include <vector> +#include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/time/time.h" +#include "chrome/browser/extensions/api/dial/device_description_fetcher.h" #include "chrome/browser/extensions/api/dial/dial_api_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/dial.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_system.h" +#include "url/gurl.h" using base::TimeDelta; using content::BrowserThread; +using extensions::api::dial::DeviceDescriptionFetcher; +using extensions::api::dial::DialDeviceData; +using extensions::api::dial::DialDeviceDescriptionData; +using extensions::api::dial::DialRegistry; + +namespace extensions { namespace { @@ -33,16 +42,12 @@ const size_t kDialMaxDevices = 256; } // namespace -namespace extensions { - -namespace dial = api::dial; - DialAPI::DialAPI(Profile* profile) : RefcountedKeyedService( BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)), profile_(profile) { - EventRouter::Get(profile) - ->RegisterObserver(this, dial::OnDeviceList::kEventName); + EventRouter::Get(profile)->RegisterObserver( + this, api::dial::OnDeviceList::kEventName); } DialAPI::~DialAPI() {} @@ -50,10 +55,12 @@ DialAPI::~DialAPI() {} DialRegistry* DialAPI::dial_registry() { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!dial_registry_.get()) { - dial_registry_.reset(new DialRegistry(this, - TimeDelta::FromSeconds(kDialRefreshIntervalSecs), - TimeDelta::FromSeconds(kDialExpirationSecs), - kDialMaxDevices)); + dial_registry_.reset(new DialRegistry( + this, TimeDelta::FromSeconds(kDialRefreshIntervalSecs), + TimeDelta::FromSeconds(kDialExpirationSecs), kDialMaxDevices)); + if (test_device_data_) { + dial_registry_->AddDeviceForTest(*test_device_data_); + } } return dial_registry_.get(); } @@ -108,7 +115,7 @@ void DialAPI::SendEventOnUIThread(const DialRegistry::DeviceList& devices) { std::unique_ptr<base::ListValue> results = api::dial::OnDeviceList::Create(args); std::unique_ptr<Event> event(new Event(events::DIAL_ON_DEVICE_LIST, - dial::OnDeviceList::kEventName, + api::dial::OnDeviceList::kEventName, std::move(results))); EventRouter::Get(profile_)->BroadcastEvent(std::move(event)); } @@ -140,14 +147,21 @@ void DialAPI::SendErrorOnUIThread(const DialRegistry::DialErrorCode code) { std::unique_ptr<base::ListValue> results = api::dial::OnError::Create(dial_error); - std::unique_ptr<Event> event(new Event( - events::DIAL_ON_ERROR, dial::OnError::kEventName, std::move(results))); + std::unique_ptr<Event> event(new Event(events::DIAL_ON_ERROR, + api::dial::OnError::kEventName, + std::move(results))); EventRouter::Get(profile_)->BroadcastEvent(std::move(event)); } void DialAPI::ShutdownOnUIThread() {} -namespace api { +void DialAPI::SetDeviceForTest( + const api::dial::DialDeviceData& device_data, + const api::dial::DialDeviceDescriptionData& device_description) { + test_device_data_ = base::MakeUnique<DialDeviceData>(device_data); + test_device_description_ = + base::MakeUnique<DialDeviceDescriptionData>(device_description); +} DialDiscoverNowFunction::DialDiscoverNowFunction() : dial_(NULL), result_(false) { @@ -171,6 +185,79 @@ bool DialDiscoverNowFunction::Respond() { return true; } -} // namespace api +DialFetchDeviceDescriptionFunction::DialFetchDeviceDescriptionFunction() + : dial_(nullptr) {} + +DialFetchDeviceDescriptionFunction::~DialFetchDeviceDescriptionFunction() {} + +bool DialFetchDeviceDescriptionFunction::RunAsync() { + dial_ = DialAPIFactory::GetForBrowserContext(browser_context()).get(); + params_ = api::dial::FetchDeviceDescription::Params::Create(*args_); + EXTENSION_FUNCTION_VALIDATE(params_.get()); + + // DialRegistry lives on the IO thread. Hop on over there to get the URL to + // fetch. + BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, + base::Bind(&DialFetchDeviceDescriptionFunction:: + GetDeviceDescriptionUrlOnIOThread, + this, params_->device_label)); + return true; +} + +void DialFetchDeviceDescriptionFunction::GetDeviceDescriptionUrlOnIOThread( + const std::string& label) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + const GURL& device_description_url = + dial_->dial_registry()->GetDeviceDescriptionURL(label); + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::Bind(&DialFetchDeviceDescriptionFunction::MaybeStartFetch, this, + device_description_url)); +} + +void DialFetchDeviceDescriptionFunction::MaybeStartFetch(const GURL& url) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + if (url.is_empty()) { + SetError("Device not found"); + SendResponse(false); + return; + } + + if (dial_->test_device_data_ && dial_->test_device_description_ && + dial_->test_device_data_->device_description_url() == url) { + OnFetchComplete(*(dial_->test_device_description_)); + return; + } + + device_description_fetcher_ = base::MakeUnique<DeviceDescriptionFetcher>( + url, Profile::FromBrowserContext(browser_context()), + base::BindOnce(&DialFetchDeviceDescriptionFunction::OnFetchComplete, + this), + base::BindOnce(&DialFetchDeviceDescriptionFunction::OnFetchError, this)); + + device_description_fetcher_->Start(); +} + +void DialFetchDeviceDescriptionFunction::OnFetchComplete( + const api::dial::DialDeviceDescriptionData& result) { + // Destroy the DeviceDescriptionFetcher since it still contains a reference + // to |this| in its un-invoked callback. + device_description_fetcher_.reset(); + api::dial::DialDeviceDescription device_description; + device_description.device_label = params_->device_label; + device_description.app_url = result.app_url.spec(); + device_description.device_description = result.device_description; + SetResult(device_description.ToValue()); + SendResponse(true); +} + +void DialFetchDeviceDescriptionFunction::OnFetchError( + const std::string& message) { + // Destroy the DeviceDescriptionFetcher since it still contains a reference + // to |this| in its un-invoked callback. + device_description_fetcher_.reset(); + SetError(message); + SendResponse(false); +} } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/dial/dial_api.h b/chromium/chrome/browser/extensions/api/dial/dial_api.h index c9ba27a5081..1aba1c75a70 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_api.h +++ b/chromium/chrome/browser/extensions/api/dial/dial_api.h @@ -10,13 +10,20 @@ #include "base/macros.h" #include "chrome/browser/extensions/api/dial/dial_device_data.h" #include "chrome/browser/extensions/api/dial/dial_registry.h" +#include "chrome/common/extensions/api/dial.h" #include "components/keyed_service/core/refcounted_keyed_service.h" #include "extensions/browser/api/async_api_function.h" #include "extensions/browser/event_router.h" namespace extensions { -class DialRegistry; +namespace api { +namespace dial { +class DeviceDescriptionFetcher; +} // namespace dial +} // namespace api + +class DialFetchDeviceDescriptionFunction; // Dial API which is a ref-counted KeyedService that manages // the DIAL registry. It takes care of creating the registry on the IO thread @@ -26,24 +33,42 @@ class DialRegistry; // TODO(mfoltz): This should probably inherit from BrowserContextKeyedAPI // instead; ShutdownOnUIThread below is a no-op, which is the whole point of // RefcountedKeyedService. +// +// TODO(mfoltz): The threading model for this API needs to be rethought. At a +// minimum, DialRegistry should move to the UI thread to avoid extra thread hops +// here. This would also allow a straightforward GetDeviceList implementation +// (crbug.com/576817), cleanup some long-tail crashes (crbug.com/640011) that +// are likely due to lifetime issues, and simplify unit tests +// (crbug.com/661457). +// +// Also, DialRegistry should be an interface that can be mocked and injected for +// tests; this would allow us to remove code that injects test data into the +// real DialRegsitry. class DialAPI : public RefcountedKeyedService, public EventRouter::Observer, - public DialRegistry::Observer { + public api::dial::DialRegistry::Observer { public: explicit DialAPI(Profile* profile); // The DialRegistry for the API. This must always be used only from the IO // thread. - DialRegistry* dial_registry(); + api::dial::DialRegistry* dial_registry(); // Called by the DialRegistry on the IO thread so that the DialAPI dispatches // the event to listeners on the UI thread. - void SendEventOnUIThread(const DialRegistry::DeviceList& devices); - void SendErrorOnUIThread(const DialRegistry::DialErrorCode type); + void SendEventOnUIThread(const api::dial::DialRegistry::DeviceList& devices); + void SendErrorOnUIThread(const api::dial::DialRegistry::DialErrorCode type); + + // Sets test device data. + void SetDeviceForTest( + const api::dial::DialDeviceData& device_data, + const api::dial::DialDeviceDescriptionData& device_description); private: ~DialAPI() override; + friend class DialFetchDeviceDescriptionFunction; + // RefcountedKeyedService: void ShutdownOnUIThread() override; @@ -52,8 +77,9 @@ class DialAPI : public RefcountedKeyedService, void OnListenerRemoved(const EventListenerInfo& details) override; // DialRegistry::Observer: - void OnDialDeviceEvent(const DialRegistry::DeviceList& devices) override; - void OnDialError(DialRegistry::DialErrorCode type) override; + void OnDialDeviceEvent( + const api::dial::DialRegistry::DeviceList& devices) override; + void OnDialError(api::dial::DialRegistry::DialErrorCode type) override; // Methods to notify the DialRegistry on the correct thread of new/removed // listeners. @@ -63,13 +89,16 @@ class DialAPI : public RefcountedKeyedService, Profile* profile_; // Created lazily on first access on the IO thread. - std::unique_ptr<DialRegistry> dial_registry_; + std::unique_ptr<api::dial::DialRegistry> dial_registry_; + + // Device data for testing. + std::unique_ptr<api::dial::DialDeviceData> test_device_data_; + std::unique_ptr<api::dial::DialDeviceDescriptionData> + test_device_description_; DISALLOW_COPY_AND_ASSIGN(DialAPI); }; -namespace api { - // DiscoverNow function. This function needs a round-trip from the IO thread // because it needs to grab a pointer to the DIAL API in order to get a // reference to the DialRegistry while on the IO thread. Then, the result @@ -100,7 +129,33 @@ class DialDiscoverNowFunction : public AsyncApiFunction { DISALLOW_COPY_AND_ASSIGN(DialDiscoverNowFunction); }; -} // namespace api +class DialFetchDeviceDescriptionFunction : public AsyncExtensionFunction { + public: + DialFetchDeviceDescriptionFunction(); + + protected: + ~DialFetchDeviceDescriptionFunction() override; + + // AsyncExtensionFunction: + bool RunAsync() override; + + private: + DECLARE_EXTENSION_FUNCTION("dial.fetchDeviceDescription", + DIAL_FETCHDEVICEDESCRIPTION) + + void GetDeviceDescriptionUrlOnIOThread(const std::string& label); + void MaybeStartFetch(const GURL& url); + void OnFetchComplete(const api::dial::DialDeviceDescriptionData& result); + void OnFetchError(const std::string& result); + + std::unique_ptr<api::dial::FetchDeviceDescription::Params> params_; + std::unique_ptr<api::dial::DeviceDescriptionFetcher> + device_description_fetcher_; + + DialAPI* dial_; + + DISALLOW_COPY_AND_ASSIGN(DialFetchDeviceDescriptionFunction); +}; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/dial/dial_apitest.cc b/chromium/chrome/browser/extensions/api/dial/dial_apitest.cc index 73ef7ab600d..c3698c52b5a 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_apitest.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_apitest.cc @@ -15,10 +15,11 @@ #include "testing/gmock/include/gmock/gmock.h" #include "url/gurl.h" -using extensions::DialDeviceData; using extensions::Extension; - -namespace api = extensions::api; +using extensions::ResultCatcher; +using extensions::api::dial::DialDeviceData; +using extensions::api::dial::DialDeviceDescriptionData; +using extensions::api::dial::DialRegistry; namespace { @@ -52,9 +53,9 @@ IN_PROC_BROWSER_TEST_F(DialAPITest, MAYBE_DeviceListEvents) { extensions::DialAPIFactory::GetInstance()->GetForBrowserContext( profile()); ASSERT_TRUE(api.get()); - extensions::DialRegistry::DeviceList devices; + DialRegistry::DeviceList devices; - extensions::ResultCatcher catcher; + ResultCatcher catcher; DialDeviceData device1; device1.set_device_id("1"); @@ -96,13 +97,13 @@ IN_PROC_BROWSER_TEST_F(DialAPITest, DiscoveryNoListeners) { // Make sure this API is only accessible to whitelisted extensions. IN_PROC_BROWSER_TEST_F(DialAPITest, NonWhitelistedExtension) { - extensions::ResultCatcher catcher; + ResultCatcher catcher; catcher.RestrictToBrowserContext(browser()->profile()); ExtensionTestMessageListener listener("ready", true); - const extensions::Extension* extension = LoadExtensionWithFlags( - test_data_dir_.AppendASCII("dial/whitelist"), - ExtensionBrowserTest::kFlagIgnoreManifestWarnings); + const Extension* extension = + LoadExtensionWithFlags(test_data_dir_.AppendASCII("dial/whitelist"), + ExtensionBrowserTest::kFlagIgnoreManifestWarnings); // We should have a DIAL API not available warning. ASSERT_FALSE(extension->install_warnings().empty()); @@ -115,3 +116,22 @@ IN_PROC_BROWSER_TEST_F(DialAPITest, NonWhitelistedExtension) { IN_PROC_BROWSER_TEST_F(DialAPITest, OnError) { ASSERT_TRUE(RunExtensionSubtest("dial/experimental", "on_error.html")); } + +IN_PROC_BROWSER_TEST_F(DialAPITest, FetchDeviceDescription) { + scoped_refptr<extensions::DialAPI> api = + extensions::DialAPIFactory::GetInstance()->GetForBrowserContext( + profile()); + ASSERT_TRUE(api); + + DialDeviceData test_device("testDeviceId", + GURL("http://127.0.0.1/description.xml"), + base::Time::Now()); + test_device.set_label("testDevice"); + + DialDeviceDescriptionData test_description("<xml>testDescription</xml>", + GURL("http://127.0.0.1/apps")); + api->SetDeviceForTest(test_device, test_description); + + ASSERT_TRUE(RunExtensionSubtest("dial/experimental", + "fetch_device_description.html")); +} diff --git a/chromium/chrome/browser/extensions/api/dial/dial_device_data.cc b/chromium/chrome/browser/extensions/api/dial/dial_device_data.cc index 821f0553e90..1db2e5c38b5 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_device_data.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_device_data.cc @@ -7,6 +7,8 @@ #include "chrome/common/extensions/api/dial.h" namespace extensions { +namespace api { +namespace dial { DialDeviceData::DialDeviceData() : max_age_(-1), config_id_(-1) { } @@ -55,4 +57,11 @@ void DialDeviceData::FillDialDevice(api::dial::DialDevice* device) const { device->config_id.reset(new int(config_id_)); } +DialDeviceDescriptionData::DialDeviceDescriptionData( + const std::string& device_description, + const GURL& app_url) + : device_description(device_description), app_url(app_url) {} + +} // namespace dial +} // namespace api } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/dial/dial_device_data.h b/chromium/chrome/browser/extensions/api/dial/dial_device_data.h index bd9f561bbcf..4706885a465 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_device_data.h +++ b/chromium/chrome/browser/extensions/api/dial/dial_device_data.h @@ -13,12 +13,10 @@ #include "url/gurl.h" namespace extensions { - namespace api { namespace dial { + struct DialDevice; -} // namespace api -} // namespace dial // Dial device information that is used within the DialService and Registry on // the IO thread. It is updated as new information arrives and a list of @@ -94,6 +92,18 @@ class DialDeviceData { int config_id_; }; +struct DialDeviceDescriptionData { + public: + DialDeviceDescriptionData() = default; + DialDeviceDescriptionData(const std::string& device_description, + const GURL& app_url); + + std::string device_description; + GURL app_url; +}; + +} // namespace dial +} // namespace api } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_DIAL_DIAL_DEVICE_DATA_H_ diff --git a/chromium/chrome/browser/extensions/api/dial/dial_device_data_unittest.cc b/chromium/chrome/browser/extensions/api/dial/dial_device_data_unittest.cc index 4ccc4701405..fc079a37cd0 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_device_data_unittest.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_device_data_unittest.cc @@ -7,6 +7,8 @@ #include "testing/gtest/include/gtest/gtest.h" namespace extensions { +namespace api { +namespace dial { namespace { @@ -101,4 +103,6 @@ TEST(DialDeviceDataTest, TestIsDeviceDescriptionUrl) { DialDeviceData::IsDeviceDescriptionUrl(GURL("file://path/to/file"))); } +} // namespace dial +} // namespace api } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/dial/dial_registry.cc b/chromium/chrome/browser/extensions/api/dial/dial_registry.cc index f3cbe46ef07..752dbd69f9f 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_registry.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_registry.cc @@ -5,6 +5,7 @@ #include "chrome/browser/extensions/api/dial/dial_registry.h" #include <memory> +#include <utility> #include "base/memory/ptr_util.h" #include "base/stl_util.h" @@ -25,6 +26,8 @@ using content::BrowserThread; using net::NetworkChangeNotifier; namespace extensions { +namespace api { +namespace dial { DialRegistry::DialRegistry(Observer* dial_api, const base::TimeDelta& refresh_interval, @@ -82,6 +85,23 @@ void DialRegistry::OnListenerRemoved() { } } +GURL DialRegistry::GetDeviceDescriptionURL(const std::string& label) const { + const auto device_it = device_by_label_map_.find(label); + if (device_it != device_by_label_map_.end()) + return device_it->second->device_description_url(); + + return GURL(); +} + +void DialRegistry::AddDeviceForTest(const DialDeviceData& device_data) { + std::unique_ptr<DialDeviceData> test_data = + base::MakeUnique<DialDeviceData>(device_data); + device_by_label_map_.insert( + std::make_pair(device_data.label(), test_data.get())); + device_by_id_map_.insert( + std::make_pair(device_data.device_id(), std::move(test_data))); +} + bool DialRegistry::ReadyToDiscover() { if (num_listeners_ == 0) { dial_api_->OnDialError(DIAL_NO_LISTENERS); @@ -334,4 +354,6 @@ void DialRegistry::OnNetworkChanged( } } +} // namespace dial +} // namespace api } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/dial/dial_registry.h b/chromium/chrome/browser/extensions/api/dial/dial_registry.h index 784aa78aaad..e43d207bff8 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_registry.h +++ b/chromium/chrome/browser/extensions/api/dial/dial_registry.h @@ -23,6 +23,8 @@ #include "net/base/network_change_notifier.h" namespace extensions { +namespace api { +namespace dial { // Keeps track of devices that have responded to discovery requests and notifies // the observer with an updated, complete set of active devices. The registry's @@ -72,6 +74,15 @@ class DialRegistry : public DialService::Observer, // already active. bool DiscoverNow(); + // Returns the URL of the device description for the device identified by + // |label|, or an empty GURL if no such device exists. + GURL GetDeviceDescriptionURL(const std::string& label) const; + + // Adds a device directly to the registry as if it was discovered. For tests + // only. Note that if discovery is actually started, this device will be + // removed by PruneExpiredDevices(). + void AddDeviceForTest(const DialDeviceData& device_data); + protected: // Returns a new instance of the DIAL service. Overridden by tests. virtual std::unique_ptr<DialService> CreateDialService(); @@ -184,6 +195,8 @@ class DialRegistry : public DialService::Observer, DISALLOW_COPY_AND_ASSIGN(DialRegistry); }; +} // namespace dial +} // namespace api } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_DIAL_DIAL_REGISTRY_H_ diff --git a/chromium/chrome/browser/extensions/api/dial/dial_registry_unittest.cc b/chromium/chrome/browser/extensions/api/dial/dial_registry_unittest.cc index 8a28d0996d0..5c98b0ee5e0 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_registry_unittest.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_registry_unittest.cc @@ -22,6 +22,8 @@ using ::testing::Return; using ::testing::InSequence; namespace extensions { +namespace api { +namespace dial { class MockDialObserver : public DialRegistry::Observer { public: @@ -376,4 +378,6 @@ TEST_F(DialRegistryTest, TestNetworkEventConnectionRestored) { registry_->OnListenerRemoved(); } +} // namespace dial +} // namespace api } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/dial/dial_service.cc b/chromium/chrome/browser/extensions/api/dial/dial_service.cc index 1fe6dae2af0..679b6b0d6cc 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_service.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_service.cc @@ -55,6 +55,8 @@ using net::StringIOBuffer; using net::UDPSocket; namespace extensions { +namespace api { +namespace dial { namespace { @@ -619,4 +621,6 @@ bool DialServiceImpl::HasOpenSockets() { return false; } +} // namespace dial +} // namespace api } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/dial/dial_service.h b/chromium/chrome/browser/extensions/api/dial/dial_service.h index bbf2fdec126..dfe56c1986d 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_service.h +++ b/chromium/chrome/browser/extensions/api/dial/dial_service.h @@ -19,14 +19,14 @@ #include "net/socket/udp_socket.h" namespace net { -class IOBuffer; class IPEndPoint; class StringIOBuffer; class NetLog; -struct NetworkInterface; } namespace extensions { +namespace api { +namespace dial { class DialDeviceData; @@ -292,6 +292,8 @@ class DialServiceImpl : public DialService { DISALLOW_COPY_AND_ASSIGN(DialServiceImpl); }; +} // namespace dial +} // namespace api } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_DIAL_DIAL_SERVICE_H_ diff --git a/chromium/chrome/browser/extensions/api/dial/dial_service_unittest.cc b/chromium/chrome/browser/extensions/api/dial/dial_service_unittest.cc index 090ae6e98b2..9c46751de36 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_service_unittest.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_service_unittest.cc @@ -38,6 +38,8 @@ const char kValidResponse[] = } // namespace namespace extensions { +namespace api { +namespace dial { class MockObserver : public DialService::Observer { public: @@ -232,4 +234,6 @@ TEST_F(DialServiceTest, TestResponseParsing) { now, ¬_parsed)); } +} // namespace dial +} // namespace api } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc index 5e4ebbbd2e9..0f27c084dd2 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc @@ -441,6 +441,8 @@ DownloadItem* GetDownload(content::BrowserContext* context, return download_item; } +// Corresponds to |DownloadFunctions| enumeration in histograms.xml. Please +// keep these in sync. enum DownloadsFunctionName { DOWNLOADS_FUNCTION_DOWNLOAD = 0, DOWNLOADS_FUNCTION_SEARCH = 1, diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h index 6ad08a15c0d..5cfcf48df71 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h @@ -24,12 +24,6 @@ #include "extensions/browser/warning_set.h" class DownloadFileIconExtractor; -class DownloadQuery; - -namespace content { -class ResourceContext; -class ResourceDispatcherHost; -} namespace extensions { class ExtensionRegistry; diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc index a8a9eca778b..6e52ba5ce29 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc @@ -320,7 +320,6 @@ class DownloadExtensionTest : public ExtensionApiTest { CreateAndSetDownloadsDirectory(); current_browser()->profile()->GetPrefs()->SetBoolean( prefs::kPromptForDownload, false); - GetOnRecordManager()->RemoveAllDownloads(); events_listener_.reset(new DownloadsEventsListener()); // Disable file chooser for current profile. DownloadTestFileActivityObserver observer(current_browser()->profile()); @@ -332,7 +331,6 @@ class DownloadExtensionTest : public ExtensionApiTest { void GoOffTheRecord() { if (!incognito_browser_) { incognito_browser_ = CreateIncognitoBrowser(); - GetOffRecordManager()->RemoveAllDownloads(); // Disable file chooser for incognito profile. DownloadTestFileActivityObserver observer(incognito_browser_->profile()); observer.EnableFileChooser(false); @@ -950,10 +948,16 @@ scoped_refptr<UIThreadExtensionFunction> MockedGetFileIconFunction( return function; } +// https://crbug.com/678967 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_FileIcon_Active DISABLED_DownloadExtensionTest_FileIcon_Active +#else +#define MAYBE_DownloadExtensionTest_FileIcon_Active DownloadExtensionTest_FileIcon_Active +#endif // Test downloads.getFileIcon() on in-progress, finished, cancelled and deleted // download items. IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_FileIcon_Active) { + MAYBE_DownloadExtensionTest_FileIcon_Active) { DownloadItem* download_item = CreateSlowTestDownload(); ASSERT_TRUE(download_item); ASSERT_FALSE(download_item->GetTargetFilePath().empty()); diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc index 8a199fa4746..840f60d3f20 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc @@ -29,18 +29,18 @@ #include "chrome/browser/ui/proximity_auth/proximity_auth_error_bubble.h" #include "chrome/common/extensions/api/easy_unlock_private.h" #include "chrome/grit/generated_resources.h" +#include "components/cryptauth/bluetooth_throttler_impl.h" +#include "components/cryptauth/cryptauth_device_manager.h" +#include "components/cryptauth/cryptauth_enrollment_manager.h" +#include "components/cryptauth/cryptauth_enrollment_utils.h" +#include "components/cryptauth/proto/cryptauth_api.pb.h" +#include "components/cryptauth/remote_device.h" +#include "components/cryptauth/secure_message_delegate.h" #include "components/proximity_auth/ble/bluetooth_low_energy_connection.h" #include "components/proximity_auth/ble/bluetooth_low_energy_connection_finder.h" -#include "components/proximity_auth/bluetooth_throttler_impl.h" #include "components/proximity_auth/bluetooth_util.h" -#include "components/proximity_auth/cryptauth/cryptauth_device_manager.h" -#include "components/proximity_auth/cryptauth/cryptauth_enrollment_manager.h" -#include "components/proximity_auth/cryptauth/cryptauth_enrollment_utils.h" -#include "components/proximity_auth/cryptauth/proto/cryptauth_api.pb.h" -#include "components/proximity_auth/cryptauth/secure_message_delegate.h" #include "components/proximity_auth/logging/logging.h" #include "components/proximity_auth/proximity_auth_client.h" -#include "components/proximity_auth/remote_device.h" #include "components/proximity_auth/screenlock_bridge.h" #include "components/proximity_auth/screenlock_state.h" #include "components/proximity_auth/switches.h" @@ -600,7 +600,7 @@ void EasyUnlockPrivateGetPermitAccessFunction::GetKeyPairForExperiment( std::string* user_public_key, std::string* user_private_key) { Profile* profile = Profile::FromBrowserContext(browser_context()); - proximity_auth::CryptAuthEnrollmentManager* enrollment_manager = + cryptauth::CryptAuthEnrollmentManager* enrollment_manager = EasyUnlockService::Get(profile) ->proximity_auth_client() ->GetCryptAuthEnrollmentManager(); @@ -718,7 +718,7 @@ std::string EasyUnlockPrivateGetRemoteDevicesFunction::GetUserPrivateKey() { Profile* profile = Profile::FromBrowserContext(browser_context()); proximity_auth::ProximityAuthClient* client = EasyUnlockService::Get(profile)->proximity_auth_client(); - proximity_auth::CryptAuthEnrollmentManager* enrollment_manager = + cryptauth::CryptAuthEnrollmentManager* enrollment_manager = client->GetCryptAuthEnrollmentManager(); return enrollment_manager->GetUserPrivateKey(); } @@ -728,9 +728,9 @@ EasyUnlockPrivateGetRemoteDevicesFunction::GetUnlockKeys() { Profile* profile = Profile::FromBrowserContext(browser_context()); proximity_auth::ProximityAuthClient* client = EasyUnlockService::Get(profile)->proximity_auth_client(); - proximity_auth::CryptAuthDeviceManager* device_manager = + cryptauth::CryptAuthDeviceManager* device_manager = client->GetCryptAuthDeviceManager(); - return device_manager->unlock_keys(); + return device_manager->GetUnlockKeys(); } void EasyUnlockPrivateGetRemoteDevicesFunction::ReturnDevicesForExperiment() { @@ -909,7 +909,7 @@ ExtensionFunction::ResponseAction EasyUnlockPrivateGetUserInfoFunction::Run() { EasyUnlockService::GetUserSettings(account_id); user.require_close_proximity = user_settings.require_close_proximity; - user.device_user_id = proximity_auth::CalculateDeviceUserId( + user.device_user_id = cryptauth::CalculateDeviceUserId( EasyUnlockService::GetDeviceId(), account_id.GetUserEmail()); user.ble_discovery_enabled = @@ -1050,7 +1050,7 @@ EasyUnlockPrivateSetAutoPairingResultFunction::Run() { EasyUnlockPrivateFindSetupConnectionFunction:: EasyUnlockPrivateFindSetupConnectionFunction() - : bluetooth_throttler_(new proximity_auth::BluetoothThrottlerImpl( + : bluetooth_throttler_(new cryptauth::BluetoothThrottlerImpl( base::MakeUnique<base::DefaultTickClock>())) {} EasyUnlockPrivateFindSetupConnectionFunction:: @@ -1069,7 +1069,7 @@ void EasyUnlockPrivateFindSetupConnectionFunction:: } void EasyUnlockPrivateFindSetupConnectionFunction::OnConnectionFound( - std::unique_ptr<proximity_auth::Connection> connection) { + std::unique_ptr<cryptauth::Connection> connection) { // Connection are not persistent by default. std::string device_address = connection->remote_device().bluetooth_address; bool persistent = false; @@ -1090,7 +1090,7 @@ bool EasyUnlockPrivateFindSetupConnectionFunction::RunAsync() { // |params->setup_service_uuid|. connection_finder_.reset( new proximity_auth::BluetoothLowEnergyConnectionFinder( - proximity_auth::RemoteDevice(), params->setup_service_uuid, + cryptauth::RemoteDevice(), params->setup_service_uuid, proximity_auth::BluetoothLowEnergyConnectionFinder::FIND_ANY_DEVICE, nullptr, bluetooth_throttler_.get(), 3)); diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.h b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.h index 91b95f6aa99..91416507356 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.h +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.h @@ -28,14 +28,14 @@ class BrowserContext; } namespace cryptauth { +class BluetoothThrottler; +class Connection; class ExternalDeviceInfo; +class SecureMessageDelegate; } namespace proximity_auth { -class Connection; class BluetoothLowEnergyConnectionFinder; -class BluetoothThrottler; -class SecureMessageDelegate; } namespace extensions { @@ -339,7 +339,7 @@ class EasyUnlockPrivateGetRemoteDevicesFunction std::unique_ptr<base::ListValue> remote_devices_; // Used to derive devices' PSK. Used for the native experiment. - std::unique_ptr<proximity_auth::SecureMessageDelegate> + std::unique_ptr<cryptauth::SecureMessageDelegate> secure_message_delegate_; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateGetRemoteDevicesFunction); @@ -477,8 +477,7 @@ class EasyUnlockPrivateFindSetupConnectionFunction // Called when the connection with the remote device advertising the setup // service was found. - void OnConnectionFound( - std::unique_ptr<proximity_auth::Connection> connection); + void OnConnectionFound(std::unique_ptr<cryptauth::Connection> connection); // Callback when waiting for |connection_finder_| to return. void OnConnectionFinderTimedOut(); @@ -488,7 +487,7 @@ class EasyUnlockPrivateFindSetupConnectionFunction connection_finder_; // The connection throttler passed to the BLE connection finder. - std::unique_ptr<proximity_auth::BluetoothThrottler> bluetooth_throttler_; + std::unique_ptr<cryptauth::BluetoothThrottler> bluetooth_throttler_; // Used for timing out when waiting for the connection finder to return. std::unique_ptr<base::Timer> timer_; diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc index bbf17ca5113..6d0d2f32a62 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc @@ -12,7 +12,6 @@ #include "base/command_line.h" #include "base/macros.h" #include "base/memory/ptr_util.h" -#include "base/strings/stringprintf.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/extensions/extension_api_unittest.h" @@ -28,7 +27,7 @@ #include "chrome/common/extensions/extension_constants.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_easy_unlock_client.h" -#include "components/proximity_auth/cryptauth/proto/cryptauth_api.pb.h" +#include "components/cryptauth/proto/cryptauth_api.pb.h" #include "components/proximity_auth/switches.h" #include "device/bluetooth/dbus/bluez_dbus_manager.h" #include "extensions/browser/api_test_utils.h" @@ -580,7 +579,7 @@ TEST_F(EasyUnlockPrivateApiTest, GetRemoteDevicesExperimental) { extensions::api_test_utils::RunFunctionAndReturnSingleResult( function.get(), "[]", profile())); ASSERT_TRUE(value.get()); - ASSERT_EQ(base::Value::TYPE_LIST, value->GetType()); + ASSERT_EQ(base::Value::Type::LIST, value->GetType()); base::ListValue* list_value = static_cast<base::ListValue*>(value.get()); EXPECT_EQ(2u, list_value->GetSize()); @@ -589,8 +588,8 @@ TEST_F(EasyUnlockPrivateApiTest, GetRemoteDevicesExperimental) { base::Value* remote_device2; ASSERT_TRUE(list_value->Get(0, &remote_device1)); ASSERT_TRUE(list_value->Get(1, &remote_device2)); - EXPECT_EQ(base::Value::TYPE_DICTIONARY, remote_device1->GetType()); - EXPECT_EQ(base::Value::TYPE_DICTIONARY, remote_device2->GetType()); + EXPECT_EQ(base::Value::Type::DICTIONARY, remote_device1->GetType()); + EXPECT_EQ(base::Value::Type::DICTIONARY, remote_device2->GetType()); std::string name1, name2; EXPECT_TRUE(static_cast<base::DictionaryValue*>(remote_device1) @@ -614,7 +613,7 @@ TEST_F(EasyUnlockPrivateApiTest, GetRemoteDevicesNonExperimental) { extensions::api_test_utils::RunFunctionAndReturnSingleResult( function.get(), "[]", profile())); ASSERT_TRUE(value.get()); - ASSERT_EQ(base::Value::TYPE_LIST, value->GetType()); + ASSERT_EQ(base::Value::Type::LIST, value->GetType()); base::ListValue* list_value = static_cast<base::ListValue*>(value.get()); EXPECT_EQ(0u, list_value->GetSize()); @@ -635,7 +634,7 @@ TEST_F(EasyUnlockPrivateApiTest, GetPermitAccessExperimental) { extensions::api_test_utils::RunFunctionAndReturnSingleResult( function.get(), "[]", profile())); ASSERT_TRUE(value); - ASSERT_EQ(base::Value::TYPE_DICTIONARY, value->GetType()); + ASSERT_EQ(base::Value::Type::DICTIONARY, value->GetType()); base::DictionaryValue* permit_access = static_cast<base::DictionaryValue*>(value.get()); diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection.cc b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection.cc index c6265f5a2c4..88fe91ba818 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection.cc +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection.cc @@ -5,7 +5,7 @@ #include "chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection.h" #include "base/lazy_instance.h" -#include "components/proximity_auth/connection.h" +#include "components/cryptauth/connection.h" namespace extensions { @@ -22,14 +22,14 @@ ApiResourceManager<EasyUnlockPrivateConnection>::GetFactoryInstance() { EasyUnlockPrivateConnection::EasyUnlockPrivateConnection( bool persistent, const std::string& owner_extension_id, - std::unique_ptr<proximity_auth::Connection> connection) + std::unique_ptr<cryptauth::Connection> connection) : ApiResource(owner_extension_id), persistent_(persistent), connection_(connection.release()) {} EasyUnlockPrivateConnection::~EasyUnlockPrivateConnection() {} -proximity_auth::Connection* EasyUnlockPrivateConnection::GetConnection() const { +cryptauth::Connection* EasyUnlockPrivateConnection::GetConnection() const { return connection_.get(); } diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection.h b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection.h index f72f2a7fea8..9c42c0c4ad4 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection.h +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection.h @@ -11,22 +11,22 @@ #include "extensions/browser/api/api_resource.h" #include "extensions/browser/api/api_resource_manager.h" -namespace proximity_auth { +namespace cryptauth { class Connection; -} // namespace proximity_auth +} // namespace cryptauth namespace extensions { -// An ApiResource wrapper for a proximity_auth::Connection. +// An ApiResource wrapper for a cryptauth::Connection. class EasyUnlockPrivateConnection : public ApiResource { public: EasyUnlockPrivateConnection( bool persistent, const std::string& owner_extension_id, - std::unique_ptr<proximity_auth::Connection> connection); + std::unique_ptr<cryptauth::Connection> connection); ~EasyUnlockPrivateConnection() override; // Returns a pointer to the underlying connection object. - proximity_auth::Connection* GetConnection() const; + cryptauth::Connection* GetConnection() const; // ApiResource override. bool IsPersistent() const override; @@ -46,7 +46,7 @@ class EasyUnlockPrivateConnection : public ApiResource { // The connection is owned by this instance and will automatically disconnect // when deleted. - std::unique_ptr<proximity_auth::Connection> connection_; + std::unique_ptr<cryptauth::Connection> connection_; DISALLOW_COPY_AND_ASSIGN(EasyUnlockPrivateConnection); }; diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.cc b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.cc index 285ccc0d263..b6dd2d32a41 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.cc +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.cc @@ -10,15 +10,18 @@ #include "base/memory/ptr_util.h" #include "chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection.h" #include "chrome/common/extensions/api/easy_unlock_private.h" -#include "components/proximity_auth/connection.h" -#include "components/proximity_auth/wire_message.h" +#include "components/cryptauth/connection.h" +#include "components/cryptauth/wire_message.h" #include "extensions/browser/event_router.h" -using proximity_auth::Connection; -using proximity_auth::WireMessage; +using cryptauth::Connection; +using cryptauth::WireMessage; namespace extensions { namespace { + +const char kEasyUnlockFeatureName[] = "easy_unlock"; + api::easy_unlock_private::ConnectionStatus ToApiConnectionStatus( Connection::Status status) { switch (status) { @@ -31,6 +34,7 @@ api::easy_unlock_private::ConnectionStatus ToApiConnectionStatus( } return api::easy_unlock_private::CONNECTION_STATUS_NONE; } + } // namespace EasyUnlockPrivateConnectionManager::EasyUnlockPrivateConnectionManager( @@ -98,7 +102,8 @@ bool EasyUnlockPrivateConnectionManager::SendMessage( const std::string& payload) { Connection* connection = GetConnection(extension->id(), connection_id); if (connection && connection->IsConnected()) { - connection->SendMessage(base::MakeUnique<WireMessage>(payload)); + connection->SendMessage(base::MakeUnique<WireMessage>( + payload, std::string(kEasyUnlockFeatureName))); return true; } return false; @@ -123,6 +128,11 @@ void EasyUnlockPrivateConnectionManager::OnConnectionStatusChanged( void EasyUnlockPrivateConnectionManager::OnMessageReceived( const Connection& connection, const WireMessage& message) { + if (message.feature() != std::string(kEasyUnlockFeatureName)) { + // Only process messages received as part of EasyUnlock. + return; + } + std::string event_name = api::easy_unlock_private::OnDataReceived::kEventName; events::HistogramValue histogram_value = events::EASY_UNLOCK_PRIVATE_ON_DATA_RECEIVED; @@ -137,6 +147,11 @@ void EasyUnlockPrivateConnectionManager::OnSendCompleted( const Connection& connection, const WireMessage& message, bool success) { + if (message.feature() != std::string(kEasyUnlockFeatureName)) { + // Only process messages sent as part of EasyUnlock. + return; + } + std::string event_name = api::easy_unlock_private::OnSendCompleted::kEventName; events::HistogramValue histogram_value = diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.h b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.h index be4e4aceb13..a6d93474a13 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.h +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection_manager.h @@ -12,9 +12,9 @@ #include "base/macros.h" #include "chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_connection.h" #include "chrome/common/extensions/api/easy_unlock_private.h" -#include "components/proximity_auth/connection.h" -#include "components/proximity_auth/connection_observer.h" -#include "components/proximity_auth/wire_message.h" +#include "components/cryptauth/connection.h" +#include "components/cryptauth/connection_observer.h" +#include "components/cryptauth/wire_message.h" namespace content { class BrowserContext; @@ -25,9 +25,9 @@ namespace extensions { class Extension; // EasyUnlockPrivateConnectionManager is used by the EasyUnlockPrivateAPI to -// interface with proximity_auth::Connection. +// interface with cryptauth::Connection. class EasyUnlockPrivateConnectionManager - : public proximity_auth::ConnectionObserver { + : public cryptauth::ConnectionObserver { public: explicit EasyUnlockPrivateConnectionManager(content::BrowserContext* context); ~EasyUnlockPrivateConnectionManager() override; @@ -35,7 +35,7 @@ class EasyUnlockPrivateConnectionManager // Stores |connection| in the API connection manager. Returns the // |connection_id|. int AddConnection(const Extension* extension, - std::unique_ptr<proximity_auth::Connection> connection, + std::unique_ptr<cryptauth::Connection> connection, bool persistent); // Returns the status of the connection with |connection_id|. @@ -58,15 +58,15 @@ class EasyUnlockPrivateConnectionManager std::string GetDeviceAddress(const Extension* extension, int connection_id) const; - // proximity_auth::ConnectionObserver: + // cryptauth::ConnectionObserver: void OnConnectionStatusChanged( - proximity_auth::Connection* connection, - proximity_auth::Connection::Status old_status, - proximity_auth::Connection::Status new_status) override; - void OnMessageReceived(const proximity_auth::Connection& connection, - const proximity_auth::WireMessage& message) override; - void OnSendCompleted(const proximity_auth::Connection& connection, - const proximity_auth::WireMessage& message, + cryptauth::Connection* connection, + cryptauth::Connection::Status old_status, + cryptauth::Connection::Status new_status) override; + void OnMessageReceived(const cryptauth::Connection& connection, + const cryptauth::WireMessage& message) override; + void OnSendCompleted(const cryptauth::Connection& connection, + const cryptauth::WireMessage& message, bool success) override; private: @@ -75,7 +75,7 @@ class EasyUnlockPrivateConnectionManager // in |args| with it. void DispatchConnectionEvent(const std::string& event_name, events::HistogramValue histogram_value, - const proximity_auth::Connection* connection, + const cryptauth::Connection* connection, std::unique_ptr<base::ListValue> args); // Convenience method to get the API resource manager. @@ -83,13 +83,13 @@ class EasyUnlockPrivateConnectionManager // Convenience method to get the connection with |connection_id| created by // extension with |extension_id| from the API resource manager. - proximity_auth::Connection* GetConnection(const std::string& extension_id, - int connection_id) const; + cryptauth::Connection* GetConnection(const std::string& extension_id, + int connection_id) const; // Find the connection_id for |connection| owned by |extension_id| from the // API resource manager. int FindConnectionId(const std::string& extension_id, - const proximity_auth::Connection* connection); + const cryptauth::Connection* connection); // BrowserContext passed during initialization. content::BrowserContext* browser_context_; diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc index 64ad488fd0b..38ddb5c0ef7 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc @@ -136,7 +136,7 @@ void EPKPChallengeKeyBase::GetDeviceAttestationEnabled( } bool EPKPChallengeKeyBase::IsEnterpriseDevice() const { - return install_attributes_->IsEnterpriseDevice(); + return install_attributes_->IsEnterpriseManaged(); } bool EPKPChallengeKeyBase::IsExtensionWhitelisted() const { diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h index 0c7d484c533..2923b3436e6 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h @@ -22,7 +22,6 @@ #include "extensions/browser/extension_function.h" #include "third_party/cros_system_api/dbus/service_constants.h" -class PrefService; class Profile; namespace chromeos { diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc index 91555cbfd61..8556defb020 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc @@ -372,21 +372,21 @@ bool ExtensionActionFunction::ExtractDataFromArguments() { return true; switch (first_arg->GetType()) { - case base::Value::TYPE_INTEGER: + case base::Value::Type::INTEGER: CHECK(first_arg->GetAsInteger(&tab_id_)); break; - case base::Value::TYPE_DICTIONARY: { + case base::Value::Type::DICTIONARY: { // Found the details argument. details_ = static_cast<base::DictionaryValue*>(first_arg); // Still need to check for the tabId within details. base::Value* tab_id_value = NULL; if (details_->Get("tabId", &tab_id_value)) { switch (tab_id_value->GetType()) { - case base::Value::TYPE_NULL: + case base::Value::Type::NONE: // OK; tabId is optional, leave it default. return true; - case base::Value::TYPE_INTEGER: + case base::Value::Type::INTEGER: CHECK(tab_id_value->GetAsInteger(&tab_id_)); return true; default: @@ -398,7 +398,7 @@ bool ExtensionActionFunction::ExtractDataFromArguments() { break; } - case base::Value::TYPE_NULL: + case base::Value::Type::NONE: // The tabId might be an optional argument. break; @@ -502,7 +502,7 @@ ExtensionActionSetBadgeBackgroundColorFunction::RunExtensionAction() { base::Value* color_value = NULL; EXTENSION_FUNCTION_VALIDATE(details_->Get("color", &color_value)); SkColor color = 0; - if (color_value->IsType(base::Value::TYPE_LIST)) { + if (color_value->IsType(base::Value::Type::LIST)) { base::ListValue* list = NULL; EXTENSION_FUNCTION_VALIDATE(details_->GetList("color", &list)); EXTENSION_FUNCTION_VALIDATE(list->GetSize() == 4); @@ -514,7 +514,7 @@ ExtensionActionSetBadgeBackgroundColorFunction::RunExtensionAction() { color = SkColorSetARGB(color_array[3], color_array[0], color_array[1], color_array[2]); - } else if (color_value->IsType(base::Value::TYPE_STRING)) { + } else if (color_value->IsType(base::Value::Type::STRING)) { std::string color_string; EXTENSION_FUNCTION_VALIDATE(details_->GetString("color", &color_string)); if (!image_util::ParseCssColorString(color_string, &color)) diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc index 58a93349b3c..ea22eb4a037 100644 --- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc +++ b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.cc @@ -21,6 +21,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/ui/simple_message_box.h" +#include "chrome/common/extensions/api/feedback_private.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/grit/generated_resources.h" #include "components/feedback/tracing_manager.h" @@ -33,7 +34,7 @@ #include "url/url_util.h" #if defined(OS_CHROMEOS) -#include "chrome/browser/chromeos/arc/arc_auth_service.h" +#include "chrome/browser/chromeos/arc/arc_session_manager.h" #endif // defined(OS_CHROMEOS) #if defined(OS_WIN) @@ -73,6 +74,9 @@ using feedback_private::SystemInformation; using feedback_private::FeedbackInfo; using feedback_private::FeedbackFlow; +using SystemInformationList = + std::vector<api::feedback_private::SystemInformation>; + static base::LazyInstance<BrowserContextKeyedAPIFactory<FeedbackPrivateAPI> > g_factory = LAZY_INSTANCE_INITIALIZER; @@ -164,8 +168,9 @@ ExtensionFunction::ResponseAction FeedbackPrivateGetStringsFunction::Run() { SET_STRING("screenshot", IDS_FEEDBACK_SCREENSHOT_LABEL); SET_STRING("user-email", IDS_FEEDBACK_USER_EMAIL_LABEL); #if defined(OS_CHROMEOS) - const arc::ArcAuthService* auth_service = arc::ArcAuthService::Get(); - if (auth_service && auth_service->IsArcEnabled()) { + const arc::ArcSessionManager* arc_session_manager = + arc::ArcSessionManager::Get(); + if (arc_session_manager && arc_session_manager->IsArcEnabled()) { SET_STRING("sys-info", IDS_FEEDBACK_INCLUDE_SYSTEM_INFORMATION_AND_METRICS_CHKBOX_ARC); } else { @@ -219,21 +224,33 @@ ExtensionFunction::ResponseAction FeedbackPrivateGetUserEmailFunction::Run() { : std::string()))); } -bool FeedbackPrivateGetSystemInformationFunction::RunAsync() { - FeedbackService* service = - FeedbackPrivateAPI::GetFactoryInstance()->Get(GetProfile())->GetService(); +ExtensionFunction::ResponseAction +FeedbackPrivateGetSystemInformationFunction::Run() { + FeedbackService* service = FeedbackPrivateAPI::GetFactoryInstance() + ->Get(browser_context()) + ->GetService(); DCHECK(service); service->GetSystemInformation( base::Bind( &FeedbackPrivateGetSystemInformationFunction::OnCompleted, this)); - return true; + return RespondLater(); } void FeedbackPrivateGetSystemInformationFunction::OnCompleted( - const SystemInformationList& sys_info) { - results_ = feedback_private::GetSystemInformation::Results::Create( - sys_info); - SendResponse(true); + std::unique_ptr<system_logs::SystemLogsResponse> sys_info) { + SystemInformationList sys_info_list; + if (sys_info) { + sys_info_list.reserve(sys_info->size()); + for (auto& itr : *sys_info) { + SystemInformation sys_info_entry; + sys_info_entry.key = std::move(itr.first); + sys_info_entry.value = std::move(itr.second); + sys_info_list.emplace_back(std::move(sys_info_entry)); + } + } + + Respond(ArgumentList( + feedback_private::GetSystemInformation::Results::Create(sys_info_list))); } bool FeedbackPrivateSendFeedbackFunction::RunAsync() { diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h index d8b10a8152b..3ff94b9c3f7 100644 --- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h +++ b/chromium/chrome/browser/extensions/api/feedback_private/feedback_private_api.h @@ -6,6 +6,7 @@ #define CHROME_BROWSER_EXTENSIONS_API_FEEDBACK_PRIVATE_FEEDBACK_PRIVATE_API_H_ #include "chrome/browser/extensions/chrome_extension_function.h" +#include "chrome/browser/feedback/system_logs/system_logs_fetcher_base.h" #include "chrome/common/extensions/api/feedback_private.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/extension_function.h" @@ -81,18 +82,17 @@ class FeedbackPrivateGetUserEmailFunction : public UIThreadExtensionFunction { }; class FeedbackPrivateGetSystemInformationFunction - : public ChromeAsyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("feedbackPrivate.getSystemInformation", FEEDBACKPRIVATE_GETSYSTEMINFORMATION); protected: ~FeedbackPrivateGetSystemInformationFunction() override {} - bool RunAsync() override; + ResponseAction Run() override; private: - void OnCompleted( - const std::vector<api::feedback_private::SystemInformation>& sys_info); + void OnCompleted(std::unique_ptr<system_logs::SystemLogsResponse> sys_info); }; class FeedbackPrivateSendFeedbackFunction diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc b/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc index e63daf14528..c00f6dcb5fb 100644 --- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc +++ b/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.cc @@ -16,28 +16,10 @@ #include "net/base/network_change_notifier.h" using content::BrowserThread; -using extensions::api::feedback_private::SystemInformation; using feedback::FeedbackData; namespace extensions { -namespace { - -void PopulateSystemInfo(SystemInformationList* sys_info_list, - const std::string& key, - const std::string& value) { - base::DictionaryValue sys_info_value; - sys_info_value.Set("key", new base::StringValue(key)); - sys_info_value.Set("value", new base::StringValue(value)); - - SystemInformation sys_info; - SystemInformation::Populate(sys_info_value, &sys_info); - - sys_info_list->push_back(std::move(sys_info)); -} - -} // namespace - FeedbackService::FeedbackService() { } @@ -73,11 +55,10 @@ void FeedbackService::SendFeedback( } void FeedbackService::GetSystemInformation( - const GetSystemInformationCallback& callback) { + const system_logs::SysLogsFetcherCallback& callback) { system_logs::ScrubbedSystemLogsFetcher* fetcher = new system_logs::ScrubbedSystemLogsFetcher(); - fetcher->Fetch(base::Bind(&FeedbackService::OnSystemLogsFetchComplete, - AsWeakPtr(), callback)); + fetcher->Fetch(callback); } void FeedbackService::AttachedFileCallback( @@ -104,18 +85,6 @@ void FeedbackService::ScreenshotCallback( CompleteSendFeedback(feedback_data, callback); } -void FeedbackService::OnSystemLogsFetchComplete( - const GetSystemInformationCallback& callback, - std::unique_ptr<system_logs::SystemLogsResponse> sys_info_map) { - SystemInformationList sys_info_list; - if (sys_info_map.get()) { - for (const auto& itr : *sys_info_map) - PopulateSystemInfo(&sys_info_list, itr.first, itr.second); - } - - callback.Run(sys_info_list); -} - void FeedbackService::CompleteSendFeedback( scoped_refptr<feedback::FeedbackData> feedback_data, const SendFeedbackCallback& callback) { diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h b/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h index 9ada1947668..e0b44055f41 100644 --- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h +++ b/chromium/chrome/browser/extensions/api/feedback_private/feedback_service.h @@ -14,16 +14,12 @@ #include "base/memory/weak_ptr.h" #include "chrome/browser/extensions/blob_reader.h" #include "chrome/browser/feedback/system_logs/scrubbed_system_logs_fetcher.h" -#include "chrome/common/extensions/api/feedback_private.h" #include "components/feedback/feedback_data.h" class Profile; namespace extensions { -using SystemInformationList = - std::vector<api::feedback_private::SystemInformation>; - // The feedback service provides the ability to gather the various pieces of // data needed to send a feedback report and then send the report once all // the pieces are available. @@ -35,9 +31,6 @@ class FeedbackService : public base::SupportsWeakPtr<FeedbackService> { // offline). using SendFeedbackCallback = base::Callback<void(bool)>; - using GetSystemInformationCallback = - base::Callback<void(const SystemInformationList&)>; - FeedbackService(); virtual ~FeedbackService(); @@ -48,7 +41,8 @@ class FeedbackService : public base::SupportsWeakPtr<FeedbackService> { // Start to gather system information. // The |callback| will be invoked once the query is completed. - void GetSystemInformation(const GetSystemInformationCallback& callback); + void GetSystemInformation( + const system_logs::SysLogsFetcherCallback& callback); private: // Callbacks to receive blob data. @@ -61,10 +55,6 @@ class FeedbackService : public base::SupportsWeakPtr<FeedbackService> { std::unique_ptr<std::string> data, int64_t total_blob_length); - void OnSystemLogsFetchComplete( - const GetSystemInformationCallback& callback, - std::unique_ptr<system_logs::SystemLogsResponse> sys_info); - // Checks if we have read all the blobs we need to; signals the feedback // data object once all the requisite data has been populated. void CompleteSendFeedback(scoped_refptr<feedback::FeedbackData> feedback_data, diff --git a/chromium/chrome/browser/extensions/api/file_handlers/app_file_handler_util.cc b/chromium/chrome/browser/extensions/api/file_handlers/app_file_handler_util.cc index 07ce6f13126..53caea04d1f 100644 --- a/chromium/chrome/browser/extensions/api/file_handlers/app_file_handler_util.cc +++ b/chromium/chrome/browser/extensions/api/file_handlers/app_file_handler_util.cc @@ -217,20 +217,6 @@ const FileHandlerInfo* FileHandlerForId(const Extension& app, return NULL; } -const FileHandlerInfo* FirstFileHandlerForEntry(const Extension& app, - const EntryInfo& entry) { - const FileHandlersInfo* file_handlers = FileHandlers::GetFileHandlers(&app); - if (!file_handlers) - return NULL; - - for (FileHandlersInfo::const_iterator i = file_handlers->begin(); - i != file_handlers->end(); i++) { - if (FileHandlerCanHandleEntry(*i, entry)) - return &*i; - } - return NULL; -} - std::vector<const FileHandlerInfo*> FindFileHandlersForEntries( const Extension& app, const std::vector<EntryInfo> entries) { diff --git a/chromium/chrome/browser/extensions/api/file_handlers/app_file_handler_util.h b/chromium/chrome/browser/extensions/api/file_handlers/app_file_handler_util.h index d90b70733f3..28d19db1948 100644 --- a/chromium/chrome/browser/extensions/api/file_handlers/app_file_handler_util.h +++ b/chromium/chrome/browser/extensions/api/file_handlers/app_file_handler_util.h @@ -18,7 +18,6 @@ class Profile; namespace extensions { -class ExtensionPrefs; struct EntryInfo; struct FileHandlerInfo; struct GrantedFileEntry; @@ -34,11 +33,6 @@ extern const char kSecurityError[]; const FileHandlerInfo* FileHandlerForId(const Extension& app, const std::string& handler_id); -// Returns the first file handler that can handle the given entry, -// or NULL if is no such handler. -const FileHandlerInfo* FirstFileHandlerForEntry(const Extension& app, - const EntryInfo* entry); - // Returns the handlers that can handle all files in |entries|. std::vector<const FileHandlerInfo*> FindFileHandlersForEntries( const Extension& extension, diff --git a/chromium/chrome/browser/extensions/api/file_handlers/directory_util.h b/chromium/chrome/browser/extensions/api/file_handlers/directory_util.h index 5ed26be66c6..2de5b4718ae 100644 --- a/chromium/chrome/browser/extensions/api/file_handlers/directory_util.h +++ b/chromium/chrome/browser/extensions/api/file_handlers/directory_util.h @@ -20,10 +20,6 @@ namespace base { class FilePath; } // namespace base -namespace storage { -class FileSystemURL; -} // namespace storage - namespace extensions { namespace app_file_handler_util { diff --git a/chromium/chrome/browser/extensions/api/gcd_private/gcd_private_apitest.cc b/chromium/chrome/browser/extensions/api/gcd_private/gcd_private_apitest.cc index 485aad4d3dd..dde5f15f497 100644 --- a/chromium/chrome/browser/extensions/api/gcd_private/gcd_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/gcd_private/gcd_private_apitest.cc @@ -5,6 +5,7 @@ #include <stdint.h> #include "base/command_line.h" +#include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/extensions/api/gcd_private/gcd_private_api.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/local_discovery/test_service_discovery_client.h" @@ -114,6 +115,7 @@ class GcdPrivateAPITest : public ExtensionApiTest { class GcdPrivateWithMdnsAPITest : public GcdPrivateAPITest { public: void SetUpOnMainThread() override { + GcdPrivateAPITest::SetUpOnMainThread(); test_service_discovery_client_ = new local_discovery::TestServiceDiscoveryClient(); test_service_discovery_client_->Start(); @@ -121,7 +123,7 @@ class GcdPrivateWithMdnsAPITest : public GcdPrivateAPITest { void TearDownOnMainThread() override { test_service_discovery_client_ = nullptr; - ExtensionApiTest::TearDownOnMainThread(); + GcdPrivateAPITest::TearDownOnMainThread(); } protected: diff --git a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter_unittest.cc b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter_unittest.cc index a749c1abdf8..06ffe44b670 100644 --- a/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter_unittest.cc +++ b/chromium/chrome/browser/extensions/api/gcd_private/privet_v3_context_getter_unittest.cc @@ -45,12 +45,13 @@ class PrivetV3ContextGetterTest : public testing::Test, void CreateServer(EmbeddedTestServer::Type type) { server_.reset(new EmbeddedTestServer(type)); - ASSERT_TRUE(server_->Start()); base::FilePath test_data_dir; ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &test_data_dir)); server_->ServeFilesFromDirectory( test_data_dir.Append(FILE_PATH_LITERAL("chrome/test/data"))); + + ASSERT_TRUE(server_->Start()); } net::URLRequestStatus::Status Run() { diff --git a/chromium/chrome/browser/extensions/api/gcm/gcm_api.h b/chromium/chrome/browser/extensions/api/gcm/gcm_api.h index f0b3460167c..9a764c613d6 100644 --- a/chromium/chrome/browser/extensions/api/gcm/gcm_api.h +++ b/chromium/chrome/browser/extensions/api/gcm/gcm_api.h @@ -11,7 +11,6 @@ namespace gcm { class GCMDriver; -class GCMProfileService; } // namespace gcm class Profile; diff --git a/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc b/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc index fd8a8ae3281..943b763adf3 100644 --- a/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc @@ -453,7 +453,14 @@ IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, Training) { EXPECT_FALSE(service()->IsTraining()); } -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, OnSpeakerModelSaved) { +// Flaky on ChromeOS (https://crbug.com/668335) +#if defined(OS_CHROMEOS) +#define MAYBE_OnSpeakerModelSaved DISABLED_OnSpeakerModelSaved +#else +#define MAYBE_OnSpeakerModelSaved OnSpeakerModelSaved +#endif + +IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, MAYBE_OnSpeakerModelSaved) { extensions::HotwordPrivateEventService::GetFactoryInstance(); ExtensionTestMessageListener listener("ready", false); ASSERT_TRUE( diff --git a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc index 22f056d2618..d0f8fcb0fc7 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc @@ -10,7 +10,6 @@ #include "base/command_line.h" #include "base/memory/ptr_util.h" #include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/chrome_notification_types.h" diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc index 687389f7c8e..b28de0a291d 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc @@ -20,8 +20,9 @@ const int kPartitionTableSize = 2 * 4096; DestroyPartitionsOperation::DestroyPartitionsOperation( base::WeakPtr<OperationManager> manager, const ExtensionId& extension_id, - const std::string& storage_unit_id) - : Operation(manager, extension_id, storage_unit_id) {} + const std::string& storage_unit_id, + const base::FilePath& download_folder) + : Operation(manager, extension_id, storage_unit_id, download_folder) {} DestroyPartitionsOperation::~DestroyPartitionsOperation() {} diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h index b01e5131c44..30b7a961015 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h @@ -19,7 +19,8 @@ class DestroyPartitionsOperation : public Operation { public: DestroyPartitionsOperation(base::WeakPtr<OperationManager> manager, const ExtensionId& extension_id, - const std::string& storage_unit_id); + const std::string& storage_unit_id, + const base::FilePath& download_folder); void StartImpl() override; private: diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc index 64e8a5db024..491ff820f74 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc @@ -28,7 +28,8 @@ TEST_F(ImageWriterDestroyPartitionsOperationTest, EndToEnd) { new DestroyPartitionsOperation( manager.AsWeakPtr(), kDummyExtensionId, - test_utils_.GetDevicePath().AsUTF8Unsafe())); + test_utils_.GetDevicePath().AsUTF8Unsafe(), + base::FilePath(FILE_PATH_LITERAL("/var/tmp")))); EXPECT_CALL( manager, diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc index 1d8d74d8672..f06a7cc7e37 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc @@ -22,12 +22,6 @@ namespace image_writer { using content::BrowserThread; const int kMD5BufferSize = 1024; -#if defined(OS_CHROMEOS) -// Chrome OS only has a 1 GB temporary partition. This is too small to hold our -// unzipped image. Fortunately we mount part of the temporary partition under -// /var/tmp. -const char kChromeOSTempRoot[] = "/var/tmp"; -#endif #if !defined(OS_CHROMEOS) static base::LazyInstance<scoped_refptr<ImageWriterUtilityClient> > @@ -36,7 +30,8 @@ static base::LazyInstance<scoped_refptr<ImageWriterUtilityClient> > Operation::Operation(base::WeakPtr<OperationManager> manager, const ExtensionId& extension_id, - const std::string& device_path) + const std::string& device_path, + const base::FilePath& download_folder) : manager_(manager), extension_id_(extension_id), #if defined(OS_WIN) @@ -46,7 +41,8 @@ Operation::Operation(base::WeakPtr<OperationManager> manager, #endif stage_(image_writer_api::STAGE_UNKNOWN), progress_(0), - zip_reader_(new zip::ZipReader) { + zip_reader_(new zip::ZipReader), + download_folder_(download_folder) { } Operation::~Operation() {} @@ -81,8 +77,8 @@ void Operation::SetUtilityClientForTesting( void Operation::Start() { #if defined(OS_CHROMEOS) - if (!temp_dir_.CreateUniqueTempDirUnderPath( - base::FilePath(kChromeOSTempRoot))) { + if (download_folder_.empty() || + !temp_dir_.CreateUniqueTempDirUnderPath(download_folder_)) { #else if (!temp_dir_.CreateUniqueTempDir()) { #endif diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/operation.h index 98412b700a7..b6d49387369 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.h @@ -62,7 +62,8 @@ class Operation : public base::RefCountedThreadSafe<Operation> { Operation(base::WeakPtr<OperationManager> manager, const ExtensionId& extension_id, - const std::string& device_path); + const std::string& device_path, + const base::FilePath& download_folder); // Starts the operation. void Start(); @@ -223,6 +224,11 @@ class Operation : public base::RefCountedThreadSafe<Operation> { // CleanUp operations that must be run. All these functions are run on the // FILE thread. std::vector<base::Closure> cleanup_functions_; + + // The download folder on Chrome OS. + const base::FilePath download_folder_; + + DISALLOW_COPY_AND_ASSIGN(Operation); }; } // namespace image_writer diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc index f8f036d0115..aaa05ff03c7 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc @@ -25,6 +25,10 @@ #include "extensions/browser/extension_registry.h" #include "extensions/browser/notification_types.h" +#if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/file_manager/path_util.h" +#endif + namespace image_writer_api = extensions::api::image_writer_private; namespace extensions { @@ -87,7 +91,8 @@ void OperationManager::StartWriteFromUrl( GetURLRequestContext(), url, hash, - device_path)); + device_path, + GetAssociatedDownloadFolder())); operations_[extension_id] = operation; BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, @@ -112,7 +117,8 @@ void OperationManager::StartWriteFromFile( } scoped_refptr<Operation> operation(new WriteFromFileOperation( - weak_factory_.GetWeakPtr(), extension_id, path, device_path)); + weak_factory_.GetWeakPtr(), extension_id, path, device_path, + GetAssociatedDownloadFolder())); operations_[extension_id] = operation; BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, @@ -147,7 +153,8 @@ void OperationManager::DestroyPartitions( } scoped_refptr<Operation> operation(new DestroyPartitionsOperation( - weak_factory_.GetWeakPtr(), extension_id, device_path)); + weak_factory_.GetWeakPtr(), extension_id, device_path, + GetAssociatedDownloadFolder())); operations_[extension_id] = operation; BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, @@ -213,6 +220,14 @@ void OperationManager::OnError(const ExtensionId& extension_id, DeleteOperation(extension_id); } +base::FilePath OperationManager::GetAssociatedDownloadFolder() { +#if defined(OS_CHROMEOS) + Profile* profile = Profile::FromBrowserContext(browser_context_); + return file_manager::util::GetDownloadsFolderForProfile(profile); +#endif + return base::FilePath(); +} + Operation* OperationManager::GetOperation(const ExtensionId& extension_id) { OperationMap::iterator existing_operation = operations_.find(extension_id); diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h index 993019bdc67..5243080e972 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h @@ -24,8 +24,6 @@ namespace image_writer_api = extensions::api::image_writer_private; -class Profile; - namespace content { class BrowserContext; } @@ -106,6 +104,9 @@ class OperationManager : public BrowserContextKeyedAPI, Operation* GetOperation(const ExtensionId& extension_id); void DeleteOperation(const ExtensionId& extension_id); + // Accessor to the associated profile download folder + base::FilePath GetAssociatedDownloadFolder(); + friend class BrowserContextKeyedAPIFactory<OperationManager>; typedef std::map<ExtensionId, scoped_refptr<Operation> > OperationMap; diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc index 55ab362bfa7..c0d6833d314 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc @@ -35,8 +35,9 @@ class OperationForTest : public Operation { public: OperationForTest(base::WeakPtr<OperationManager> manager_, const ExtensionId& extension_id, - const std::string& device_path) - : Operation(manager_, extension_id, device_path) {} + const std::string& device_path, + const base::FilePath& download_path) + : Operation(manager_, extension_id, device_path, download_path) {} void StartImpl() override {} @@ -85,7 +86,8 @@ class ImageWriterOperationTest : public ImageWriterUnitTestBase { operation_ = new OperationForTest(manager_.AsWeakPtr(), kDummyExtensionId, - test_utils_.GetDevicePath().AsUTF8Unsafe()); + test_utils_.GetDevicePath().AsUTF8Unsafe(), + base::FilePath(FILE_PATH_LITERAL("/var/tmp"))); operation_->SetImagePath(test_utils_.GetImagePath()); } diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc index a80427854f8..b29feaa45dc 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc @@ -16,8 +16,9 @@ WriteFromFileOperation::WriteFromFileOperation( base::WeakPtr<OperationManager> manager, const ExtensionId& extension_id, const base::FilePath& user_file_path, - const std::string& device_path) - : Operation(manager, extension_id, device_path) { + const std::string& device_path, + const base::FilePath& download_folder) + : Operation(manager, extension_id, device_path, download_folder) { image_path_ = user_file_path; } diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h index 3f567ae080a..ef82e25f881 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h @@ -16,7 +16,8 @@ class WriteFromFileOperation : public Operation { WriteFromFileOperation(base::WeakPtr<OperationManager> manager, const ExtensionId& extension_id, const base::FilePath& user_file_path, - const std::string& storage_unit_id); + const std::string& storage_unit_id, + const base::FilePath& download_folder); void StartImpl() override; private: diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc index bb241d01727..3c6fb916d49 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc @@ -29,7 +29,8 @@ TEST_F(ImageWriterFromFileTest, InvalidFile) { new WriteFromFileOperation(manager_.AsWeakPtr(), kDummyExtensionId, test_utils_.GetImagePath(), - test_utils_.GetDevicePath().AsUTF8Unsafe()); + test_utils_.GetDevicePath().AsUTF8Unsafe(), + base::FilePath(FILE_PATH_LITERAL("/var/tmp"))); base::DeleteFile(test_utils_.GetImagePath(), false); @@ -52,7 +53,8 @@ TEST_F(ImageWriterFromFileTest, WriteFromFileEndToEnd) { new WriteFromFileOperation(manager_.AsWeakPtr(), kDummyExtensionId, test_utils_.GetImagePath(), - test_utils_.GetDevicePath().AsUTF8Unsafe()); + test_utils_.GetDevicePath().AsUTF8Unsafe(), + base::FilePath(FILE_PATH_LITERAL("/var/tmp"))); EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, image_writer_api::STAGE_WRITE, _)) .Times(AnyNumber()); diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc index 911d93893de..4c619e38b9f 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc @@ -20,8 +20,9 @@ WriteFromUrlOperation::WriteFromUrlOperation( net::URLRequestContextGetter* request_context, GURL url, const std::string& hash, - const std::string& device_path) - : Operation(manager, extension_id, device_path), + const std::string& device_path, + const base::FilePath& download_folder) + : Operation(manager, extension_id, device_path, download_folder), request_context_(request_context), url_(url), hash_(hash), diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h index 99013ce54d2..b653bbfb70c 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h @@ -29,7 +29,8 @@ class WriteFromUrlOperation : public Operation, public net::URLFetcherDelegate { net::URLRequestContextGetter* request_context, GURL url, const std::string& hash, - const std::string& storage_unit_id); + const std::string& storage_unit_id, + const base::FilePath& download_folder); void StartImpl() override; protected: diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc index ca70690c292..d26833a1ee2 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc @@ -40,7 +40,8 @@ class OperationForTest : public WriteFromUrlOperation { request_context, url, hash, - storage_unit_id) {} + storage_unit_id, + base::FilePath(FILE_PATH_LITERAL("/var/tmp"))) {} void StartImpl() override {} diff --git a/chromium/chrome/browser/extensions/api/inline_install_private/inline_install_private_apitest.cc b/chromium/chrome/browser/extensions/api/inline_install_private/inline_install_private_apitest.cc index 7cf7f3450b7..f376268b53d 100644 --- a/chromium/chrome/browser/extensions/api/inline_install_private/inline_install_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/inline_install_private/inline_install_private_apitest.cc @@ -40,7 +40,7 @@ class InlineInstallPrivateApiTestApp : public: InlineInstallPrivateApiTestApp() : InlineInstallPrivateApiTestBase( - "extensions/api_test/inline_install_private/", + "extensions/api_test/inline_install_private", "app.crx") {} }; diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc index e1969b3423d..92d58e9eb86 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc @@ -5,6 +5,7 @@ #include "chrome/browser/extensions/api/input_ime/input_ime_api.h" #include "base/lazy_instance.h" +#include "base/memory/ptr_util.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/common/extensions/api/input_ime.h" #include "content/public/browser/notification_registrar.h" diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h index 2b2f81be125..a4b849daa20 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h @@ -65,6 +65,7 @@ class ImeObserver : public input_method::InputMethodEngineBase::Observer { int cursor_pos, int anchor_pos, int offset_pos) override; + void OnRequestEngineSwitch() override {}; protected: // Helper function used to forward the given event to the |profile_|'s event diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc index 8d8778b812a..29a9791edc1 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc @@ -91,6 +91,17 @@ class ImeObserverNonChromeOS : public ui::ImeObserver { OnCompositionBoundsChanged::kEventName, std::move(args)); } + void OnRequestEngineSwitch() override { + Browser* browser = chrome::FindLastActive(); + if (!browser) + return; + extensions::InputImeEventRouter* router = + extensions::GetInputImeEventRouter(browser->profile()); + if (!router) + return; + ui::IMEBridge::Get()->SetCurrentEngineHandler(router->active_engine()); + } + private: // ImeObserver overrides. void DispatchEventToExtension( diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h index 011015e56ae..da76c4637c6 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h @@ -41,6 +41,10 @@ class InputImeEventRouter : public InputImeEventRouterBase { // previous engine if another extension was active. void SetActiveEngine(const std::string& extension_id); + input_method::InputMethodEngine* active_engine() { + return active_engine_; + } + // Deletes the current input method engine of the specific extension. void DeleteInputMethodEngine(const std::string& extension_id); diff --git a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h index 4665b47e828..eb514ab7838 100644 --- a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h +++ b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h @@ -9,8 +9,6 @@ #include "components/gcm_driver/instance_id/instance_id.h" #include "extensions/browser/extension_function.h" -class Profile; - namespace extensions { class InstanceIDApiFunction : public UIThreadExtensionFunction { diff --git a/chromium/chrome/browser/extensions/api/launcher_page/launcher_page_api.h b/chromium/chrome/browser/extensions/api/launcher_page/launcher_page_api.h index 1f5a0dce27c..a1897fcceb6 100644 --- a/chromium/chrome/browser/extensions/api/launcher_page/launcher_page_api.h +++ b/chromium/chrome/browser/extensions/api/launcher_page/launcher_page_api.h @@ -11,7 +11,6 @@ namespace app_list { class AppListSyncableService; -class AppListModel; } namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/log_private/log_private_apitest_chromeos.cc b/chromium/chrome/browser/extensions/api/log_private/log_private_apitest_chromeos.cc index 47f29ab538d..6a9d490fbfc 100644 --- a/chromium/chrome/browser/extensions/api/log_private/log_private_apitest_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/log_private/log_private_apitest_chromeos.cc @@ -89,9 +89,9 @@ class LogPrivateApiTest : public ExtensionApiTest { IN_PROC_BROWSER_TEST_F(LogPrivateApiTest, DumpLogsAndCaptureEvents) { // Setup dummy HTTP server. host_resolver()->AddRule("www.test.com", "127.0.0.1"); - ASSERT_TRUE(StartEmbeddedTestServer()); embedded_test_server()->RegisterRequestHandler( base::Bind(&LogPrivateApiTest::HandleRequest, base::Unretained(this))); + ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionTest("log_private/dump_logs")); } diff --git a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc index 6e0998c35d2..9d52108e54c 100644 --- a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc +++ b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc @@ -338,8 +338,7 @@ GURL ChromeManagementAPIDelegate::GetIconURL( const extensions::Extension* extension, int icon_size, ExtensionIconSet::MatchType match, - bool grayscale, - bool* exists) const { + bool grayscale) const { return extensions::ExtensionIconSource::GetIconURL(extension, icon_size, - match, grayscale, exists); + match, grayscale); } diff --git a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h index 87c41c06728..6c127360516 100644 --- a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h +++ b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h @@ -10,10 +10,6 @@ #include "chrome/browser/extensions/extension_uninstall_dialog.h" #include "extensions/browser/api/management/management_api_delegate.h" -namespace favicon_base { -struct FaviconImageResult; -} // namespace favicon_base - class ChromeManagementAPIDelegate : public extensions::ManagementAPIDelegate { public: ChromeManagementAPIDelegate(); @@ -71,8 +67,7 @@ class ChromeManagementAPIDelegate : public extensions::ManagementAPIDelegate { GURL GetIconURL(const extensions::Extension* extension, int icon_size, ExtensionIconSet::MatchType match, - bool grayscale, - bool* exists) const override; + bool grayscale) const override; }; #endif // CHROME_BROWSER_EXTENSIONS_API_MANAGEMENT_CHROME_MANAGEMENT_API_DELEGATE_H_ diff --git a/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc b/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc index d8673d79204..75c9f026141 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc @@ -179,6 +179,7 @@ class ExtensionManagementApiEscalationTest : static const char kId[]; void SetUpOnMainThread() override { + ExtensionManagementApiBrowserTest::SetUpOnMainThread(); EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); base::FilePath pem_path = test_data_dir_. AppendASCII("permissions_increase").AppendASCII("permissions.pem"); @@ -243,7 +244,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiEscalationTest, std::unique_ptr<base::Value> result(util::RunFunctionAndReturnSingleResult( function.get(), base::StringPrintf("[\"%s\"]", kId), browser())); ASSERT_TRUE(result.get() != NULL); - ASSERT_TRUE(result->IsType(base::Value::TYPE_DICTIONARY)); + ASSERT_TRUE(result->IsType(base::Value::Type::DICTIONARY)); base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(result.get()); std::string reason; diff --git a/chromium/chrome/browser/extensions/api/management/management_apitest.cc b/chromium/chrome/browser/extensions/api/management/management_apitest.cc index 281ebe37432..978aaf341a1 100644 --- a/chromium/chrome/browser/extensions/api/management/management_apitest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_apitest.cc @@ -201,8 +201,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, "prohibited.html")); } -// Disabled. See http://crbug.com/176023 -IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, DISABLED_LaunchPanelApp) { +IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) { ExtensionService* service = extensions::ExtensionSystem::Get( browser()->profile())->extension_service(); diff --git a/chromium/chrome/browser/extensions/api/mdns/dns_sd_registry.h b/chromium/chrome/browser/extensions/api/mdns/dns_sd_registry.h index 4f342684288..2ea2057ebd0 100644 --- a/chromium/chrome/browser/extensions/api/mdns/dns_sd_registry.h +++ b/chromium/chrome/browser/extensions/api/mdns/dns_sd_registry.h @@ -17,7 +17,6 @@ namespace local_discovery { class ServiceDiscoverySharedClient; -class ServiceDiscoveryClient; } namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc index 6daf3bdca3e..d5d062629d2 100644 --- a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc +++ b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc @@ -41,6 +41,7 @@ #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "components/storage_monitor/storage_info.h" +#include "components/web_modal/web_contents_modal_dialog_manager.h" #include "content/public/browser/blob_handle.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" @@ -49,6 +50,8 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" +#include "extensions/browser/app_window/app_window.h" +#include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/blob_holder.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_system.h" @@ -262,6 +265,30 @@ class SelectDirectoryDialog : public ui::SelectFileDialog::Listener, DISALLOW_COPY_AND_ASSIGN(SelectDirectoryDialog); }; +// Returns a web contents to use as the source for a prompt showing to the user. +// The web contents has to support modal dialogs, so it can't be the app's +// background page. +content::WebContents* GetWebContentsForPrompt( + content::WebContents* sender_web_contents, + content::BrowserContext* browser_context, + const std::string& app_id) { + // Check if the sender web contents supports modal dialogs. + if (sender_web_contents && + web_modal::WebContentsModalDialogManager::FromWebContents( + sender_web_contents)) { + return sender_web_contents; + } + // Otherwise, check for the current app window for the app (app windows + // support modal dialogs). + if (!app_id.empty()) { + AppWindow* window = AppWindowRegistry::Get(browser_context) + ->GetCurrentAppWindowForApp(app_id); + if (window) + return window->web_contents(); + } + return nullptr; +} + } // namespace MediaGalleriesEventRouter::MediaGalleriesEventRouter( @@ -445,7 +472,9 @@ void MediaGalleriesGetMediaFileSystemsFunction::ReturnGalleries( void MediaGalleriesGetMediaFileSystemsFunction::ShowDialog() { media_galleries::UsageCount(media_galleries::SHOW_DIALOG); WebContents* contents = - ChromeExtensionFunctionDetails(this).GetOriginWebContents(); + GetWebContentsForPrompt(GetSenderWebContents(), + browser_context(), + extension()->id()); if (!contents) { SendResponse(false); return; @@ -482,10 +511,11 @@ bool MediaGalleriesAddUserSelectedFolderFunction::RunAsync() { } void MediaGalleriesAddUserSelectedFolderFunction::OnPreferencesInit() { - Profile* profile = GetProfile(); const std::string& app_id = extension()->id(); WebContents* contents = - ChromeExtensionFunctionDetails(this).GetOriginWebContents(); + GetWebContentsForPrompt(GetSenderWebContents(), + browser_context(), + app_id); if (!contents) { SendResponse(false); return; @@ -498,7 +528,7 @@ void MediaGalleriesAddUserSelectedFolderFunction::OnPreferencesInit() { base::FilePath last_used_path = extensions::file_system_api::GetLastChooseEntryDirectory( - extensions::ExtensionPrefs::Get(profile), app_id); + extensions::ExtensionPrefs::Get(browser_context()), app_id); SelectDirectoryDialog::Callback callback = base::Bind( &MediaGalleriesAddUserSelectedFolderFunction::OnDirectorySelected, this); scoped_refptr<SelectDirectoryDialog> select_directory_dialog = @@ -722,9 +752,16 @@ void MediaGalleriesGetMetadataFunction::ConstructNextBlob( attached_images_list->Append(std::move(attached_image)); blob_uuids->push_back(current_blob->GetUUID()); + + content::RenderProcessHost* render_process_host = + render_frame_host()->GetProcess(); + if (!render_process_host) { + SendResponse(false); + return; + } + extensions::BlobHolder* holder = - extensions::BlobHolder::FromRenderProcessHost( - render_frame_host()->GetProcess()); + extensions::BlobHolder::FromRenderProcessHost(render_process_host); holder->HoldBlobReference(std::move(current_blob)); // Construct the next Blob if necessary. diff --git a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.h b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.h index e0927284cd0..ba623c552a0 100644 --- a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.h +++ b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_api.h @@ -31,17 +31,10 @@ namespace MediaGalleries = extensions::api::media_galleries; namespace content { class BlobHandle; -class WebContents; -} - -namespace metadata { -class SafeMediaMetadataParser; } namespace extensions { -class Extension; - // The profile-keyed service that manages the media galleries extension API. // Created at the same time as the Profile. This is also the event router. class MediaGalleriesEventRouter : public BrowserContextKeyedAPI, diff --git a/chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc b/chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc index 2e7f5952750..09e55602fe5 100644 --- a/chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc +++ b/chromium/chrome/browser/extensions/api/messaging/extension_message_port.cc @@ -91,7 +91,7 @@ class ExtensionMessagePort::FrameTracker : public content::WebContentsObserver, ExtensionMessagePort::ExtensionMessagePort( base::WeakPtr<MessageService> message_service, - int port_id, + const PortId& port_id, const std::string& extension_id, content::RenderProcessHost* extension_process) : weak_message_service_(message_service), @@ -99,7 +99,6 @@ ExtensionMessagePort::ExtensionMessagePort( extension_id_(extension_id), browser_context_(extension_process->GetBrowserContext()), extension_process_(extension_process), - opener_tab_id_(-1), did_create_port_(false), background_host_ptr_(nullptr), frame_tracker_(new FrameTracker(this)) { @@ -113,7 +112,7 @@ ExtensionMessagePort::ExtensionMessagePort( ExtensionMessagePort::ExtensionMessagePort( base::WeakPtr<MessageService> message_service, - int port_id, + const PortId& port_id, const std::string& extension_id, content::RenderFrameHost* rfh, bool include_child_frames) @@ -122,7 +121,6 @@ ExtensionMessagePort::ExtensionMessagePort( extension_id_(extension_id), browser_context_(rfh->GetProcess()->GetBrowserContext()), extension_process_(nullptr), - opener_tab_id_(-1), did_create_port_(false), background_host_ptr_(nullptr), frame_tracker_(new FrameTracker(this)) { @@ -203,10 +201,8 @@ void ExtensionMessagePort::DispatchOnConnect( const GURL& source_url, const std::string& tls_channel_id) { ExtensionMsg_TabConnectionInfo source; - if (source_tab) { + if (source_tab) source.tab.Swap(source_tab.get()); - source.tab.GetInteger("id", &opener_tab_id_); - } source.frame_id = source_frame_id; ExtensionMsg_ExternalConnectionInfo info; @@ -228,7 +224,7 @@ void ExtensionMessagePort::DispatchOnDisconnect( void ExtensionMessagePort::DispatchOnMessage(const Message& message) { SendToPort(base::MakeUnique<ExtensionMsg_DeliverMessage>( - MSG_ROUTING_NONE, port_id_, opener_tab_id_, message)); + MSG_ROUTING_NONE, port_id_, message)); } void ExtensionMessagePort::IncrementLazyKeepaliveCount() { diff --git a/chromium/chrome/browser/extensions/api/messaging/extension_message_port.h b/chromium/chrome/browser/extensions/api/messaging/extension_message_port.h index 92b785803d2..4c2ba8a831d 100644 --- a/chromium/chrome/browser/extensions/api/messaging/extension_message_port.h +++ b/chromium/chrome/browser/extensions/api/messaging/extension_message_port.h @@ -7,6 +7,7 @@ #include "base/macros.h" #include "chrome/browser/extensions/api/messaging/message_service.h" +#include "extensions/common/api/messaging/port_id.h" class GURL; @@ -29,14 +30,14 @@ class ExtensionMessagePort : public MessageService::MessagePort { public: // Create a port that is tied to frame(s) in a single tab. ExtensionMessagePort(base::WeakPtr<MessageService> message_service, - int port_id, + const PortId& port_id, const std::string& extension_id, content::RenderFrameHost* rfh, bool include_child_frames); // Create a port that is tied to all frames of an extension, possibly spanning // multiple tabs, including the invisible background page, popups, etc. ExtensionMessagePort(base::WeakPtr<MessageService> message_service, - int port_id, + const PortId& port_id, const std::string& extension_id, content::RenderProcessHost* extension_process); ~ExtensionMessagePort() override; @@ -85,7 +86,7 @@ class ExtensionMessagePort : public MessageService::MessagePort { base::WeakPtr<MessageService> weak_message_service_; - int port_id_; + const PortId port_id_; std::string extension_id_; content::BrowserContext* browser_context_; // Only for receivers in an extension process. @@ -98,11 +99,6 @@ class ExtensionMessagePort : public MessageService::MessagePort { // when the frame is removed or unloaded. std::set<content::RenderFrameHost*> frames_; - // The ID of the tab where the channel was created. This is saved so that any - // onMessage events can be run in the scope of the tab. - // Only set on receiver ports (if the opener was a tab). -1 if invalid. - int opener_tab_id_; - // Whether the renderer acknowledged creation of the port. This is used to // distinguish abnormal port closure (e.g. no receivers) from explicit port // closure (e.g. by the port.disconnect() JavaScript method in the renderer). diff --git a/chromium/chrome/browser/extensions/api/messaging/message_service.cc b/chromium/chrome/browser/extensions/api/messaging/message_service.cc index 5b4c3829bff..b77fbdeea3c 100644 --- a/chromium/chrome/browser/extensions/api/messaging/message_service.cc +++ b/chromium/chrome/browser/extensions/api/messaging/message_service.cc @@ -8,7 +8,6 @@ #include <limits> #include <utility> -#include "base/atomic_sequence_num.h" #include "base/bind.h" #include "base/callback.h" #include "base/json/json_writer.h" @@ -63,18 +62,6 @@ using content::BrowserThread; using content::SiteInstance; using content::WebContents; -// Since we have 2 ports for every channel, we just index channels by half the -// port ID. -#define GET_CHANNEL_ID(port_id) ((port_id) / 2) -#define GET_CHANNEL_OPENER_ID(channel_id) ((channel_id) * 2) -#define GET_CHANNEL_RECEIVERS_ID(channel_id) ((channel_id) * 2 + 1) - -// Port1 is always even, port2 is always odd. -#define IS_OPENER_PORT_ID(port_id) (((port_id) & 1) == 0) - -// Change even to odd and vice versa, to get the other side of a given channel. -#define GET_OPPOSITE_PORT_ID(source_port_id) ((source_port_id) ^ 1) - namespace extensions { MessageService::PolicyPermission MessageService::IsNativeMessagingHostAllowed( @@ -138,7 +125,7 @@ struct MessageService::OpenChannelParams { std::unique_ptr<base::DictionaryValue> source_tab; int source_frame_id; std::unique_ptr<MessagePort> receiver; - int receiver_port_id; + PortId receiver_port_id; std::string source_extension_id; std::string target_extension_id; GURL source_url; @@ -153,7 +140,7 @@ struct MessageService::OpenChannelParams { std::unique_ptr<base::DictionaryValue> source_tab, int source_frame_id, MessagePort* receiver, - int receiver_port_id, + const PortId& receiver_port_id, const std::string& source_extension_id, const std::string& target_extension_id, const GURL& source_url, @@ -181,8 +168,6 @@ struct MessageService::OpenChannelParams { namespace { -static base::StaticAtomicSequenceNumber g_next_channel_id; - static content::RenderProcessHost* GetExtensionProcess( BrowserContext* context, const std::string& extension_id) { @@ -201,28 +186,6 @@ bool MessageService::MessagePort::HasFrame( return false; } -// static -void MessageService::AllocatePortIdPair(int* port1, int* port2) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - - unsigned channel_id = static_cast<unsigned>(g_next_channel_id.GetNext()) % - (std::numeric_limits<int32_t>::max() / 2); - unsigned port1_id = channel_id * 2; - unsigned port2_id = channel_id * 2 + 1; - - // Sanity checks to make sure our channel<->port converters are correct. - DCHECK(IS_OPENER_PORT_ID(port1_id)); - DCHECK_EQ(GET_OPPOSITE_PORT_ID(port1_id), port2_id); - DCHECK_EQ(GET_OPPOSITE_PORT_ID(port2_id), port1_id); - DCHECK_EQ(GET_CHANNEL_ID(port1_id), GET_CHANNEL_ID(port2_id)); - DCHECK_EQ(GET_CHANNEL_ID(port1_id), channel_id); - DCHECK_EQ(GET_CHANNEL_OPENER_ID(channel_id), port1_id); - DCHECK_EQ(GET_CHANNEL_RECEIVERS_ID(channel_id), port2_id); - - *port1 = port1_id; - *port2 = port2_id; -} - MessageService::MessageService(BrowserContext* context) : lazy_background_task_queue_( LazyBackgroundTaskQueue::Get(context)), @@ -251,13 +214,16 @@ MessageService* MessageService::Get(BrowserContext* context) { } void MessageService::OpenChannelToExtension( - int source_process_id, int source_routing_id, int receiver_port_id, + int source_process_id, + int source_routing_id, + const PortId& source_port_id, const std::string& source_extension_id, const std::string& target_extension_id, const GURL& source_url, const std::string& channel_name, bool include_tls_channel_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(source_port_id.is_opener); content::RenderFrameHost* source = content::RenderFrameHost::FromID(source_process_id, source_routing_id); @@ -268,6 +234,8 @@ void MessageService::OpenChannelToExtension( ExtensionRegistry* registry = ExtensionRegistry::Get(context); const Extension* target_extension = registry->enabled_extensions().GetByID(target_extension_id); + PortId receiver_port_id(source_port_id.context_id, source_port_id.port_number, + false); if (!target_extension) { DispatchOnDisconnect( source, receiver_port_id, kReceivingEndDoesntExistError); @@ -355,7 +323,7 @@ void MessageService::OpenChannelToExtension( target_extension_id, source_url, channel_name, include_tls_channel_id, include_guest_process_info)); - pending_incognito_channels_[GET_CHANNEL_ID(params->receiver_port_id)] = + pending_incognito_channels_[params->receiver_port_id.GetChannelId()] = PendingMessagesQueue(); if (context->IsOffTheRecord() && !util::IsIncognitoEnabled(target_extension_id, context)) { @@ -405,9 +373,10 @@ void MessageService::OpenChannelToExtension( void MessageService::OpenChannelToNativeApp( int source_process_id, int source_routing_id, - int receiver_port_id, + const PortId& source_port_id, const std::string& native_app_name) { DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(source_port_id.is_opener); content::RenderFrameHost* source = content::RenderFrameHost::FromID(source_process_id, source_routing_id); @@ -430,6 +399,8 @@ void MessageService::OpenChannelToNativeApp( extension->permissions_data()->HasAPIPermission( APIPermission::kNativeMessaging); + PortId receiver_port_id(source_port_id.context_id, source_port_id.port_number, + false); if (!has_permission) { DispatchOnDisconnect(source, receiver_port_id, kMissingPermissionError); return; @@ -449,8 +420,7 @@ void MessageService::OpenChannelToNativeApp( std::unique_ptr<MessageChannel> channel(new MessageChannel()); channel->opener.reset( - new ExtensionMessagePort(weak_factory_.GetWeakPtr(), - GET_OPPOSITE_PORT_ID(receiver_port_id), + new ExtensionMessagePort(weak_factory_.GetWeakPtr(), source_port_id, extension->id(), source, false)); if (!channel->opener->IsValidPort()) return; @@ -487,13 +457,14 @@ void MessageService::OpenChannelToNativeApp( void MessageService::OpenChannelToTab(int source_process_id, int source_routing_id, - int receiver_port_id, + const PortId& source_port_id, int tab_id, int frame_id, const std::string& extension_id, const std::string& channel_name) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_GE(frame_id, -1); + DCHECK(source_port_id.is_opener); content::RenderFrameHost* source = content::RenderFrameHost::FromID(source_process_id, source_routing_id); @@ -504,6 +475,8 @@ void MessageService::OpenChannelToTab(int source_process_id, WebContents* contents = NULL; std::unique_ptr<MessagePort> receiver; + PortId receiver_port_id(source_port_id.context_id, source_port_id.port_number, + false); if (!ExtensionTabUtil::GetTabById(tab_id, profile, true, NULL, NULL, &contents, NULL) || contents->GetController().NeedsReload()) { @@ -572,10 +545,9 @@ void MessageService::OpenChannelImpl(BrowserContext* browser_context, return; } - std::unique_ptr<ExtensionMessagePort> opener( - new ExtensionMessagePort(weak_factory_.GetWeakPtr(), - GET_OPPOSITE_PORT_ID(params->receiver_port_id), - params->source_extension_id, source, false)); + std::unique_ptr<ExtensionMessagePort> opener(new ExtensionMessagePort( + weak_factory_.GetWeakPtr(), params->receiver_port_id.GetOppositePortId(), + params->source_extension_id, source, false)); if (!opener->IsValidPort()) return; opener->OpenPort(params->source_process_id, params->source_routing_id); @@ -594,11 +566,6 @@ void MessageService::OpenChannelImpl(BrowserContext* browser_context, channel->receiver.reset(params->receiver.release()); AddChannel(std::move(channel_ptr), params->receiver_port_id); - // TODO(robwu): Could |guest_process_id| and |guest_render_frame_routing_id| - // be removed? In the past extension message routing was process-based, but - // now that extensions are routed from a specific RFH, the special casing for - // guest views seems no longer necessary, because the ExtensionMessagePort can - // simply obtain the source process & frame ID directly from the RFH. int guest_process_id = content::ChildProcessHost::kInvalidUniqueID; int guest_render_frame_routing_id = MSG_ROUTING_NONE; if (params->include_guest_process_info) { @@ -654,20 +621,22 @@ void MessageService::OpenChannelImpl(BrowserContext* browser_context, } void MessageService::AddChannel(std::unique_ptr<MessageChannel> channel, - int receiver_port_id) { + const PortId& receiver_port_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - int channel_id = GET_CHANNEL_ID(receiver_port_id); + ChannelId channel_id = receiver_port_id.GetChannelId(); CHECK(channels_.find(channel_id) == channels_.end()); channels_[channel_id] = std::move(channel); pending_lazy_background_page_channels_.erase(channel_id); } -void MessageService::OpenPort(int port_id, int process_id, int routing_id) { +void MessageService::OpenPort(const PortId& port_id, + int process_id, + int routing_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(!IS_OPENER_PORT_ID(port_id)); + DCHECK(!port_id.is_opener); - int channel_id = GET_CHANNEL_ID(port_id); + ChannelId channel_id = port_id.GetChannelId(); MessageChannelMap::iterator it = channels_.find(channel_id); if (it == channels_.end()) return; @@ -675,26 +644,28 @@ void MessageService::OpenPort(int port_id, int process_id, int routing_id) { it->second->receiver->OpenPort(process_id, routing_id); } -void MessageService::ClosePort( - int port_id, int process_id, int routing_id, bool force_close) { +void MessageService::ClosePort(const PortId& port_id, + int process_id, + int routing_id, + bool force_close) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ClosePortImpl(port_id, process_id, routing_id, force_close, std::string()); } -void MessageService::CloseChannel(int port_id, +void MessageService::CloseChannel(const PortId& port_id, const std::string& error_message) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ClosePortImpl(port_id, content::ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE, true, error_message); } -void MessageService::ClosePortImpl(int port_id, +void MessageService::ClosePortImpl(const PortId& port_id, int process_id, int routing_id, bool force_close, const std::string& error_message) { // Note: The channel might be gone already, if the other side closed first. - int channel_id = GET_CHANNEL_ID(port_id); + ChannelId channel_id = port_id.GetChannelId(); MessageChannelMap::iterator it = channels_.find(channel_id); if (it == channels_.end()) { PendingLazyBackgroundPageChannelMap::iterator pending = @@ -714,18 +685,17 @@ void MessageService::ClosePortImpl(int port_id, // receivers, whereas closing a channel always forces all ports to be closed. if (force_close) { CloseChannelImpl(it, port_id, error_message, true); - } else if (IS_OPENER_PORT_ID(port_id)) { + } else if (port_id.is_opener) { it->second->opener->ClosePort(process_id, routing_id); } else { it->second->receiver->ClosePort(process_id, routing_id); } } -void MessageService::CloseChannelImpl( - MessageChannelMap::iterator channel_iter, - int closing_port_id, - const std::string& error_message, - bool notify_other_port) { +void MessageService::CloseChannelImpl(MessageChannelMap::iterator channel_iter, + const PortId& closing_port_id, + const std::string& error_message, + bool notify_other_port) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::unique_ptr<MessageChannel> channel = std::move(channel_iter->second); @@ -735,8 +705,8 @@ void MessageService::CloseChannelImpl( // Notify the other side. if (notify_other_port) { - MessagePort* port = IS_OPENER_PORT_ID(closing_port_id) ? - channel->receiver.get() : channel->opener.get(); + MessagePort* port = closing_port_id.is_opener ? channel->receiver.get() + : channel->opener.get(); port->DispatchOnDisconnect(error_message); } @@ -745,10 +715,11 @@ void MessageService::CloseChannelImpl( channel->receiver->DecrementLazyKeepaliveCount(); } -void MessageService::PostMessage(int source_port_id, const Message& message) { +void MessageService::PostMessage(const PortId& source_port_id, + const Message& message) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - int channel_id = GET_CHANNEL_ID(source_port_id); + ChannelId channel_id = source_port_id.GetChannelId(); MessageChannelMap::iterator iter = channels_.find(channel_id); if (iter == channels_.end()) { // If this channel is pending, queue up the PostMessage to run once @@ -760,8 +731,8 @@ void MessageService::PostMessage(int source_port_id, const Message& message) { DispatchMessage(source_port_id, iter->second.get(), message); } -void MessageService::EnqueuePendingMessage(int source_port_id, - int channel_id, +void MessageService::EnqueuePendingMessage(const PortId& source_port_id, + const ChannelId& channel_id, const Message& message) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -794,8 +765,8 @@ void MessageService::EnqueuePendingMessage(int source_port_id, } void MessageService::EnqueuePendingMessageForLazyBackgroundLoad( - int source_port_id, - int channel_id, + const PortId& source_port_id, + const ChannelId& channel_id, const Message& message) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -809,17 +780,16 @@ void MessageService::EnqueuePendingMessageForLazyBackgroundLoad( } } -void MessageService::DispatchMessage(int source_port_id, +void MessageService::DispatchMessage(const PortId& source_port_id, MessageChannel* channel, const Message& message) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // Figure out which port the ID corresponds to. - int dest_port_id = GET_OPPOSITE_PORT_ID(source_port_id); - MessagePort* port = IS_OPENER_PORT_ID(dest_port_id) ? - channel->opener.get() : channel->receiver.get(); + MessagePort* dest_port = source_port_id.is_opener ? channel->receiver.get() + : channel->opener.get(); - port->DispatchOnMessage(message); + dest_port->DispatchOnMessage(message); } bool MessageService::MaybeAddPendingLazyBackgroundPageOpenChannelTask( @@ -841,7 +811,7 @@ bool MessageService::MaybeAddPendingLazyBackgroundPageOpenChannelTask( if (!lazy_background_task_queue_->ShouldEnqueueTask(context, extension)) return false; - int channel_id = GET_CHANNEL_ID((*params)->receiver_port_id); + ChannelId channel_id = (*params)->receiver_port_id.GetChannelId(); pending_lazy_background_page_channels_[channel_id] = PendingLazyBackgroundPageChannel(context, extension->id()); int source_id = (*params)->source_process_id; @@ -862,7 +832,7 @@ void MessageService::OnOpenChannelAllowed( bool allowed) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - int channel_id = GET_CHANNEL_ID(params->receiver_port_id); + ChannelId channel_id = params->receiver_port_id.GetChannelId(); PendingChannelMap::iterator pending_for_incognito = pending_incognito_channels_.find(channel_id); @@ -944,7 +914,7 @@ void MessageService::GotChannelID(std::unique_ptr<OpenChannelParams> params, DCHECK_CURRENTLY_ON(BrowserThread::UI); params->tls_channel_id.assign(tls_channel_id); - int channel_id = GET_CHANNEL_ID(params->receiver_port_id); + ChannelId channel_id = params->receiver_port_id.GetChannelId(); PendingChannelMap::iterator pending_for_tls_channel_id = pending_tls_channel_id_channels_.find(channel_id); @@ -1000,19 +970,19 @@ void MessageService::PendingLazyBackgroundPageOpenChannel( } void MessageService::DispatchOnDisconnect(content::RenderFrameHost* source, - int port_id, + const PortId& port_id, const std::string& error_message) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ExtensionMessagePort port(weak_factory_.GetWeakPtr(), - GET_OPPOSITE_PORT_ID(port_id), "", source, false); + port_id.GetOppositePortId(), "", source, false); if (!port.IsValidPort()) return; port.DispatchOnDisconnect(error_message); } void MessageService::DispatchPendingMessages(const PendingMessagesQueue& queue, - int channel_id) { + const ChannelId& channel_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); MessageChannelMap::iterator channel_iter = channels_.find(channel_id); diff --git a/chromium/chrome/browser/extensions/api/messaging/message_service.h b/chromium/chrome/browser/extensions/api/messaging/message_service.h index 667594eb6cf..e5d5322ba24 100644 --- a/chromium/chrome/browser/extensions/api/messaging/message_service.h +++ b/chromium/chrome/browser/extensions/api/messaging/message_service.h @@ -19,10 +19,10 @@ #include "extensions/browser/api/messaging/native_message_host.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/common/api/messaging/message.h" +#include "extensions/common/api/messaging/port_id.h" #include "extensions/common/extension_id.h" class GURL; -class Profile; namespace content { class BrowserContext; @@ -123,10 +123,6 @@ class MessageService : public BrowserContextKeyedAPI { const PrefService* pref_service, const std::string& native_host_name); - // Allocates a pair of port ids. - // NOTE: this can be called from any thread. - static void AllocatePortIdPair(int* port1, int* port2); - explicit MessageService(content::BrowserContext* context); ~MessageService() override; @@ -139,46 +135,49 @@ class MessageService : public BrowserContextKeyedAPI { // Given an extension's ID, opens a channel between the given renderer "port" // and every listening context owned by that extension. |channel_name| is // an optional identifier for use by extension developers. - void OpenChannelToExtension( - int source_process_id, int source_routing_id, int receiver_port_id, - const std::string& source_extension_id, - const std::string& target_extension_id, - const GURL& source_url, - const std::string& channel_name, - bool include_tls_channel_id); + void OpenChannelToExtension(int source_process_id, + int source_routing_id, + const PortId& source_port_id, + const std::string& source_extension_id, + const std::string& target_extension_id, + const GURL& source_url, + const std::string& channel_name, + bool include_tls_channel_id); // Same as above, but opens a channel to the tab with the given ID. Messages // are restricted to that tab, so if there are multiple tabs in that process, // only the targeted tab will receive messages. void OpenChannelToTab(int source_process_id, int source_routing_id, - int receiver_port_id, + const PortId& source_port_id, int tab_id, int frame_id, const std::string& extension_id, const std::string& channel_name); - void OpenChannelToNativeApp( - int source_process_id, - int source_routing_id, - int receiver_port_id, - const std::string& native_app_name); + void OpenChannelToNativeApp(int source_process_id, + int source_routing_id, + const PortId& source_port_id, + const std::string& native_app_name); // Mark the given port as opened by the frame identified by // (process_id, routing_id). - void OpenPort(int port_id, int process_id, int routing_id); + void OpenPort(const PortId& port_id, int process_id, int routing_id); // Closes the given port in the given frame. If this was the last frame or if // |force_close| is true, then the other side is closed as well. - void ClosePort(int port_id, int process_id, int routing_id, bool force_close); + void ClosePort(const PortId& port_id, + int process_id, + int routing_id, + bool force_close); // Closes the message channel associated with the given port, and notifies // the other side. - void CloseChannel(int port_id, const std::string& error_message); + void CloseChannel(const PortId& port_id, const std::string& error_message); // Enqueues a message on a pending channel, or sends a message to the given // port if the channel isn't pending. - void PostMessage(int port_id, const Message& message); + void PostMessage(const PortId& port_id, const Message& message); private: friend class MockMessageService; @@ -186,20 +185,21 @@ class MessageService : public BrowserContextKeyedAPI { struct OpenChannelParams; // A map of channel ID to its channel object. - using MessageChannelMap = std::map<int, std::unique_ptr<MessageChannel>>; + using MessageChannelMap = + std::map<ChannelId, std::unique_ptr<MessageChannel>>; - using PendingMessage = std::pair<int, Message>; + using PendingMessage = std::pair<PortId, Message>; using PendingMessagesQueue = std::vector<PendingMessage>; // A set of channel IDs waiting to complete opening, and any pending messages // queued to be sent on those channels. - using PendingChannelMap = std::map<int, PendingMessagesQueue>; + using PendingChannelMap = std::map<ChannelId, PendingMessagesQueue>; // A map of channel ID to information about the extension that is waiting // for that channel to open. Used for lazy background pages. using PendingLazyBackgroundPageChannel = std::pair<content::BrowserContext*, ExtensionId>; using PendingLazyBackgroundPageChannelMap = - std::map<int, PendingLazyBackgroundPageChannel>; + std::map<ChannelId, PendingLazyBackgroundPageChannel>; // Common implementation for opening a channel configured by |params|. // @@ -213,21 +213,21 @@ class MessageService : public BrowserContextKeyedAPI { const Extension* target_extension, bool did_enqueue); - void ClosePortImpl(int port_id, + void ClosePortImpl(const PortId& port_id, int process_id, int routing_id, bool force_close, const std::string& error_message); void CloseChannelImpl(MessageChannelMap::iterator channel_iter, - int port_id, + const PortId& port_id, const std::string& error_message, bool notify_other_port); // Have MessageService take ownership of |channel|, and remove any pending // channels with the same id. void AddChannel(std::unique_ptr<MessageChannel> channel, - int receiver_port_id); + const PortId& receiver_port_id); // If the channel is being opened from an incognito tab the user must allow // the connection. @@ -237,16 +237,18 @@ class MessageService : public BrowserContextKeyedAPI { const std::string& tls_channel_id); // Enqueues a message on a pending channel. - void EnqueuePendingMessage(int port_id, int channel_id, + void EnqueuePendingMessage(const PortId& port_id, + const ChannelId& channel_id, const Message& message); // Enqueues a message on a channel pending on a lazy background page load. - void EnqueuePendingMessageForLazyBackgroundLoad(int port_id, - int channel_id, + void EnqueuePendingMessageForLazyBackgroundLoad(const PortId& port_id, + const ChannelId& channel_id, const Message& message); // Immediately sends a message to the given port. - void DispatchMessage(int port_id, MessageChannel* channel, + void DispatchMessage(const PortId& port_id, + MessageChannel* channel, const Message& message); // Potentially registers a pending task with the LazyBackgroundTaskQueue @@ -265,7 +267,7 @@ class MessageService : public BrowserContextKeyedAPI { std::unique_ptr<OpenChannelParams> params, int source_process_id, extensions::ExtensionHost* host); - void PendingLazyBackgroundPageClosePort(int port_id, + void PendingLazyBackgroundPageClosePort(const PortId& port_id, int process_id, int routing_id, bool force_close, @@ -275,7 +277,7 @@ class MessageService : public BrowserContextKeyedAPI { ClosePortImpl(port_id, process_id, routing_id, force_close, error_message); } - void PendingLazyBackgroundPagePostMessage(int port_id, + void PendingLazyBackgroundPagePostMessage(const PortId& port_id, const Message& message, extensions::ExtensionHost* host) { if (host) @@ -285,11 +287,11 @@ class MessageService : public BrowserContextKeyedAPI { // Immediate dispatches a disconnect to |source| for |port_id|. Sets source's // runtime.lastMessage to |error_message|, if any. void DispatchOnDisconnect(content::RenderFrameHost* source, - int port_id, + const PortId& port_id, const std::string& error_message); void DispatchPendingMessages(const PendingMessagesQueue& queue, - int channel_id); + const ChannelId& channel_id); // BrowserContextKeyedAPI implementation. static const char* service_name() { diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc index ab9e4ac2264..d41cb9fed36 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_message_port.cc @@ -86,7 +86,7 @@ void NativeMessagePort::Core::CloseChannel(const std::string& error_message) { NativeMessagePort::NativeMessagePort( base::WeakPtr<MessageService> message_service, - int port_id, + const PortId& port_id, std::unique_ptr<NativeMessageHost> native_message_host) : weak_message_service_(message_service), host_task_runner_(native_message_host->task_runner()), diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_port.h b/chromium/chrome/browser/extensions/api/messaging/native_message_port.h index 9437d35be7a..ecfa6ac9f1f 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_message_port.h +++ b/chromium/chrome/browser/extensions/api/messaging/native_message_port.h @@ -7,16 +7,16 @@ #include "base/threading/thread_checker.h" #include "chrome/browser/extensions/api/messaging/message_service.h" +#include "extensions/common/api/messaging/port_id.h" namespace extensions { -class NativeMessageProcessHost; // A port that manages communication with a native application. // All methods must be called on the UI Thread of the browser process. class NativeMessagePort : public MessageService::MessagePort { public: NativeMessagePort(base::WeakPtr<MessageService> message_service, - int port_id, + const PortId& port_id, std::unique_ptr<NativeMessageHost> native_message_host); ~NativeMessagePort() override; @@ -32,7 +32,7 @@ class NativeMessagePort : public MessageService::MessagePort { base::ThreadChecker thread_checker_; base::WeakPtr<MessageService> weak_message_service_; scoped_refptr<base::SingleThreadTaskRunner> host_task_runner_; - int port_id_; + const PortId port_id_; std::unique_ptr<Core> core_; base::WeakPtrFactory<NativeMessagePort> weak_factory_; diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc index fee82b6c469..bb153dc8f1a 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.cc @@ -21,7 +21,7 @@ NativeMessagingHostListPolicyHandler::NativeMessagingHostListPolicyHandler( const char* policy_name, const char* pref_path, bool allow_wildcards) - : policy::TypeCheckingPolicyHandler(policy_name, base::Value::TYPE_LIST), + : policy::TypeCheckingPolicyHandler(policy_name, base::Value::Type::LIST), pref_path_(pref_path), allow_wildcards_(allow_wildcards) {} @@ -71,7 +71,7 @@ bool NativeMessagingHostListPolicyHandler::CheckAndGetList( if (!(*entry)->GetAsString(&name)) { errors->AddError(policy_name(), entry - list_value->begin(), IDS_POLICY_TYPE_ERROR, - base::Value::GetTypeName(base::Value::TYPE_STRING)); + base::Value::GetTypeName(base::Value::Type::STRING)); continue; } if (!(allow_wildcards_ && name == "*") && diff --git a/chromium/chrome/browser/extensions/api/music_manager_private/device_id_win.cc b/chromium/chrome/browser/extensions/api/music_manager_private/device_id_win.cc index 90814d7f8f5..6455e9a8f86 100644 --- a/chromium/chrome/browser/extensions/api/music_manager_private/device_id_win.cc +++ b/chromium/chrome/browser/extensions/api/music_manager_private/device_id_win.cc @@ -25,8 +25,9 @@ #include "base/threading/thread_restrictions.h" #include "base/win/windows_version.h" #include "content/public/browser/browser_thread.h" +#include "rlz/features/features.h" -#if defined(ENABLE_RLZ) +#if BUILDFLAG(ENABLE_RLZ) #include "rlz/lib/machine_id.h" #endif @@ -183,13 +184,13 @@ void GetMacAddress(const IsValidMacAddressCallback& is_valid_mac_address, } std::string GetRlzMachineId() { -#if defined(ENABLE_RLZ) +#if BUILDFLAG(ENABLE_RLZ) std::string machine_id; if (!rlz_lib::GetMachineId(&machine_id)) - return ""; + return std::string(); return machine_id; #else - return ""; + return std::string(); #endif } diff --git a/chromium/chrome/browser/extensions/api/music_manager_private/music_manager_private_browsertest.cc b/chromium/chrome/browser/extensions/api/music_manager_private/music_manager_private_browsertest.cc index 27e7bc95024..40a360bfd06 100644 --- a/chromium/chrome/browser/extensions/api/music_manager_private/music_manager_private_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/music_manager_private/music_manager_private_browsertest.cc @@ -5,9 +5,10 @@ #include "build/build_config.h" #include "chrome/browser/apps/app_browsertest_util.h" #include "extensions/test/extension_test_message_listener.h" +#include "rlz/features/features.h" // Supported on all platforms, but on Windows only if RLZ is enabled. -#if !defined(OS_WIN) || defined(ENABLE_RLZ) +#if !defined(OS_WIN) || BUILDFLAG(ENABLE_RLZ) class MusicManagerPrivateTest : public extensions::PlatformAppBrowserTest { }; diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc index 02d6d1abc93..d8d0b782e43 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc @@ -183,6 +183,10 @@ class TestDelegate : public NetworkingPrivateDelegate { return result; } + std::unique_ptr<base::DictionaryValue> GetGlobalPolicy() override { + return base::MakeUnique<base::DictionaryValue>(); + } + bool EnableNetworkType(const std::string& type) override { enabled_[type] = true; return !fail_; @@ -462,6 +466,10 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateApiTest, SetCellularSimState) { EXPECT_TRUE(RunNetworkingSubtest("setCellularSimState")) << message_; } +IN_PROC_BROWSER_TEST_F(NetworkingPrivateApiTest, GetGlobalPolicy) { + EXPECT_TRUE(RunNetworkingSubtest("getGlobalPolicy")) << message_; +} + // Test failure case class NetworkingPrivateApiTestFail : public NetworkingPrivateApiTest { @@ -516,6 +524,7 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateApiTestFail, GetDeviceStates) { // * disableNetworkType // * enableNetworkType // * requestNetworkScan +// * getGlobalPolicy IN_PROC_BROWSER_TEST_F(NetworkingPrivateApiTestFail, StartConnect) { EXPECT_FALSE(RunNetworkingSubtest("startConnect")) << message_; diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc index 6d22232e525..f1918f2ae4d 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc @@ -9,6 +9,8 @@ #include "base/callback.h" #include "base/command_line.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "base/strings/stringprintf.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/login/helper.h" #include "chrome/browser/chromeos/net/network_portal_detector_test_impl.h" @@ -24,6 +26,7 @@ #include "chromeos/dbus/shill_manager_client.h" #include "chromeos/dbus/shill_profile_client.h" #include "chromeos/dbus/shill_service_client.h" +#include "chromeos/network/managed_network_configuration_handler.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/onc/onc_utils.h" @@ -167,10 +170,11 @@ class NetworkingPrivateChromeOSApiTest : public ExtensionApiTest { service_test_(nullptr), device_test_(nullptr) {} - bool RunNetworkingSubtest(const std::string& subtest) { - return RunExtensionSubtest("networking_private/chromeos", - "main.html?" + subtest, - kFlagEnableFileAccess | kFlagLoadAsComponent); + bool RunNetworkingSubtest(const std::string& test) { + const std::string arg = + base::StringPrintf("{\"test\": \"%s\"}", test.c_str()); + return RunPlatformAppTestWithArg("networking_private/chromeos", + arg.c_str()); } void SetUpInProcessBrowserTestFixture() override { @@ -713,4 +717,29 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, CellularSimPuk) { EXPECT_TRUE(RunNetworkingSubtest("cellularSimPuk")) << message_; } +IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, GetGlobalPolicy) { + base::DictionaryValue global_config; + global_config.SetBooleanWithoutPathExpansion( + ::onc::global_network_config::kAllowOnlyPolicyNetworksToAutoconnect, + true); + global_config.SetBooleanWithoutPathExpansion( + ::onc::global_network_config::kAllowOnlyPolicyNetworksToConnect, false); + global_config.SetBooleanWithoutPathExpansion("SomeNewGlobalPolicy", false); + chromeos::NetworkHandler::Get() + ->managed_network_configuration_handler() + ->SetPolicy(::onc::ONC_SOURCE_DEVICE_POLICY, + std::string() /* no username hash */, base::ListValue(), + global_config); + base::RunLoop().RunUntilIdle(); + + EXPECT_TRUE(RunNetworkingSubtest("getGlobalPolicy")) << message_; +} + +// Tests subset of networking API for the networking API alias - to verify that +// using API methods and event does not cause access exceptions (due to +// missing permissions). +IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, Alias) { + EXPECT_TRUE(RunPlatformAppTest("networking_private/alias")) << message_; +} + } // namespace diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_browsertest.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_browsertest.cc new file mode 100644 index 00000000000..5e1e31fb73d --- /dev/null +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_browsertest.cc @@ -0,0 +1,79 @@ +// Copyright 2017 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 "base/bind.h" +#include "base/callback.h" +#include "base/macros.h" +#include "base/run_loop.h" +#include "chrome/browser/extensions/api/networking_private/networking_private_credentials_getter.h" +#include "chrome/common/extensions/wifi_credentials_getter.mojom.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "content/public/browser/browser_thread.h" + +#if !defined(OS_WIN) +#error This test is OS_WIN only. +#endif + +class NetworkingPrivateCredentialsGetterTest : public InProcessBrowserTest { + public: + NetworkingPrivateCredentialsGetterTest() = default; + + void RunTest(bool use_test_network) { + base::RunLoop run_loop; + quit_closure_ = run_loop.QuitClosure(); + + if (use_test_network) + network_ = extensions::mojom::WiFiCredentialsGetter::kWiFiTestNetwork; + + done_called_ = false; + content::BrowserThread::PostBlockingPoolTask( + FROM_HERE, + base::Bind(&NetworkingPrivateCredentialsGetterTest::GetCredentials, + base::Unretained(this))); + run_loop.Run(); + + EXPECT_TRUE(done_called_); + } + + private: + void GetCredentials() { + std::unique_ptr<extensions::NetworkingPrivateCredentialsGetter> getter( + extensions::NetworkingPrivateCredentialsGetter::Create()); + getter->Start( + network_, "public_key", + base::Bind(&NetworkingPrivateCredentialsGetterTest::CredentialsDone, + base::Unretained(this))); + } + + void CredentialsDone(const std::string& key_data, const std::string& error) { + done_called_ = true; + + if (!network_.empty()) { + EXPECT_EQ(network_, key_data); + EXPECT_EQ("", error); + } else { + EXPECT_EQ("", key_data); + EXPECT_FALSE(error.empty()); + } + + content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, + quit_closure_); + } + + base::Closure quit_closure_; + std::string network_; + bool done_called_; + + DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateCredentialsGetterTest); +}; + +IN_PROC_BROWSER_TEST_F(NetworkingPrivateCredentialsGetterTest, + GetCredentialsSuccess) { + RunTest(true); +} + +IN_PROC_BROWSER_TEST_F(NetworkingPrivateCredentialsGetterTest, + GetCredentialsFailure) { + RunTest(false); +} diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_win.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_win.cc index b5a047d769f..824a4a217bd 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_win.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_win.cc @@ -10,113 +10,123 @@ #include "base/bind.h" #include "base/macros.h" #include "base/strings/string_piece.h" -#include "base/strings/stringprintf.h" -#include "base/threading/sequenced_worker_pool.h" -#include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/extensions/api/networking_private/networking_private_crypto.h" -#include "chrome/common/extensions/chrome_utility_extensions_messages.h" +#include "chrome/common/extensions/wifi_credentials_getter.mojom.h" #include "chrome/grit/generated_resources.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/utility_process_host.h" -#include "content/public/browser/utility_process_host_client.h" +#include "content/public/browser/utility_process_mojo_client.h" #include "ui/base/l10n/l10n_util.h" -using content::BrowserThread; -using content::UtilityProcessHost; -using content::UtilityProcessHostClient; -using extensions::NetworkingPrivateCredentialsGetter; - namespace { -class CredentialsGetterHostClient : public UtilityProcessHostClient { - public: - explicit CredentialsGetterHostClient(const std::string& public_key); - - // UtilityProcessHostClient - bool OnMessageReceived(const IPC::Message& message) override; - void OnProcessCrashed(int exit_code) override; - void OnProcessLaunchFailed(int error_code) override; +using extensions::NetworkingPrivateCredentialsGetter; - // IPC message handlers. - void OnGotCredentials(const std::string& key_data, bool success); +class CredentialsGetterHostClient { + public: + static CredentialsGetterHostClient* Create(const std::string& public_key) { + return new CredentialsGetterHostClient(public_key); + } - // Starts the utility process that gets wifi passphrase from system. - void StartProcessOnIOThread( + void GetWiFiCredentialsOnIOThread( const std::string& network_guid, const NetworkingPrivateCredentialsGetter::CredentialsCallback& callback); private: - ~CredentialsGetterHostClient() override; + explicit CredentialsGetterHostClient(const std::string& public_key) + : public_key_(public_key.begin(), public_key.end()) {} + + ~CredentialsGetterHostClient() = default; + + // Credentials result handler. + void GetWiFiCredentialsDone(bool success, const std::string& key_data); + + // Report the result to |callback_|. + void ReportResult(bool success, const std::string& key_data); - // Public key used to encrypt results + // Public key used to encrypt the result. std::vector<uint8_t> public_key_; - // Callback for reporting the result. + // Callback for reporting the encrypted result. NetworkingPrivateCredentialsGetter::CredentialsCallback callback_; + // Utility process used to get the credentials. + std::unique_ptr<content::UtilityProcessMojoClient< + extensions::mojom::WiFiCredentialsGetter>> + utility_process_mojo_client_; + + // WiFi network to get the credentials from. + std::string wifi_network_; + DISALLOW_COPY_AND_ASSIGN(CredentialsGetterHostClient); }; -CredentialsGetterHostClient::CredentialsGetterHostClient( - const std::string& public_key) - : public_key_(public_key.begin(), public_key.end()) { -} +void CredentialsGetterHostClient::GetWiFiCredentialsOnIOThread( + const std::string& network_guid, + const NetworkingPrivateCredentialsGetter::CredentialsCallback& callback) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + DCHECK(!utility_process_mojo_client_); + DCHECK(!callback.is_null()); -bool CredentialsGetterHostClient::OnMessageReceived( - const IPC::Message& message) { - bool handled = true; - IPC_BEGIN_MESSAGE_MAP(CredentialsGetterHostClient, message) - IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_GotWiFiCredentials, OnGotCredentials) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - return handled; -} + wifi_network_ = network_guid; + callback_ = callback; + + const base::string16 utility_process_name = l10n_util::GetStringUTF16( + IDS_UTILITY_PROCESS_WIFI_CREDENTIALS_GETTER_NAME); + + utility_process_mojo_client_.reset( + new content::UtilityProcessMojoClient< + extensions::mojom::WiFiCredentialsGetter>(utility_process_name)); + utility_process_mojo_client_->set_error_callback( + base::Bind(&CredentialsGetterHostClient::GetWiFiCredentialsDone, + base::Unretained(this), false, std::string())); + + utility_process_mojo_client_->set_run_elevated(); -void CredentialsGetterHostClient::OnProcessCrashed(int exit_code) { - callback_.Run( - "", base::StringPrintf("Process Crashed with code %08x.", exit_code)); + utility_process_mojo_client_->Start(); // Start the utility process. + + utility_process_mojo_client_->service()->GetWiFiCredentials( + wifi_network_, + base::Bind(&CredentialsGetterHostClient::GetWiFiCredentialsDone, + base::Unretained(this))); } -void CredentialsGetterHostClient::OnProcessLaunchFailed(int error_code) { - callback_.Run("", base::StringPrintf("Process Launch Failed with code %08x.", - error_code)); +void CredentialsGetterHostClient::GetWiFiCredentialsDone( + bool success, + const std::string& key_data) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); + + utility_process_mojo_client_.reset(); // Terminate the utility process. + ReportResult(success, key_data); + delete this; } -void CredentialsGetterHostClient::OnGotCredentials(const std::string& key_data, - bool success) { - if (success) { - std::vector<uint8_t> ciphertext; - if (!networking_private_crypto::EncryptByteString( - public_key_, key_data, &ciphertext)) { - callback_.Run("", "Encrypt Credentials Failed"); - return; - } - - std::string base64_encoded_key_data; - base::Base64Encode( - base::StringPiece(reinterpret_cast<const char*>(ciphertext.data()), - ciphertext.size()), - &base64_encoded_key_data); - callback_.Run(base64_encoded_key_data, ""); - } else { - callback_.Run("", "Get Credentials Failed"); +void CredentialsGetterHostClient::ReportResult(bool success, + const std::string& key_data) { + if (!success) { + callback_.Run(std::string(), "Get Credentials Failed"); + return; } -} -void CredentialsGetterHostClient::StartProcessOnIOThread( - const std::string& network_guid, - const NetworkingPrivateCredentialsGetter::CredentialsCallback& callback) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - callback_ = callback; - UtilityProcessHost* host = - UtilityProcessHost::Create(this, base::ThreadTaskRunnerHandle::Get()); - host->SetName(l10n_util::GetStringUTF16( - IDS_UTILITY_PROCESS_WIFI_CREDENTIALS_GETTER_NAME)); - host->ElevatePrivileges(); - host->Send(new ChromeUtilityHostMsg_GetWiFiCredentials(network_guid)); -} + if (wifi_network_ == + extensions::mojom::WiFiCredentialsGetter::kWiFiTestNetwork) { + DCHECK_EQ(wifi_network_, key_data); + callback_.Run(key_data, std::string()); + return; + } + + std::vector<uint8_t> ciphertext; + if (!networking_private_crypto::EncryptByteString(public_key_, key_data, + &ciphertext)) { + callback_.Run(std::string(), "Encrypt Credentials Failed"); + return; + } -CredentialsGetterHostClient::~CredentialsGetterHostClient() { + std::string base64_encoded_key_data; + base::Base64Encode( + base::StringPiece(reinterpret_cast<const char*>(ciphertext.data()), + ciphertext.size()), + &base64_encoded_key_data); + callback_.Run(base64_encoded_key_data, std::string()); } } // namespace @@ -126,36 +136,34 @@ namespace extensions { class NetworkingPrivateCredentialsGetterWin : public NetworkingPrivateCredentialsGetter { public: - NetworkingPrivateCredentialsGetterWin(); + NetworkingPrivateCredentialsGetterWin() = default; void Start(const std::string& network_guid, const std::string& public_key, - const CredentialsCallback& callback) override; + const CredentialsCallback& callback) override { + content::BrowserThread::PostTask( + content::BrowserThread::IO, FROM_HERE, + base::Bind( + &NetworkingPrivateCredentialsGetterWin::GetCredentialsOnIOThread, + network_guid, public_key, callback)); + } private: - ~NetworkingPrivateCredentialsGetterWin() override; + ~NetworkingPrivateCredentialsGetterWin() override = default; - DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateCredentialsGetterWin); -}; - -NetworkingPrivateCredentialsGetterWin::NetworkingPrivateCredentialsGetterWin() { -} + static void GetCredentialsOnIOThread(const std::string& network_guid, + const std::string& public_key, + const CredentialsCallback& callback) { + DCHECK_CURRENTLY_ON(content::BrowserThread::IO); -void NetworkingPrivateCredentialsGetterWin::Start( - const std::string& network_guid, - const std::string& public_key, - const CredentialsCallback& callback) { - BrowserThread::PostTask( - BrowserThread::IO, - FROM_HERE, - base::Bind(&CredentialsGetterHostClient::StartProcessOnIOThread, - new CredentialsGetterHostClient(public_key), - network_guid, - callback)); -} + // CredentialsGetterHostClient is self deleting. + CredentialsGetterHostClient* client = + CredentialsGetterHostClient::Create(public_key); + client->GetWiFiCredentialsOnIOThread(network_guid, callback); + } -NetworkingPrivateCredentialsGetterWin:: - ~NetworkingPrivateCredentialsGetterWin() {} + DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateCredentialsGetterWin); +}; NetworkingPrivateCredentialsGetter* NetworkingPrivateCredentialsGetter::Create() { diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_crypto_unittest.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_crypto_unittest.cc index 79c790efdde..1afe9ce7448 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_crypto_unittest.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_crypto_unittest.cc @@ -7,7 +7,6 @@ #include "base/base64.h" #include "base/logging.h" -#include "base/strings/stringprintf.h" #include "testing/gtest/include/gtest/gtest.h" namespace { diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc index b03ea5d26f6..39abdd96447 100644 --- a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc +++ b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc @@ -278,7 +278,7 @@ IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestGetPermissionLevel) { std::unique_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult( notification_function.get(), "[]", browser(), utils::NONE)); - EXPECT_EQ(base::Value::TYPE_STRING, result->GetType()); + EXPECT_EQ(base::Value::Type::STRING, result->GetType()); std::string permission_level; EXPECT_TRUE(result->GetAsString(&permission_level)); EXPECT_EQ("granted", permission_level); @@ -303,7 +303,7 @@ IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestGetPermissionLevel) { std::unique_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult( notification_function.get(), "[]", browser(), utils::NONE)); - EXPECT_EQ(base::Value::TYPE_STRING, result->GetType()); + EXPECT_EQ(base::Value::Type::STRING, result->GetType()); std::string permission_level; EXPECT_TRUE(result->GetAsString(&permission_level)); EXPECT_EQ("denied", permission_level); diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc index 5212b3588e7..d954ed0be43 100644 --- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc +++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc @@ -45,17 +45,6 @@ const char kBackgroundTabDisposition[] = "newBackgroundTab"; // Pref key for omnibox.setDefaultSuggestion. const char kOmniboxDefaultSuggestion[] = "omnibox_default_suggestion"; -#if defined(OS_LINUX) -static const int kOmniboxIconPaddingLeft = 2; -static const int kOmniboxIconPaddingRight = 2; -#elif defined(OS_MACOSX) -static const int kOmniboxIconPaddingLeft = 0; -static const int kOmniboxIconPaddingRight = 2; -#else -static const int kOmniboxIconPaddingLeft = 0; -static const int kOmniboxIconPaddingRight = 0; -#endif - std::unique_ptr<omnibox::SuggestResult> GetOmniboxDefaultSuggestion( Profile* profile, const std::string& extension_id) { @@ -195,10 +184,7 @@ OmniboxAPI::OmniboxAPI(content::BrowserContext* context) } // Use monochrome icons for Omnibox icons. - omnibox_popup_icon_manager_.set_monochrome(true); omnibox_icon_manager_.set_monochrome(true); - omnibox_icon_manager_.set_padding(gfx::Insets(0, kOmniboxIconPaddingLeft, - 0, kOmniboxIconPaddingRight)); } void OmniboxAPI::Shutdown() { @@ -226,7 +212,6 @@ void OmniboxAPI::OnExtensionLoaded(content::BrowserContext* browser_context, const std::string& keyword = OmniboxInfo::GetKeyword(extension); if (!keyword.empty()) { // Load the omnibox icon so it will be ready to display in the URL bar. - omnibox_popup_icon_manager_.LoadIcon(profile_, extension); omnibox_icon_manager_.LoadIcon(profile_, extension); if (url_service_) { @@ -256,13 +241,7 @@ void OmniboxAPI::OnExtensionUnloaded(content::BrowserContext* browser_context, } gfx::Image OmniboxAPI::GetOmniboxIcon(const std::string& extension_id) { - return gfx::Image::CreateFrom1xBitmap( - omnibox_icon_manager_.GetIcon(extension_id)); -} - -gfx::Image OmniboxAPI::GetOmniboxPopupIcon(const std::string& extension_id) { - return gfx::Image::CreateFrom1xBitmap( - omnibox_popup_icon_manager_.GetIcon(extension_id)); + return omnibox_icon_manager_.GetIcon(extension_id); } void OmniboxAPI::OnTemplateURLsLoaded() { diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h index 09678937945..5fbec3e645d 100644 --- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h +++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h @@ -25,10 +25,6 @@ class Profile; class TemplateURL; class TemplateURLService; -namespace base { -class ListValue; -} - namespace content { class BrowserContext; class WebContents; @@ -99,13 +95,10 @@ class OmniboxAPI : public BrowserContextKeyedAPI, // KeyedService implementation. void Shutdown() override; - // Returns the icon to display in the omnibox for the given extension. + // Returns the icon to display in the location bar or omnibox popup for the + // given extension. gfx::Image GetOmniboxIcon(const std::string& extension_id); - // Returns the icon to display in the omnibox popup window for the given - // extension. - gfx::Image GetOmniboxPopupIcon(const std::string& extension_id); - private: friend class BrowserContextKeyedAPIFactory<OmniboxAPI>; @@ -140,7 +133,6 @@ class OmniboxAPI : public BrowserContextKeyedAPI, // Keeps track of favicon-sized omnibox icons for extensions. ExtensionIconManager omnibox_icon_manager_; - ExtensionIconManager omnibox_popup_icon_manager_; std::unique_ptr<TemplateURLService::Subscription> template_url_sub_; diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h index 7faeddd4f7a..0cb1e04da72 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h @@ -19,12 +19,6 @@ #include "components/keyed_service/core/keyed_service.h" #include "extensions/browser/extension_function.h" -class Profile; - -namespace base { -class Value; -} - namespace content { class WebContents; } diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers.h b/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers.h index 4e06564f321..8990b388ee2 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers.h +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers.h @@ -10,10 +10,6 @@ #include "base/memory/ref_counted.h" -namespace base { -class DictionaryValue; -} - namespace extensions { class PermissionSet; diff --git a/chromium/chrome/browser/extensions/api/preference/preference_api.cc b/chromium/chrome/browser/extensions/api/preference/preference_api.cc index 025bf3a80c9..5b0c0ec1be9 100644 --- a/chromium/chrome/browser/extensions/api/preference/preference_api.cc +++ b/chromium/chrome/browser/extensions/api/preference/preference_api.cc @@ -47,6 +47,7 @@ #include "extensions/common/error_utils.h" #include "extensions/common/permissions/api_permission.h" #include "extensions/common/permissions/permissions_data.h" +#include "media/media_features.h" namespace keys = extensions::preference_api_constants; namespace helpers = extensions::preference_helpers; @@ -103,7 +104,7 @@ PrefMappingEntry kPrefMapping[] = { {"networkPredictionEnabled", prefs::kNetworkPredictionOptions, APIPermission::kPrivacy, APIPermission::kPrivacy}, {"passwordSavingEnabled", - password_manager::prefs::kPasswordManagerSavingEnabled, + password_manager::prefs::kCredentialsEnableService, APIPermission::kPrivacy, APIPermission::kPrivacy}, {"protectedContentEnabled", prefs::kEnableDRM, APIPermission::kPrivacy, APIPermission::kPrivacy}, @@ -124,7 +125,7 @@ PrefMappingEntry kPrefMapping[] = { APIPermission::kPrivacy, APIPermission::kPrivacy}, {"translationServiceEnabled", prefs::kEnableTranslate, APIPermission::kPrivacy, APIPermission::kPrivacy}, -#if defined(ENABLE_WEBRTC) +#if BUILDFLAG(ENABLE_WEBRTC) // webRTCMultipleRoutesEnabled and webRTCNonProxiedUdpEnabled have been // replaced by webRTCIPHandlingPolicy. Leaving it for backward // compatibility. TODO(guoweis): Remove this in M50. diff --git a/chromium/chrome/browser/extensions/api/preference/preference_apitest.cc b/chromium/chrome/browser/extensions/api/preference/preference_apitest.cc index 6d2a5bad5bb..98672cf9df3 100644 --- a/chromium/chrome/browser/extensions/api/preference/preference_apitest.cc +++ b/chromium/chrome/browser/extensions/api/preference/preference_apitest.cc @@ -32,6 +32,7 @@ #include "extensions/browser/test_extension_registry_observer.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" +#include "media/media_features.h" class ExtensionPreferenceApiTest : public ExtensionApiTest { protected: @@ -51,8 +52,8 @@ class ExtensionPreferenceApiTest : public ExtensionApiTest { EXPECT_TRUE(prefs->GetBoolean(prefs::kEnableTranslate)); EXPECT_EQ(chrome_browser_net::NETWORK_PREDICTION_DEFAULT, prefs->GetInteger(prefs::kNetworkPredictionOptions)); - EXPECT_TRUE(prefs->GetBoolean( - password_manager::prefs::kPasswordManagerSavingEnabled)); + EXPECT_TRUE( + prefs->GetBoolean(password_manager::prefs::kCredentialsEnableService)); EXPECT_TRUE(prefs->GetBoolean(prefs::kSafeBrowsingEnabled)); EXPECT_TRUE(prefs->GetBoolean(prefs::kSearchSuggestEnabled)); } @@ -71,8 +72,8 @@ class ExtensionPreferenceApiTest : public ExtensionApiTest { EXPECT_FALSE(prefs->GetBoolean(prefs::kEnableTranslate)); EXPECT_EQ(chrome_browser_net::NETWORK_PREDICTION_NEVER, prefs->GetInteger(prefs::kNetworkPredictionOptions)); - EXPECT_FALSE(prefs->GetBoolean( - password_manager::prefs::kPasswordManagerSavingEnabled)); + EXPECT_FALSE( + prefs->GetBoolean(password_manager::prefs::kCredentialsEnableService)); EXPECT_FALSE(prefs->GetBoolean(prefs::kSafeBrowsingEnabled)); EXPECT_FALSE(prefs->GetBoolean(prefs::kSearchSuggestEnabled)); } @@ -122,11 +123,10 @@ IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, MAYBE_Standard) { prefs->SetBoolean(prefs::kEnableTranslate, false); prefs->SetInteger(prefs::kNetworkPredictionOptions, chrome_browser_net::NETWORK_PREDICTION_NEVER); - prefs->SetBoolean(password_manager::prefs::kPasswordManagerSavingEnabled, - false); + prefs->SetBoolean(password_manager::prefs::kCredentialsEnableService, false); prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false); prefs->SetBoolean(prefs::kSearchSuggestEnabled, false); -#if defined(ENABLE_WEBRTC) +#if BUILDFLAG(ENABLE_WEBRTC) prefs->SetBoolean(prefs::kWebRTCMultipleRoutesEnabled, false); prefs->SetBoolean(prefs::kWebRTCNonProxiedUdpEnabled, false); prefs->SetString(prefs::kWebRTCIPHandlingPolicy, diff --git a/chromium/chrome/browser/extensions/api/processes/processes_api.cc b/chromium/chrome/browser/extensions/api/processes/processes_api.cc index e43d5df24e9..fe041297856 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_api.cc +++ b/chromium/chrome/browser/extensions/api/processes/processes_api.cc @@ -60,7 +60,7 @@ std::unique_ptr<api::processes::Cache> CreateCacheData( const blink::WebCache::ResourceTypeStat& stat) { std::unique_ptr<api::processes::Cache> cache(new api::processes::Cache()); cache->size = static_cast<double>(stat.size); - cache->live_size = static_cast<double>(stat.liveSize); + cache->live_size = static_cast<double>(stat.size); return cache; } diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc b/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc index e52ebb19868..c2ad7f37bb2 100644 --- a/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc +++ b/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc @@ -103,7 +103,7 @@ base::Value* ProxyPrefTransformer::ExtensionToBrowserPref( // When ExtensionToBrowserPref is called, the format of |extension_pref| // has been verified already by the extension API to match the schema // defined in the extension API JSON. - CHECK(extension_pref->IsType(base::Value::TYPE_DICTIONARY)); + CHECK(extension_pref->IsType(base::Value::Type::DICTIONARY)); const base::DictionaryValue* config = static_cast<const base::DictionaryValue*>(extension_pref); @@ -140,7 +140,7 @@ base::Value* ProxyPrefTransformer::ExtensionToBrowserPref( base::Value* ProxyPrefTransformer::BrowserToExtensionPref( const base::Value* browser_pref) { - CHECK(browser_pref->IsType(base::Value::TYPE_DICTIONARY)); + CHECK(browser_pref->IsType(base::Value::Type::DICTIONARY)); // This is a dictionary wrapper that exposes the proxy configuration stored in // the browser preferences. diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc index 6ac96677064..8d2cbdadadf 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc @@ -13,7 +13,6 @@ #include "base/lazy_instance.h" #include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" -#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "chrome/browser/extensions/api/sessions/session_id.h" @@ -276,6 +275,8 @@ std::unique_ptr<windows::Window> SessionsGetDevicesFunction::CreateWindowModel( windows::WindowState state = windows::WINDOW_STATE_NONE; switch (window.show_state) { case ui::SHOW_STATE_NORMAL: + + // TODO(afakhry): Remove Docked Windows in M58. case ui::SHOW_STATE_DOCKED: state = windows::WINDOW_STATE_NORMAL; break; diff --git a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc index 8ffa9275392..7b8882b66c5 100644 --- a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc +++ b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc @@ -277,7 +277,6 @@ void SettingsOverridesAPI::RegisterSearchProvider( std::string install_parameter = prefs->GetInstallParam(extension->id()); std::unique_ptr<TemplateURLData> data = ConvertSearchProvider( profile_->GetPrefs(), *settings->search_engine, install_parameter); - data->show_in_default_list = info->wants_to_be_default_engine; auto turl = base::MakeUnique<TemplateURL>( *data, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION); diff --git a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.h b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.h index 5167a049a47..2781665c3a5 100644 --- a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.h +++ b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.h @@ -15,7 +15,6 @@ #include "extensions/browser/extension_registry_observer.h" class Profile; -class TemplateURL; namespace extensions { class ExtensionRegistry; diff --git a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc index e2f86c70b4a..444b7d6f4c3 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc @@ -143,7 +143,7 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_private::PrefType::PREF_TYPE_STRING; (*s_whitelist)[::prefs::kNetworkPredictionOptions] = settings_private::PrefType::PREF_TYPE_NUMBER; - (*s_whitelist)[password_manager::prefs::kPasswordManagerSavingEnabled] = + (*s_whitelist)[password_manager::prefs::kCredentialsEnableService] = settings_private::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[password_manager::prefs::kCredentialsEnableAutosignin] = settings_private::PrefType::PREF_TYPE_BOOLEAN; @@ -162,6 +162,12 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { (*s_whitelist)[translate::TranslatePrefs::kPrefTranslateBlockedLanguages] = settings_private::PrefType::PREF_TYPE_LIST; + // Search page. + (*s_whitelist)[::prefs::kDefaultSearchProviderEnabled] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[::prefs::kGoogleNowLauncherEnabled] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; + // Site Settings prefs. (*s_whitelist)[::prefs::kBlockThirdPartyCookies] = settings_private::PrefType::PREF_TYPE_BOOLEAN; @@ -235,6 +241,10 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { (*s_whitelist)[::prefs::kAccessibilityMonoAudioEnabled] = settings_private::PrefType::PREF_TYPE_BOOLEAN; + // Android Apps. + (*s_whitelist)[::prefs::kArcEnabled] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; + // Misc. (*s_whitelist)[::prefs::kUse24HourClock] = settings_private::PrefType::PREF_TYPE_BOOLEAN; @@ -329,6 +339,12 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_private::PrefType::PREF_TYPE_BOOLEAN; #endif + // Search settings. + (*s_whitelist)[::prefs::kHotwordSearchEnabled] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[::prefs::kHotwordAlwaysOnSearchEnabled] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; + // Proxy settings. (*s_whitelist)[proxy_config::prefs::kProxy] = settings_private::PrefType::PREF_TYPE_DICTIONARY; @@ -344,17 +360,17 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_private::PrefType PrefsUtil::GetType(const std::string& name, base::Value::Type type) { switch (type) { - case base::Value::Type::TYPE_BOOLEAN: + case base::Value::Type::BOOLEAN: return settings_private::PrefType::PREF_TYPE_BOOLEAN; - case base::Value::Type::TYPE_INTEGER: - case base::Value::Type::TYPE_DOUBLE: + case base::Value::Type::INTEGER: + case base::Value::Type::DOUBLE: return settings_private::PrefType::PREF_TYPE_NUMBER; - case base::Value::Type::TYPE_STRING: + case base::Value::Type::STRING: return IsPrefTypeURL(name) ? settings_private::PrefType::PREF_TYPE_URL : settings_private::PrefType::PREF_TYPE_STRING; - case base::Value::Type::TYPE_LIST: + case base::Value::Type::LIST: return settings_private::PrefType::PREF_TYPE_LIST; - case base::Value::Type::TYPE_DICTIONARY: + case base::Value::Type::DICTIONARY: return settings_private::PrefType::PREF_TYPE_DICTIONARY; default: return settings_private::PrefType::PREF_TYPE_NONE; @@ -489,13 +505,13 @@ PrefsUtil::SetPrefResult PrefsUtil::SetPref(const std::string& pref_name, DCHECK_EQ(pref->GetType(), value->GetType()); switch (pref->GetType()) { - case base::Value::TYPE_BOOLEAN: - case base::Value::TYPE_DOUBLE: - case base::Value::TYPE_LIST: - case base::Value::TYPE_DICTIONARY: + case base::Value::Type::BOOLEAN: + case base::Value::Type::DOUBLE: + case base::Value::Type::LIST: + case base::Value::Type::DICTIONARY: pref_service->Set(pref_name, *value); break; - case base::Value::TYPE_INTEGER: { + case base::Value::Type::INTEGER: { // In JS all numbers are doubles. double double_value; if (!value->GetAsDouble(&double_value)) @@ -504,7 +520,7 @@ PrefsUtil::SetPrefResult PrefsUtil::SetPref(const std::string& pref_name, pref_service->SetInteger(pref_name, static_cast<int>(double_value)); break; } - case base::Value::TYPE_STRING: { + case base::Value::Type::STRING: { std::string string_value; if (!value->GetAsString(&string_value)) return PREF_TYPE_MISMATCH; @@ -696,12 +712,24 @@ const Extension* PrefsUtil::GetExtensionControllingPref( // corresponds with some indiciator that should be shown in the settings UI. if (pref_object.key == ::prefs::kHomePage) return GetExtensionOverridingHomepage(profile_); + + if (pref_object.key == ::prefs::kRestoreOnStartup) { + int restore_on_startup; + CHECK(pref_object.value->GetAsInteger(&restore_on_startup)); + + if (restore_on_startup == SessionStartupPref::kPrefValueURLs) + return GetExtensionOverridingStartupPages(profile_); + } + if (pref_object.key == ::prefs::kURLsToRestoreOnStartup) return GetExtensionOverridingStartupPages(profile_); + if (pref_object.key == ::prefs::kDefaultSearchProviderEnabled) return GetExtensionOverridingSearchEngine(profile_); + if (pref_object.key == proxy_config::prefs::kProxy) return GetExtensionOverridingProxy(profile_); + return nullptr; } diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc index a73f78f8d83..64104da47cb 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc @@ -99,7 +99,7 @@ ExtensionFunction::ResponseAction SettingsPrivateGetPrefFunction::Run() { return RespondNow(Error(kDelegateIsNull)); std::unique_ptr<base::Value> value = delegate->GetPref(parameters->name); - if (value->IsType(base::Value::TYPE_NULL)) + if (value->IsType(base::Value::Type::NONE)) return RespondNow(Error("Pref * does not exist", parameters->name)); else return RespondNow(OneArgument(std::move(value))); diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc index 13ed8a8ddbe..1311f2f9cee 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.cc @@ -46,7 +46,7 @@ std::unique_ptr<base::Value> SettingsPrivateDelegate::GetAllPrefs() { const TypedPrefMap& keys = prefs_util_->GetWhitelistedKeys(); for (const auto& it : keys) { std::unique_ptr<base::Value> pref = GetPref(it.first); - if (!pref->IsType(base::Value::TYPE_NULL)) + if (!pref->IsType(base::Value::Type::NONE)) prefs->Append(std::move(pref)); } diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h index 06477b50893..75fef8f2c45 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h @@ -20,8 +20,6 @@ class BrowserContext; namespace extensions { -class SettingsPrivateDelegate; - // This is an event router that will observe listeners to pref changes on the // appropriate pref service(s) and notify listeners on the JavaScript // settingsPrivate API. diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h index 2ed5be0a07a..0c6dad3e6e4 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h @@ -21,8 +21,6 @@ class Profile; namespace content { class BrowserContext; -class NotificationDetails; -class NotificationObserver; class NotificationRegistrar; } // namespace content diff --git a/chromium/chrome/browser/extensions/api/socket/mock_tcp_client_socket.h b/chromium/chrome/browser/extensions/api/socket/mock_tcp_client_socket.h index 595d2685234..0db73de4cd9 100644 --- a/chromium/chrome/browser/extensions/api/socket/mock_tcp_client_socket.h +++ b/chromium/chrome/browser/extensions/api/socket/mock_tcp_client_socket.h @@ -17,7 +17,6 @@ class MockTCPClientSocket : public net::TCPClientSocket { MockTCPClientSocket(); virtual ~MockTCPClientSocket(); - // Copied from MockTCPClientSocket in blimp/net/test_common.h MOCK_METHOD3(Read, int(net::IOBuffer*, int, const net::CompletionCallback&)); MOCK_METHOD3(Write, int(net::IOBuffer*, int, const net::CompletionCallback&)); MOCK_METHOD1(SetReceiveBufferSize, int(int32_t)); @@ -35,7 +34,7 @@ class MockTCPClientSocket : public net::TCPClientSocket { MOCK_CONST_METHOD0(UsingTCPFastOpen, bool()); MOCK_CONST_METHOD0(NumBytesRead, int64_t()); MOCK_CONST_METHOD0(GetConnectTimeMicros, base::TimeDelta()); - MOCK_CONST_METHOD0(WasNpnNegotiated, bool()); + MOCK_CONST_METHOD0(WasAlpnNegotiated, bool()); MOCK_CONST_METHOD0(GetNegotiatedProtocol, net::NextProto()); MOCK_METHOD1(GetSSLInfo, bool(net::SSLInfo*)); MOCK_CONST_METHOD1(GetConnectionAttempts, void(net::ConnectionAttempts*)); diff --git a/chromium/chrome/browser/extensions/api/socket/socket_apitest.cc b/chromium/chrome/browser/extensions/api/socket/socket_apitest.cc index c31b8af8b99..8fb5d4e1ee6 100644 --- a/chromium/chrome/browser/extensions/api/socket/socket_apitest.cc +++ b/chromium/chrome/browser/extensions/api/socket/socket_apitest.cc @@ -33,6 +33,7 @@ class SocketApiTest : public ExtensionApiTest { resolver_creator_(new extensions::MockHostResolverCreator()) {} void SetUpOnMainThread() override { + ExtensionApiTest::SetUpOnMainThread(); extensions::HostResolverWrapper::GetInstance()->SetHostResolverForTesting( resolver_creator_->CreateMockHostResolver()); } diff --git a/chromium/chrome/browser/extensions/api/socket/tls_socket_unittest.cc b/chromium/chrome/browser/extensions/api/socket/tls_socket_unittest.cc index 2e19965cbba..09633f1f569 100644 --- a/chromium/chrome/browser/extensions/api/socket/tls_socket_unittest.cc +++ b/chromium/chrome/browser/extensions/api/socket/tls_socket_unittest.cc @@ -58,7 +58,7 @@ class MockSSLClientSocket : public net::SSLClientSocket { MOCK_METHOD0(SetOmniboxSpeculation, void()); MOCK_CONST_METHOD0(WasEverUsed, bool()); MOCK_CONST_METHOD0(UsingTCPFastOpen, bool()); - MOCK_CONST_METHOD0(WasNpnNegotiated, bool()); + MOCK_CONST_METHOD0(WasAlpnNegotiated, bool()); MOCK_CONST_METHOD0(GetNegotiatedProtocol, net::NextProto()); MOCK_METHOD1(GetSSLInfo, bool(net::SSLInfo*)); MOCK_CONST_METHOD1(GetConnectionAttempts, void(net::ConnectionAttempts*)); diff --git a/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h b/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h index c98db37b9c2..6522f30864a 100644 --- a/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h +++ b/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h @@ -16,10 +16,6 @@ namespace syncer { class SyncData; } -namespace sync_pb { -class ExtensionSettingSpecifics; -} - namespace extensions { // Container for data interpreted from sync data/changes for an extension or diff --git a/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc b/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc index b934a9b55e0..ac1d74b70a9 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc +++ b/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc @@ -442,37 +442,37 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, ExtensionsSchemas) { ASSERT_TRUE(schema); ASSERT_TRUE(schema->valid()); - ASSERT_EQ(base::Value::TYPE_DICTIONARY, schema->type()); + ASSERT_EQ(base::Value::Type::DICTIONARY, schema->type()); ASSERT_TRUE(schema->GetKnownProperty("string-policy").valid()); - EXPECT_EQ(base::Value::TYPE_STRING, + EXPECT_EQ(base::Value::Type::STRING, schema->GetKnownProperty("string-policy").type()); ASSERT_TRUE(schema->GetKnownProperty("int-policy").valid()); - EXPECT_EQ(base::Value::TYPE_INTEGER, + EXPECT_EQ(base::Value::Type::INTEGER, schema->GetKnownProperty("int-policy").type()); ASSERT_TRUE(schema->GetKnownProperty("double-policy").valid()); - EXPECT_EQ(base::Value::TYPE_DOUBLE, + EXPECT_EQ(base::Value::Type::DOUBLE, schema->GetKnownProperty("double-policy").type()); ASSERT_TRUE(schema->GetKnownProperty("boolean-policy").valid()); - EXPECT_EQ(base::Value::TYPE_BOOLEAN, + EXPECT_EQ(base::Value::Type::BOOLEAN, schema->GetKnownProperty("boolean-policy").type()); policy::Schema list = schema->GetKnownProperty("list-policy"); ASSERT_TRUE(list.valid()); - ASSERT_EQ(base::Value::TYPE_LIST, list.type()); + ASSERT_EQ(base::Value::Type::LIST, list.type()); ASSERT_TRUE(list.GetItems().valid()); - EXPECT_EQ(base::Value::TYPE_STRING, list.GetItems().type()); + EXPECT_EQ(base::Value::Type::STRING, list.GetItems().type()); policy::Schema dict = schema->GetKnownProperty("dict-policy"); ASSERT_TRUE(dict.valid()); - ASSERT_EQ(base::Value::TYPE_DICTIONARY, dict.type()); + ASSERT_EQ(base::Value::Type::DICTIONARY, dict.type()); list = dict.GetKnownProperty("list"); ASSERT_TRUE(list.valid()); - ASSERT_EQ(base::Value::TYPE_LIST, list.type()); + ASSERT_EQ(base::Value::Type::LIST, list.type()); dict = list.GetItems(); ASSERT_TRUE(dict.valid()); - ASSERT_EQ(base::Value::TYPE_DICTIONARY, dict.type()); + ASSERT_EQ(base::Value::Type::DICTIONARY, dict.type()); ASSERT_TRUE(dict.GetProperty("anything").valid()); - EXPECT_EQ(base::Value::TYPE_INTEGER, dict.GetProperty("anything").type()); + EXPECT_EQ(base::Value::Type::INTEGER, dict.GetProperty("anything").type()); } IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, ManagedStorage) { diff --git a/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc b/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc index 64cba600a48..1339ae4f344 100644 --- a/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc @@ -19,7 +19,6 @@ #include "content/public/browser/download_item.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/render_process_host.h" -#include "content/public/browser/resource_controller.h" #include "content/public/browser/web_contents.h" #include "content/public/test/download_test_observer.h" #include "extensions/browser/event_router.h" @@ -37,7 +36,6 @@ using content::BrowserThread; using content::DownloadItem; using content::DownloadManager; using content::DownloadUrlParameters; -using content::ResourceController; using content::WebContents; using extensions::Event; using extensions::ExtensionSystem; @@ -138,8 +136,8 @@ class StreamsPrivateApiTest : public ExtensionApiTest { void SetUpOnMainThread() override { // Init test server. test_server_.reset(new net::EmbeddedTestServer); - ASSERT_TRUE(test_server_->Start()); test_server_->RegisterRequestHandler(base::Bind(&HandleRequest)); + ASSERT_TRUE(test_server_->Start()); ExtensionApiTest::SetUpOnMainThread(); } @@ -165,7 +163,6 @@ class StreamsPrivateApiTest : public ExtensionApiTest { DownloadManager* manager = GetDownloadManager(); DownloadPrefs::FromDownloadManager(manager)->ResetAutoOpen(); - manager->RemoveAllDownloads(); } // Sends onExecuteContentHandler event with the MIME type "test/done" to the diff --git a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc index 5a059fd104c..549b4aaa415 100644 --- a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc @@ -84,6 +84,7 @@ class SyncFileSystemTest : public extensions::PlatformAppBrowserTest, } void SetUpOnMainThread() override { + extensions::PlatformAppBrowserTest::SetUpOnMainThread(); ASSERT_TRUE(base_dir_.CreateUniqueTempDir()); SyncFileSystemServiceFactory* factory = diff --git a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h index 1fe28267fee..318d8ebf5f7 100644 --- a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h +++ b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h @@ -8,8 +8,6 @@ #include "chrome/browser/extensions/api/extension_action/extension_action_api.h" #include "extensions/browser/extension_function.h" -class Profile; - namespace extensions { class SystemIndicatorSetIconFunction : public ExtensionActionSetIconFunction { diff --git a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc index f50fdf9c3cb..776dd0a3281 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.cc @@ -12,8 +12,10 @@ #include "chrome/browser/extensions/api/tab_capture/tab_capture_registry.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/web_contents_sizer.h" +#include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" +#include "content/public/common/web_preferences.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/process_manager.h" @@ -120,6 +122,13 @@ void OffscreenTab::Start(const GURL& start_url, if (!optional_presentation_id.empty()) { NOTIMPLEMENTED() << "Register with PresentationRouter, id=" << optional_presentation_id; + + if (auto* render_view_host = + offscreen_tab_web_contents_->GetRenderViewHost()) { + auto web_prefs = render_view_host->GetWebkitPreferences(); + web_prefs.presentation_receiver = true; + render_view_host->UpdateWebkitPreferences(web_prefs); + } } // Navigate to the initial URL. @@ -206,16 +215,18 @@ bool OffscreenTab::CanDragEnter( } bool OffscreenTab::ShouldCreateWebContents( - WebContents* contents, + content::WebContents* web_contents, + content::SiteInstance* source_site_instance, int32_t route_id, int32_t main_frame_route_id, int32_t main_frame_widget_route_id, WindowContainerType window_container_type, + const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const std::string& partition_id, content::SessionStorageNamespace* session_storage_namespace) { - DCHECK_EQ(offscreen_tab_web_contents_.get(), contents); + DCHECK_EQ(offscreen_tab_web_contents_.get(), web_contents); // Disallow creating separate WebContentses. The WebContents implementation // uses this to spawn new windows/tabs, which is also not allowed for // offscreen tabs. diff --git a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h index e6393192a06..992160d5365 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h +++ b/chromium/chrome/browser/extensions/api/tab_capture/offscreen_tab.h @@ -140,11 +140,13 @@ class OffscreenTab : protected content::WebContentsDelegate, const content::DropData& data, blink::WebDragOperationsMask operations_allowed) final; bool ShouldCreateWebContents( - content::WebContents* contents, + content::WebContents* web_contents, + content::SiteInstance* source_site_instance, int32_t route_id, int32_t main_frame_route_id, int32_t main_frame_widget_route_id, WindowContainerType window_container_type, + const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const std::string& partition_id, diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc index 17987c1481d..7ad501fee3a 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc @@ -15,6 +15,7 @@ #include "base/command_line.h" #include "base/macros.h" +#include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" #include "chrome/browser/extensions/api/tab_capture/offscreen_tab.h" @@ -87,7 +88,7 @@ void FilterDeprecatedGoogConstraints(TabCapture::CaptureOptions* options) { std::vector<std::string> bad_keys; base::DictionaryValue::Iterator it(*dict); for (; !it.IsAtEnd(); it.Advance()) { - if (it.key().find("goog") == 0) + if (base::StartsWith(it.key(), "goog", base::CompareCase::SENSITIVE)) bad_keys.push_back(it.key()); } for (const std::string& k : bad_keys) { diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc index ffd167bf2e2..40f4f5c402d 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc @@ -166,9 +166,15 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTests) { ASSERT_TRUE(RunExtensionSubtest("tab_capture", "api_tests.html")) << message_; } +#if defined(OS_MACOSX) && defined(ADDRESS_SANITIZER) +// Flaky on ASAN on Mac. See https://crbug.com/674497. +#define MAYBE_MaxOffscreenTabs DISABLED_MaxOffscreenTabs +#else +#define MAYBE_MaxOffscreenTabs MaxOffscreenTabs +#endif // Tests that there is a maximum limitation to the number of simultaneous // off-screen tabs. -IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MaxOffscreenTabs) { +IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_MaxOffscreenTabs) { AddExtensionToCommandLineWhitelist(); ASSERT_TRUE(RunExtensionSubtest("tab_capture", "max_offscreen_tabs.html")) << message_; @@ -305,17 +311,12 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ActiveTabPermission) { EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } -// http://crbug.com/177163 -#if defined(OS_WIN) && !defined(NDEBUG) -#define MAYBE_FullscreenEvents DISABLED_FullscreenEvents -#else -#define MAYBE_FullscreenEvents FullscreenEvents -#endif +// Flaky: http://crbug.com/675851 // Tests that fullscreen transitions during a tab capture session dispatch // events to the onStatusChange listener. The test loads a page that toggles // fullscreen mode, using the Fullscreen Javascript API, in response to mouse // clicks. -IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_FullscreenEvents) { +IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, DISABLED_FullscreenEvents) { AddExtensionToCommandLineWhitelist(); ExtensionTestMessageListener capture_started("tab_capture_started", false); diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc index 6be7404636a..ab42182e4d3 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc @@ -5,7 +5,6 @@ #include "base/command_line.h" #include "base/strings/stringprintf.h" #include "base/test/trace_event_analyzer.h" -#include "base/win/windows_version.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/tab_helper.h" @@ -28,6 +27,10 @@ #include "ui/compositor/compositor_switches.h" #include "ui/gl/gl_switches.h" +#if defined(OS_WIN) +#include "base/win/windows_version.h" +#endif + namespace { const char kExtensionId[] = "ddchlicdkolnonkihahngkmmmjnjlkkf"; diff --git a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h index 7f829741012..8b8511a7a65 100644 --- a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h +++ b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h @@ -7,7 +7,6 @@ #include <string> -#include "base/containers/scoped_ptr_hash_map.h" #include "base/macros.h" #include "chrome/browser/extensions/window_controller.h" diff --git a/chromium/chrome/browser/extensions/api/tabs/ash_panel_contents.cc b/chromium/chrome/browser/extensions/api/tabs/ash_panel_contents.cc index 4279baa9535..c2509c6d37f 100644 --- a/chromium/chrome/browser/extensions/api/tabs/ash_panel_contents.cc +++ b/chromium/chrome/browser/extensions/api/tabs/ash_panel_contents.cc @@ -71,9 +71,6 @@ void AshPanelContents::NativeWindowChanged(NativeAppWindow* native_app_window) { void AshPanelContents::NativeWindowClosed() { } -void AshPanelContents::DispatchWindowShownForTests() const { -} - void AshPanelContents::OnWindowReady() {} content::WebContents* AshPanelContents::GetWebContents() const { diff --git a/chromium/chrome/browser/extensions/api/tabs/ash_panel_contents.h b/chromium/chrome/browser/extensions/api/tabs/ash_panel_contents.h index 78299ec947c..d0f77301d2e 100644 --- a/chromium/chrome/browser/extensions/api/tabs/ash_panel_contents.h +++ b/chromium/chrome/browser/extensions/api/tabs/ash_panel_contents.h @@ -36,7 +36,6 @@ class AshPanelContents void NativeWindowChanged( extensions::NativeAppWindow* native_app_window) override; void NativeWindowClosed() override; - void DispatchWindowShownForTests() const override; void OnWindowReady() override; content::WebContents* GetWebContents() const override; extensions::WindowController* GetWindowController() const override; diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc index f882148ceb7..a92dd4acf19 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc @@ -23,7 +23,6 @@ #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/browser_process.h" @@ -1177,11 +1176,17 @@ bool TabsUpdateFunction::RunAsync() { int tab_index = -1; TabStripModel* tab_strip = NULL; - if (!GetTabById(tab_id, browser_context(), include_incognito(), NULL, + Browser* browser = nullptr; + if (!GetTabById(tab_id, browser_context(), include_incognito(), &browser, &tab_strip, &contents, &tab_index, &error_)) { return false; } + if (!ExtensionTabUtil::BrowserSupportsTabs(browser)) { + error_ = keys::kNoCurrentWindowError; + return false; + } + web_contents_ = contents; // TODO(rafaelw): handle setting remaining tab properties: @@ -1255,6 +1260,11 @@ bool TabsUpdateFunction::RunAsync() { &opener_contents, nullptr)) return false; + if (tab_strip->GetIndexOfWebContents(opener_contents) == + TabStripModel::kNoTab) { + error_ = "Tab opener must be in the same window as the updated tab."; + return false; + } tab_strip->SetOpenerOfWebContentsAt(tab_index, opener_contents); } @@ -1547,10 +1557,11 @@ ExtensionFunction::ResponseAction TabsReloadFunction::Run() { WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_RELOAD, false); current_browser->OpenURL(params); - } else if (bypass_cache) { - web_contents->GetController().ReloadBypassingCache(true); } else { - web_contents->GetController().Reload(true); + web_contents->GetController().Reload( + bypass_cache ? content::ReloadType::BYPASSING_CACHE + : content::ReloadType::NORMAL, + true); } return RespondNow(NoArguments()); diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h index 5e5299c1e9d..82b5d1b253b 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h @@ -26,10 +26,6 @@ class GURL; class SkBitmap; class TabStripModel; -namespace base { -class DictionaryValue; -} - namespace content { class WebContents; } diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc index 9e33edf72d9..5df6a2a4c3b 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc @@ -9,6 +9,7 @@ #include <memory> #include <string> +#include "apps/test/app_window_waiter.h" #include "base/memory/ref_counted.h" #include "base/strings/pattern.h" #include "base/strings/string_split.h" @@ -45,7 +46,6 @@ #include "extensions/browser/api_test_utils.h" #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/app_window_registry.h" -#include "extensions/browser/app_window/native_app_window.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/test_util.h" #include "extensions/test/extension_test_message_listener.h" @@ -798,13 +798,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, UpdateDevToolsWindow) { // TODO(llandwerlin): Activating a browser window and waiting for the // action to happen requires views::Widget which is not available on // MacOSX. Deactivate for now. +// TODO(warx): Move ExtensionWindowLastFocusedTest to interactive +// uitest as it triggers native widget activation. #if !defined(OS_MACOSX) class ExtensionWindowLastFocusedTest : public ExtensionTabsTest { public: void SetUpOnMainThread() override; - void ActivateAppWindow(AppWindow* app_window); - void ActivateBrowserWindow(Browser* browser); Browser* CreateBrowserWithEmptyTab(bool as_popup); @@ -815,44 +815,6 @@ class ExtensionWindowLastFocusedTest : public ExtensionTabsTest { const std::string& params); private: - // A helper class to wait for an AppWindow to become activated. On - // window system like X11, for a NativeWidget to be activated, we - // need to wait for the round trip communication with the X server. - class AppWindowActivatedWaiter : public AppWindowRegistry::Observer { - public: - AppWindowActivatedWaiter(AppWindow* app_window, - content::BrowserContext* browser_context) - : app_window_(app_window), - browser_context_(browser_context), - waiting_(false) { - AppWindowRegistry::Get(browser_context_)->AddObserver(this); - } - ~AppWindowActivatedWaiter() override { - AppWindowRegistry::Get(browser_context_)->RemoveObserver(this); - } - - void ActivateAndWait() { - app_window_->GetBaseWindow()->Activate(); - if (!app_window_->GetBaseWindow()->IsActive()) { - waiting_ = true; - content::RunMessageLoop(); - } - } - - // AppWindowRegistry::Observer: - void OnAppWindowActivated(AppWindow* app_window) override { - if (app_window_ == app_window && waiting_) { - base::MessageLoopForUI::current()->QuitWhenIdle(); - waiting_ = false; - } - } - - private: - AppWindow* app_window_; - content::BrowserContext* browser_context_; - bool waiting_; - }; - // A helper class to wait for an views::Widget to become activated. class WidgetActivatedWaiter : public views::WidgetObserver { public: @@ -892,11 +854,6 @@ void ExtensionWindowLastFocusedTest::SetUpOnMainThread() { extension_ = test_util::CreateEmptyExtension(); } -void ExtensionWindowLastFocusedTest::ActivateAppWindow(AppWindow* app_window) { - AppWindowActivatedWaiter waiter(app_window, browser()->profile()); - waiter.ActivateAndWait(); -} - void ExtensionWindowLastFocusedTest::ActivateBrowserWindow(Browser* browser) { BrowserView* view = BrowserView::GetBrowserViewForBrowser(browser); EXPECT_NE(nullptr, view); @@ -943,6 +900,34 @@ base::Value* ExtensionWindowLastFocusedTest::RunFunction( } IN_PROC_BROWSER_TEST_F(ExtensionWindowLastFocusedTest, + ExtensionAPICannotNavigateDevtools) { + std::unique_ptr<base::DictionaryValue> test_extension_value( + api_test_utils::ParseDictionary( + "{\"name\": \"Test\", \"version\": \"1.0\", \"permissions\": " + "[\"tabs\"]}")); + scoped_refptr<Extension> extension( + api_test_utils::CreateExtension(test_extension_value.get())); + + DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( + browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); + + scoped_refptr<TabsUpdateFunction> function = + new TabsUpdateFunction(); + function->set_extension(extension.get()); + + EXPECT_TRUE(base::MatchPattern( + utils::RunFunctionAndReturnError( + function.get(), base::StringPrintf( + "[%d, {\"url\":\"http://example.com\"}]", + ExtensionTabUtil::GetTabId( + DevToolsWindowTesting::Get(devtools)->main_web_contents())), + DevToolsWindowTesting::Get(devtools)->browser()), + tabs_constants::kNoCurrentWindowError)); + + DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); +} + +IN_PROC_BROWSER_TEST_F(ExtensionWindowLastFocusedTest, NoDevtoolsAndAppWindows) { DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); @@ -965,7 +950,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWindowLastFocusedTest, " \"minWidth\": 200, \"minHeight\": 200," " \"maxWidth\": 400, \"maxHeight\": 400}}"); { - ActivateAppWindow(app_window); + apps::AppWindowWaiter waiter(AppWindowRegistry::Get(browser()->profile()), + app_window->extension_id()); + waiter.WaitForActivated(); scoped_refptr<WindowsGetLastFocusedFunction> get_current_app_function = new WindowsGetLastFocusedFunction(); @@ -1037,7 +1024,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWindowLastFocusedTest, " \"minWidth\": 200, \"minHeight\": 200," " \"maxWidth\": 400, \"maxHeight\": 400}}"); { - ActivateAppWindow(app_window); + apps::AppWindowWaiter waiter(AppWindowRegistry::Get(browser()->profile()), + app_window->extension_id()); + waiter.WaitForActivated(); scoped_refptr<WindowsGetLastFocusedFunction> get_current_app_function = new WindowsGetLastFocusedFunction(); @@ -1168,7 +1157,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DuplicateTab) { int duplicate_tab_window_id = GetTabWindowId(duplicate_result.get()); int duplicate_tab_index = api_test_utils::GetInteger(duplicate_result.get(), "index"); - EXPECT_EQ(base::Value::TYPE_DICTIONARY, duplicate_result->GetType()); + EXPECT_EQ(base::Value::Type::DICTIONARY, duplicate_result->GetType()); // Duplicate tab id should be different from the original tab id. EXPECT_NE(tab_id, duplicate_tab_id); EXPECT_EQ(window_id, duplicate_tab_window_id); @@ -1205,7 +1194,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DuplicateTabNoPermission) { int duplicate_tab_window_id = GetTabWindowId(duplicate_result.get()); int duplicate_tab_index = api_test_utils::GetInteger(duplicate_result.get(), "index"); - EXPECT_EQ(base::Value::TYPE_DICTIONARY, duplicate_result->GetType()); + EXPECT_EQ(base::Value::Type::DICTIONARY, duplicate_result->GetType()); // Duplicate tab id should be different from the original tab id. EXPECT_NE(tab_id, duplicate_tab_id); EXPECT_EQ(window_id, duplicate_tab_window_id); diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_util.h b/chromium/chrome/browser/extensions/api/tabs/windows_util.h index b8b20c6f361..d5526e10c30 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_util.h +++ b/chromium/chrome/browser/extensions/api/tabs/windows_util.h @@ -9,12 +9,7 @@ class UIThreadExtensionFunction; -namespace content { -class BrowserContext; -} - namespace extensions { -class Extension; class WindowController; } diff --git a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc index 3e7db7188c3..f42859dff10 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc @@ -7,6 +7,7 @@ #include <utility> #include "base/bind.h" +#include "base/command_line.h" #include "base/json/json_writer.h" #include "base/memory/ptr_util.h" #include "base/sys_info.h" @@ -14,6 +15,7 @@ #include "chrome/browser/extensions/api/terminal/terminal_extension_helper.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/api/terminal_private.h" #include "chromeos/process_proxy/process_proxy_registry.h" #include "content/public/browser/browser_context.h" @@ -40,18 +42,22 @@ const char kCroshCommand[] = "/usr/bin/crosh"; // We make stubbed crosh just echo back input. const char kStubbedCroshCommand[] = "cat"; -const char* GetCroshPath() { +std::string GetCroshPath() { + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kCroshCommand)) + return command_line->GetSwitchValueASCII(switches::kCroshCommand); + if (base::SysInfo::IsRunningOnChromeOS()) - return kCroshCommand; - else - return kStubbedCroshCommand; + return std::string(kCroshCommand); + + return std::string(kStubbedCroshCommand); } -const char* GetProcessCommandForName(const std::string& name) { +std::string GetProcessCommandForName(const std::string& name) { if (name == kCroshName) return GetCroshPath(); else - return NULL; + return std::string(); } void NotifyProcessOutput(content::BrowserContext* browser_context, @@ -101,7 +107,7 @@ int GetTabOrWindowSessionId(content::BrowserContext* browser_context, namespace extensions { TerminalPrivateOpenTerminalProcessFunction:: - TerminalPrivateOpenTerminalProcessFunction() : command_(NULL) {} + TerminalPrivateOpenTerminalProcessFunction() {} TerminalPrivateOpenTerminalProcessFunction:: ~TerminalPrivateOpenTerminalProcessFunction() {} @@ -113,7 +119,7 @@ TerminalPrivateOpenTerminalProcessFunction::Run() { EXTENSION_FUNCTION_VALIDATE(params.get()); command_ = GetProcessCommandForName(params->process_name); - if (!command_) + if (command_.empty()) return RespondNow(Error("Invalid process name.")); content::WebContents* caller_contents = GetSenderWebContents(); @@ -150,12 +156,12 @@ TerminalPrivateOpenTerminalProcessFunction::Run() { void TerminalPrivateOpenTerminalProcessFunction::OpenOnFileThread( const ProcessOutputCallback& output_callback, const OpenProcessCallback& callback) { - DCHECK(command_); + DCHECK(!command_.empty()); chromeos::ProcessProxyRegistry* registry = chromeos::ProcessProxyRegistry::Get(); - int terminal_id = registry->OpenProcess(command_, output_callback); + int terminal_id = registry->OpenProcess(command_.c_str(), output_callback); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, base::Bind(callback, terminal_id)); diff --git a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h index b2c044d6740..09982a74805 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h @@ -36,7 +36,7 @@ class TerminalPrivateOpenTerminalProcessFunction const OpenProcessCallback& callback); void RespondOnUIThread(int terminal_id); - const char* command_; + std::string command_; }; // Send input to the terminal process specified by the terminal ID, which is set diff --git a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc index 3d27973cfae..aeda9a0a8a8 100644 --- a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc +++ b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc @@ -140,7 +140,7 @@ bool ChromeVirtualKeyboardDelegate::LockKeyboard(bool state) { if (!controller) return false; - keyboard::KeyboardController::GetInstance()->set_lock_keyboard(state); + keyboard::KeyboardController::GetInstance()->set_keyboard_locked(state); return true; } @@ -151,12 +151,8 @@ bool ChromeVirtualKeyboardDelegate::SendKeyEvent(const std::string& type, int modifiers) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); aura::Window* window = GetKeyboardContainer(); - return window && keyboard::SendKeyEvent(type, - char_value, - key_code, - key_name, - modifiers | ui::EF_IS_SYNTHESIZED, - window->GetHost()); + return window && keyboard::SendKeyEvent(type, char_value, key_code, key_name, + modifiers, window->GetHost()); } bool ChromeVirtualKeyboardDelegate::ShowLanguageSettings() { diff --git a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc index fe50acfe062..2519c77975b 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc +++ b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc @@ -30,7 +30,6 @@ const char* const kValidSchemes[] = { FrameNavigationState::FrameState::FrameState() { error_occurred = false; - is_iframe_srcdoc = false; is_loading = false; is_parsing = false; } @@ -71,13 +70,10 @@ void FrameNavigationState::StartTrackingDocumentLoad( content::RenderFrameHost* frame_host, const GURL& url, bool is_same_page, - bool is_error_page, - bool is_iframe_srcdoc) { + bool is_error_page) { FrameState& frame_state = frame_host_state_map_[frame_host]; frame_state.error_occurred = is_error_page; frame_state.url = url; - frame_state.is_iframe_srcdoc = is_iframe_srcdoc; - DCHECK(!is_iframe_srcdoc || url == url::kAboutBlankURL); if (!is_same_page) { frame_state.is_loading = true; frame_state.is_parsing = true; @@ -116,8 +112,6 @@ GURL FrameNavigationState::GetUrl(content::RenderFrameHost* frame_host) const { if (it == frame_host_state_map_.end()) return GURL(); - if (it->second.is_iframe_srcdoc) - return GURL(content::kAboutSrcDocURL); return it->second.url; } diff --git a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.h b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.h index 1647dad0db4..97de022098e 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.h +++ b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.h @@ -42,8 +42,7 @@ class FrameNavigationState { void StartTrackingDocumentLoad(content::RenderFrameHost* frame_host, const GURL& url, bool is_same_page, - bool is_error_page, - bool is_iframe_srcdoc); + bool is_error_page); // Adds the |frame_host| to the set of RenderFrameHosts associated with the // WebContents this object is tracking. This method and FrameHostDeleted @@ -97,7 +96,6 @@ class FrameNavigationState { FrameState(); bool error_occurred; // True if an error has occurred in this frame. - bool is_iframe_srcdoc; // True if the frame is displaying its srcdoc. bool is_loading; // True if there is a document load going on. bool is_parsing; // True if the frame is still parsing. GURL url; // URL of this frame. diff --git a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state_unittest.cc b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state_unittest.cc index 83eb6c1ff7e..c39357c9100 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state_unittest.cc +++ b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state_unittest.cc @@ -39,8 +39,7 @@ TEST_F(FrameNavigationStateTest, TrackFrame) { // Create a main frame. EXPECT_FALSE(navigation_state_.CanSendEvents(main_rfh())); EXPECT_FALSE(navigation_state_.IsValidFrame(main_rfh())); - navigation_state_.StartTrackingDocumentLoad(main_rfh(), url1, false, false, - false); + navigation_state_.StartTrackingDocumentLoad(main_rfh(), url1, false, false); EXPECT_TRUE(navigation_state_.CanSendEvents(main_rfh())); EXPECT_TRUE(navigation_state_.IsValidFrame(main_rfh())); @@ -49,8 +48,7 @@ TEST_F(FrameNavigationStateTest, TrackFrame) { content::RenderFrameHostTester::For(main_rfh())->AppendChild("child"); EXPECT_FALSE(navigation_state_.CanSendEvents(sub_frame)); EXPECT_FALSE(navigation_state_.IsValidFrame(sub_frame)); - navigation_state_.StartTrackingDocumentLoad(sub_frame, url2, false, false, - false); + navigation_state_.StartTrackingDocumentLoad(sub_frame, url2, false, false); EXPECT_TRUE(navigation_state_.CanSendEvents(sub_frame)); EXPECT_TRUE(navigation_state_.IsValidFrame(sub_frame)); @@ -73,8 +71,7 @@ TEST_F(FrameNavigationStateTest, TrackFrame) { TEST_F(FrameNavigationStateTest, ErrorState) { const GURL url("http://www.google.com/"); - navigation_state_.StartTrackingDocumentLoad(main_rfh(), url, false, false, - false); + navigation_state_.StartTrackingDocumentLoad(main_rfh(), url, false, false); EXPECT_TRUE(navigation_state_.CanSendEvents(main_rfh())); EXPECT_FALSE(navigation_state_.GetErrorOccurredInFrame(main_rfh())); @@ -84,14 +81,12 @@ TEST_F(FrameNavigationStateTest, ErrorState) { EXPECT_TRUE(navigation_state_.GetErrorOccurredInFrame(main_rfh())); // Navigations to a network error page should be ignored. - navigation_state_.StartTrackingDocumentLoad(main_rfh(), GURL(), false, true, - false); + navigation_state_.StartTrackingDocumentLoad(main_rfh(), GURL(), false, true); EXPECT_FALSE(navigation_state_.CanSendEvents(main_rfh())); EXPECT_TRUE(navigation_state_.GetErrorOccurredInFrame(main_rfh())); // However, when the frame navigates again, it should send events again. - navigation_state_.StartTrackingDocumentLoad(main_rfh(), url, false, false, - false); + navigation_state_.StartTrackingDocumentLoad(main_rfh(), url, false, false); EXPECT_TRUE(navigation_state_.CanSendEvents(main_rfh())); EXPECT_FALSE(navigation_state_.GetErrorOccurredInFrame(main_rfh())); } @@ -103,10 +98,8 @@ TEST_F(FrameNavigationStateTest, ErrorStateFrame) { content::RenderFrameHost* sub_frame = content::RenderFrameHostTester::For(main_rfh())->AppendChild("child"); - navigation_state_.StartTrackingDocumentLoad(main_rfh(), url, false, false, - false); - navigation_state_.StartTrackingDocumentLoad(sub_frame, url, false, false, - false); + navigation_state_.StartTrackingDocumentLoad(main_rfh(), url, false, false); + navigation_state_.StartTrackingDocumentLoad(sub_frame, url, false, false); EXPECT_TRUE(navigation_state_.CanSendEvents(main_rfh())); EXPECT_TRUE(navigation_state_.CanSendEvents(sub_frame)); @@ -116,14 +109,12 @@ TEST_F(FrameNavigationStateTest, ErrorStateFrame) { EXPECT_FALSE(navigation_state_.CanSendEvents(sub_frame)); // Navigations to a network error page should be ignored. - navigation_state_.StartTrackingDocumentLoad(sub_frame, GURL(), false, true, - false); + navigation_state_.StartTrackingDocumentLoad(sub_frame, GURL(), false, true); EXPECT_TRUE(navigation_state_.CanSendEvents(main_rfh())); EXPECT_FALSE(navigation_state_.CanSendEvents(sub_frame)); // However, when the frame navigates again, it should send events again. - navigation_state_.StartTrackingDocumentLoad(sub_frame, url, false, false, - false); + navigation_state_.StartTrackingDocumentLoad(sub_frame, url, false, false); EXPECT_TRUE(navigation_state_.CanSendEvents(main_rfh())); EXPECT_TRUE(navigation_state_.CanSendEvents(sub_frame)); } @@ -132,8 +123,7 @@ TEST_F(FrameNavigationStateTest, ErrorStateFrame) { TEST_F(FrameNavigationStateTest, WebSafeScheme) { const GURL url("unsafe://www.google.com/"); - navigation_state_.StartTrackingDocumentLoad(main_rfh(), url, false, false, - false); + navigation_state_.StartTrackingDocumentLoad(main_rfh(), url, false, false); EXPECT_FALSE(navigation_state_.CanSendEvents(main_rfh())); } @@ -145,10 +135,9 @@ TEST_F(FrameNavigationStateTest, SrcDoc) { content::RenderFrameHost* sub_frame = content::RenderFrameHostTester::For(main_rfh())->AppendChild("child"); - navigation_state_.StartTrackingDocumentLoad(main_rfh(), url, false, false, - false); - navigation_state_.StartTrackingDocumentLoad(sub_frame, blank, false, false, - true); + navigation_state_.StartTrackingDocumentLoad(main_rfh(), url, false, false); + navigation_state_.StartTrackingDocumentLoad(sub_frame, srcdoc, false, false); + EXPECT_TRUE(navigation_state_.CanSendEvents(main_rfh())); EXPECT_TRUE(navigation_state_.CanSendEvents(sub_frame)); @@ -166,8 +155,7 @@ TEST_F(FrameNavigationStateTest, DetachFrame) { // Create a main frame. EXPECT_FALSE(navigation_state_.CanSendEvents(main_rfh())); EXPECT_FALSE(navigation_state_.IsValidFrame(main_rfh())); - navigation_state_.StartTrackingDocumentLoad(main_rfh(), url1, false, false, - false); + navigation_state_.StartTrackingDocumentLoad(main_rfh(), url1, false, false); EXPECT_TRUE(navigation_state_.CanSendEvents(main_rfh())); EXPECT_TRUE(navigation_state_.IsValidFrame(main_rfh())); @@ -176,8 +164,7 @@ TEST_F(FrameNavigationStateTest, DetachFrame) { content::RenderFrameHostTester::For(main_rfh())->AppendChild("child"); EXPECT_FALSE(navigation_state_.CanSendEvents(sub_frame)); EXPECT_FALSE(navigation_state_.IsValidFrame(sub_frame)); - navigation_state_.StartTrackingDocumentLoad(sub_frame, url2, false, false, - false); + navigation_state_.StartTrackingDocumentLoad(sub_frame, url2, false, false); EXPECT_TRUE(navigation_state_.CanSendEvents(sub_frame)); EXPECT_TRUE(navigation_state_.IsValidFrame(sub_frame)); diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc index 6d45ec58562..3feaa460c84 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc @@ -271,11 +271,34 @@ void WebNavigationTabObserver::DidStartNavigation( return; } - helpers::DispatchOnBeforeNavigate(navigation_handle); + pending_on_before_navigate_event_ = + helpers::CreateOnBeforeNavigateEvent(navigation_handle); + + // Only dispatch the onBeforeNavigate event if the associated WebContents + // is already added to the tab strip. Otherwise the event should be delayed + // and sent after the addition, to preserve the ordering of events. + // + // TODO(nasko|devlin): This check is necessary because chrome::Navigate() + // begins the navigation before the sending the TAB_ADDED notification, and it + // is used an indication of that. It would be best if instead it was known + // when the tab was created and immediately sent the created event instead of + // waiting for the later TAB_ADDED notification, but this appears to work for + // now. + if (ExtensionTabUtil::GetTabById(ExtensionTabUtil::GetTabId(web_contents()), + web_contents()->GetBrowserContext(), false, + nullptr, nullptr, nullptr, nullptr)) { + DispatchCachedOnBeforeNavigate(); + } } void WebNavigationTabObserver::DidFinishNavigation( content::NavigationHandle* navigation_handle) { + // If there has been a DidStartNavigation call before the tab was ready to + // dispatch events, ensure that it is sent before processing the + // DidFinishNavigation. + // Note: This is exercised by WebNavigationApiTest.TargetBlankIncognito. + DispatchCachedOnBeforeNavigate(); + if (navigation_handle->HasCommitted() && !navigation_handle->IsErrorPage()) { HandleCommit(navigation_handle); return; @@ -320,13 +343,8 @@ void WebNavigationTabObserver::DidFinishLoad( // A new navigation might have started before the old one completed. // Ignore the old navigation completion in that case. - // srcdoc iframes will report a url of about:blank, still let it through. - if (navigation_state_.GetUrl(render_frame_host) != validated_url && - (navigation_state_.GetUrl(render_frame_host) != - content::kAboutSrcDocURL || - validated_url != url::kAboutBlankURL)) { + if (navigation_state_.GetUrl(render_frame_host) != validated_url) return; - } // The load might already have finished by the time we finished parsing. For // compatibility reasons, we artifically delay the load completed signal until @@ -391,6 +409,17 @@ void WebNavigationTabObserver::WebContentsDestroyed() { registrar_.RemoveAll(); } +void WebNavigationTabObserver::DispatchCachedOnBeforeNavigate() { + if (!pending_on_before_navigate_event_) + return; + + // EventRouter can be null in unit tests. + EventRouter* event_router = + EventRouter::Get(web_contents()->GetBrowserContext()); + if (event_router) + event_router->BroadcastEvent(std::move(pending_on_before_navigate_event_)); +} + void WebNavigationTabObserver::HandleCommit( content::NavigationHandle* navigation_handle) { bool is_reference_fragment_navigation = IsReferenceFragmentNavigation( @@ -399,8 +428,7 @@ void WebNavigationTabObserver::HandleCommit( navigation_state_.StartTrackingDocumentLoad( navigation_handle->GetRenderFrameHost(), navigation_handle->GetURL(), navigation_handle->IsSamePage(), - false, // is_error_page - navigation_handle->IsSrcdoc()); + false); // is_error_page events::HistogramValue histogram_value = events::UNKNOWN; std::string event_name; @@ -423,8 +451,7 @@ void WebNavigationTabObserver::HandleError( navigation_state_.StartTrackingDocumentLoad( navigation_handle->GetRenderFrameHost(), navigation_handle->GetURL(), navigation_handle->IsSamePage(), - true, // is_error_page - navigation_handle->IsSrcdoc()); + true); // is_error_page } helpers::DispatchOnErrorOccurred(navigation_handle); diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h index 47a2915470d..c663e68fb58 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h @@ -71,6 +71,9 @@ class WebNavigationTabObserver ui::PageTransition transition) override; void WebContentsDestroyed() override; + // This method dispatches the already created onBeforeNavigate event. + void DispatchCachedOnBeforeNavigate(); + private: explicit WebNavigationTabObserver(content::WebContents* web_contents); friend class content::WebContentsUserData<WebNavigationTabObserver>; @@ -95,6 +98,11 @@ class WebNavigationTabObserver // Tracks the state of the frames we are sending events for. FrameNavigationState navigation_state_; + // The latest onBeforeNavigate event this frame has generated. It is stored + // as it might not be sent immediately, but delayed until the tab is added to + // the tab strip and is ready to dispatch events. + std::unique_ptr<Event> pending_on_before_navigate_event_; + // Used for tracking registrations to redirect notifications. content::NotificationRegistrar registrar_; diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc index 3f1e5a4aa99..ac74ce13664 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc @@ -13,6 +13,7 @@ #include "base/strings/string_number_conversions.h" #include "base/time/time.h" #include "base/values.h" +#include "chrome/browser/extensions/api/web_navigation/web_navigation_api.h" #include "chrome/browser/extensions/api/web_navigation/web_navigation_api_constants.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/profiles/profile.h" @@ -61,11 +62,10 @@ void DispatchEvent(content::BrowserContext* browser_context, } // namespace -// Constructs and dispatches an onBeforeNavigate event. -void DispatchOnBeforeNavigate(content::NavigationHandle* navigation_handle) { +// Constructs an onBeforeNavigate event. +std::unique_ptr<Event> CreateOnBeforeNavigateEvent( + content::NavigationHandle* navigation_handle) { GURL url(navigation_handle->GetURL()); - if (navigation_handle->IsSrcdoc()) - url = GURL(content::kAboutSrcDocURL); web_navigation::OnBeforeNavigate::Details details; details.tab_id = @@ -81,8 +81,15 @@ void DispatchOnBeforeNavigate(content::NavigationHandle* navigation_handle) { new Event(events::WEB_NAVIGATION_ON_BEFORE_NAVIGATE, web_navigation::OnBeforeNavigate::kEventName, web_navigation::OnBeforeNavigate::Create(details))); - DispatchEvent(navigation_handle->GetWebContents()->GetBrowserContext(), - std::move(event), url); + + EventFilteringInfo info; + info.SetURL(navigation_handle->GetURL()); + + event->restrict_to_browser_context = + navigation_handle->GetWebContents()->GetBrowserContext(); + event->filter_info = info; + + return event; } // Constructs and dispatches an onCommitted or onReferenceFragmentUpdated @@ -96,9 +103,6 @@ void DispatchOnCommitted(events::HistogramValue histogram_value, navigation_handle->GetRenderFrameHost(); ui::PageTransition transition_type = navigation_handle->GetPageTransition(); - if (navigation_handle->IsSrcdoc()) - url = GURL(content::kAboutSrcDocURL); - std::unique_ptr<base::ListValue> args(new base::ListValue()); std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); dict->SetInteger(keys::kTabIdKey, ExtensionTabUtil::GetTabId(web_contents)); @@ -203,6 +207,12 @@ void DispatchOnCreatedNavigationTarget( web_navigation::OnCreatedNavigationTarget::kEventName, web_navigation::OnCreatedNavigationTarget::Create(details))); DispatchEvent(browser_context, std::move(event), target_url); + + // If the target WebContents already received the onBeforeNavigate event, + // send it immediately after the onCreatedNavigationTarget above. + WebNavigationTabObserver* target_observer = + WebNavigationTabObserver::Get(target_web_contents); + target_observer->DispatchCachedOnBeforeNavigate(); } // Constructs and dispatches an onErrorOccurred event. diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h index db2832c17f6..5a447c9285a 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_WEB_NAVIGATION_WEB_NAVIGATION_API_HELPERS_H_ #define CHROME_BROWSER_EXTENSIONS_API_WEB_NAVIGATION_WEB_NAVIGATION_API_HELPERS_H_ +#include <memory> #include <string> #include "extensions/browser/extension_event_histogram_value.h" @@ -21,6 +22,8 @@ class GURL; namespace extensions { +struct Event; + namespace web_navigation_api_helpers { // Returns the frame ID as it will be passed to the extension: @@ -29,7 +32,8 @@ namespace web_navigation_api_helpers { int GetFrameId(content::RenderFrameHost* frame_host); // Create and dispatch the various events of the webNavigation API. -void DispatchOnBeforeNavigate(content::NavigationHandle* navigation_handle); +std::unique_ptr<Event> CreateOnBeforeNavigateEvent( + content::NavigationHandle* navigation_handle); void DispatchOnCommitted(events::HistogramValue histogram_value, const std::string& event_name, diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc index 0031c798f90..feec62e949c 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc @@ -7,6 +7,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/strings/string_util.h" @@ -37,7 +38,6 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" -#include "content/public/browser/resource_controller.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/resource_throttle.h" #include "content/public/browser/web_contents.h" @@ -94,7 +94,7 @@ class TestNavigationListener WeakThrottleList::const_iterator it; for (it = throttles_.begin(); it != throttles_.end(); ++it) { if (it->get()) - (*it)->Resume(); + (*it)->ResumeHandler(); } throttles_.clear(); } @@ -110,7 +110,7 @@ class TestNavigationListener WeakThrottleList::iterator it; for (it = throttles_.begin(); it != throttles_.end(); ++it) { if (it->get() && it->get()->url() == url) { - (*it)->Resume(); + (*it)->ResumeHandler(); throttles_.erase(it); break; } @@ -120,13 +120,13 @@ class TestNavigationListener // Constructs a ResourceThrottle if the request for |url| should be held. // // Needs to be invoked on the IO thread. - content::ResourceThrottle* CreateResourceThrottle( + std::unique_ptr<content::ResourceThrottle> CreateResourceThrottle( const GURL& url) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (urls_to_delay_.find(url) == urls_to_delay_.end()) return NULL; - Throttle* throttle = new Throttle(); + auto throttle = base::MakeUnique<Throttle>(); throttle->set_url(url); throttles_.push_back(throttle->AsWeakPtr()); return throttle; @@ -141,9 +141,7 @@ class TestNavigationListener class Throttle : public content::ResourceThrottle, public base::SupportsWeakPtr<Throttle> { public: - void Resume() { - controller()->Resume(); - } + void ResumeHandler() { Resume(); } // content::ResourceThrottle implementation. void WillStartRequest(bool* defer) override { *defer = true; } @@ -271,8 +269,7 @@ class StartProvisionalLoadObserver : public content::WebContentsObserver { void DidStartProvisionalLoadForFrame( content::RenderFrameHost* render_frame_host, const GURL& validated_url, - bool is_error_page, - bool is_iframe_srcdoc) override { + bool is_error_page) override { if (validated_url == url_) { url_seen_ = true; message_loop_runner_->Quit(); @@ -307,22 +304,22 @@ class TestResourceDispatcherHostDelegate } ~TestResourceDispatcherHostDelegate() override {} - void RequestBeginning( - net::URLRequest* request, - content::ResourceContext* resource_context, - content::AppCacheService* appcache_service, - ResourceType resource_type, - ScopedVector<content::ResourceThrottle>* throttles) override { + void RequestBeginning(net::URLRequest* request, + content::ResourceContext* resource_context, + content::AppCacheService* appcache_service, + ResourceType resource_type, + std::vector<std::unique_ptr<content::ResourceThrottle>>* + throttles) override { ChromeResourceDispatcherHostDelegate::RequestBeginning( request, resource_context, appcache_service, resource_type, throttles); - content::ResourceThrottle* throttle = + std::unique_ptr<content::ResourceThrottle> throttle = test_navigation_listener_->CreateResourceThrottle(request->url()); if (throttle) - throttles->push_back(throttle); + throttles->push_back(std::move(throttle)); } private: @@ -576,14 +573,15 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, RequestOpenTab) { ui_test_utils::NavigateToURL(browser(), url); // There's a link on a.html. Middle-click on it to open it in a new tab. - blink::WebMouseEvent mouse_event; - mouse_event.type = blink::WebInputEvent::MouseDown; + blink::WebMouseEvent mouse_event(blink::WebInputEvent::MouseDown, + blink::WebInputEvent::NoModifiers, + blink::WebInputEvent::TimeStampForTesting); mouse_event.button = blink::WebMouseEvent::Button::Middle; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; tab->GetRenderViewHost()->GetWidget()->ForwardMouseEvent(mouse_event); - mouse_event.type = blink::WebInputEvent::MouseUp; + mouse_event.setType(blink::WebInputEvent::MouseUp); tab->GetRenderViewHost()->GetWidget()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); @@ -608,14 +606,15 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, TargetBlank) { // There's a link with target=_blank on a.html. Click on it to open it in a // new tab. - blink::WebMouseEvent mouse_event; - mouse_event.type = blink::WebInputEvent::MouseDown; + blink::WebMouseEvent mouse_event(blink::WebInputEvent::MouseDown, + blink::WebInputEvent::NoModifiers, + blink::WebInputEvent::TimeStampForTesting); mouse_event.button = blink::WebMouseEvent::Button::Left; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; tab->GetRenderViewHost()->GetWidget()->ForwardMouseEvent(mouse_event); - mouse_event.type = blink::WebInputEvent::MouseUp; + mouse_event.setType(blink::WebInputEvent::MouseUp); tab->GetRenderViewHost()->GetWidget()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); @@ -638,14 +637,15 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, TargetBlankIncognito) { // There's a link with target=_blank on a.html. Click on it to open it in a // new tab. - blink::WebMouseEvent mouse_event; - mouse_event.type = blink::WebInputEvent::MouseDown; + blink::WebMouseEvent mouse_event(blink::WebInputEvent::MouseDown, + blink::WebInputEvent::NoModifiers, + blink::WebInputEvent::TimeStampForTesting); mouse_event.button = blink::WebMouseEvent::Button::Left; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; tab->GetRenderViewHost()->GetWidget()->ForwardMouseEvent(mouse_event); - mouse_event.type = blink::WebInputEvent::MouseUp; + mouse_event.setType(blink::WebInputEvent::MouseUp); tab->GetRenderViewHost()->GetWidget()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc index 004116e4948..8cd15af9a9d 100644 --- a/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc @@ -598,7 +598,7 @@ TEST_F(ExtensionWebRequestTest, AccessRequestBodyData) { std::unique_ptr<const base::Value> form_data = base::JSONReader::Read(kFormData); ASSERT_TRUE(form_data.get() != NULL); - ASSERT_TRUE(form_data->GetType() == base::Value::TYPE_DICTIONARY); + ASSERT_TRUE(form_data->GetType() == base::Value::Type::DICTIONARY); // Contents of raw. base::ListValue raw; extensions::subtle::AppendKeyValuePair( diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc index 6c145daf861..b22bf14c7ca 100644 --- a/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc +++ b/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc @@ -232,7 +232,10 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, } // This test times out regularly on win_rel trybots. See http://crbug.com/122178 -#if defined(OS_WIN) +// Also on Linux/ChromiumOS debug, ASAN and MSAN builds. +// https://crbug.com/670415 +#if defined(OS_WIN) || !defined(NDEBUG) || defined(ADDRESS_SANITIZER) || \ + defined(MEMORY_SANITIZER) #define MAYBE_WebRequestBlocking DISABLED_WebRequestBlocking #else #define MAYBE_WebRequestBlocking WebRequestBlocking @@ -270,14 +273,15 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, MAYBE_WebRequestNewTab) { // There's a link on a.html with target=_blank. Click on it to open it in a // new tab. - blink::WebMouseEvent mouse_event; - mouse_event.type = blink::WebInputEvent::MouseDown; + blink::WebMouseEvent mouse_event(blink::WebInputEvent::MouseDown, + blink::WebInputEvent::NoModifiers, + blink::WebInputEvent::TimeStampForTesting); mouse_event.button = blink::WebMouseEvent::Button::Left; mouse_event.x = 7; mouse_event.y = 7; mouse_event.clickCount = 1; tab->GetRenderViewHost()->GetWidget()->ForwardMouseEvent(mouse_event); - mouse_event.type = blink::WebInputEvent::MouseUp; + mouse_event.setType(blink::WebInputEvent::MouseUp); tab->GetRenderViewHost()->GetWidget()->ForwardMouseEvent(mouse_event); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); @@ -550,8 +554,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, FeatureSwitch::scripts_require_action(), true); host_resolver()->AddRule("*", "127.0.0.1"); - ASSERT_TRUE(embedded_test_server()->Start()); content::SetupCrossSiteRedirector(embedded_test_server()); + ASSERT_TRUE(embedded_test_server()->Start()); // Load an extension that registers a listener for webRequest events, and // wait 'til it's initialized. diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc index af28138ea03..3682c629d20 100644 --- a/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc +++ b/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc @@ -11,6 +11,7 @@ #include "chrome/common/extensions/extension_test_util.h" #include "chromeos/login/login_state.h" #include "content/public/browser/resource_request_info.h" +#include "content/public/common/previews_state.h" #include "content/public/test/test_browser_thread_bundle.h" #include "extensions/browser/api/web_request/web_request_permissions.h" #include "extensions/browser/info_map.h" @@ -151,19 +152,15 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, TestHideRequestForURL) { int view_id = 17; std::unique_ptr<net::URLRequest> sensitive_request( context.CreateRequest(non_sensitive_url, net::DEFAULT_PRIORITY, NULL)); - ResourceRequestInfo::AllocateForTesting(sensitive_request.get(), - content::RESOURCE_TYPE_SCRIPT, - NULL, - process_id, - view_id, - MSG_ROUTING_NONE, - false, // is_main_frame - false, // parent_is_main_frame - true, // allow_download - false, // is_async - false); // is_using_lofi - extension_info_map_->RegisterExtensionProcess( - extensions::kWebStoreAppId, process_id, site_instance_id); + ResourceRequestInfo::AllocateForTesting( + sensitive_request.get(), content::RESOURCE_TYPE_SCRIPT, NULL, + process_id, view_id, MSG_ROUTING_NONE, + /*is_main_frame=*/false, + /*parent_is_main_frame=*/false, + /*allow_download=*/true, + /*is_async=*/false, content::PREVIEWS_OFF); + extension_info_map_->RegisterExtensionProcess(extensions::kWebStoreAppId, + process_id, site_instance_id); EXPECT_TRUE(WebRequestPermissions::HideRequest( extension_info_map_.get(), sensitive_request.get(), nullptr)); } diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc index efdf7178daa..edc852f6c1a 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc @@ -29,7 +29,7 @@ namespace extensions { using content::BrowserThread; using content::RenderProcessHost; -using media::AudioDeviceNames; +using media::AudioDeviceDescriptions; using media::AudioManager; namespace wap = api::webrtc_audio_private; @@ -109,28 +109,31 @@ WebrtcAudioPrivateFunction::WebrtcAudioPrivateFunction() {} WebrtcAudioPrivateFunction::~WebrtcAudioPrivateFunction() { } -void WebrtcAudioPrivateFunction::GetOutputDeviceNames() { +void WebrtcAudioPrivateFunction::GetOutputDeviceDescriptions() { scoped_refptr<base::SingleThreadTaskRunner> audio_manager_runner = AudioManager::Get()->GetTaskRunner(); if (!audio_manager_runner->BelongsToCurrentThread()) { DCHECK_CURRENTLY_ON(BrowserThread::UI); audio_manager_runner->PostTask( FROM_HERE, - base::Bind(&WebrtcAudioPrivateFunction::GetOutputDeviceNames, this)); + base::Bind(&WebrtcAudioPrivateFunction::GetOutputDeviceDescriptions, + this)); return; } - std::unique_ptr<AudioDeviceNames> device_names(new AudioDeviceNames); - AudioManager::Get()->GetAudioOutputDeviceNames(device_names.get()); + std::unique_ptr<AudioDeviceDescriptions> device_descriptions = + base::MakeUnique<AudioDeviceDescriptions>(); + AudioManager::Get()->GetAudioOutputDeviceDescriptions( + device_descriptions.get()); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, - base::Bind(&WebrtcAudioPrivateFunction::OnOutputDeviceNames, this, - base::Passed(&device_names))); + base::Bind(&WebrtcAudioPrivateFunction::OnOutputDeviceDescriptions, this, + base::Passed(&device_descriptions))); } -void WebrtcAudioPrivateFunction::OnOutputDeviceNames( - std::unique_ptr<AudioDeviceNames> device_names) { +void WebrtcAudioPrivateFunction::OnOutputDeviceDescriptions( + std::unique_ptr<AudioDeviceDescriptions> device_descriptions) { NOTREACHED(); } @@ -193,7 +196,7 @@ std::string WebrtcAudioPrivateFunction::CalculateHMACImpl( const std::string& raw_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - // We don't hash the default device name, and we always return + // We don't hash the default device description, and we always return // "default" for the default device. There is code in SetActiveSink // that transforms "default" to the empty string, and code in // GetActiveSink that ensures we return "default" if we get the @@ -218,20 +221,20 @@ bool WebrtcAudioPrivateGetSinksFunction::RunAsync() { DCHECK_CURRENTLY_ON(BrowserThread::UI); InitDeviceIDSalt(); - GetOutputDeviceNames(); + GetOutputDeviceDescriptions(); return true; } -void WebrtcAudioPrivateGetSinksFunction::OnOutputDeviceNames( - std::unique_ptr<AudioDeviceNames> raw_ids) { +void WebrtcAudioPrivateGetSinksFunction::OnOutputDeviceDescriptions( + std::unique_ptr<AudioDeviceDescriptions> raw_ids) { DCHECK_CURRENTLY_ON(BrowserThread::IO); std::vector<wap::SinkInfo> results; - for (const media::AudioDeviceName& name : *raw_ids) { + for (const media::AudioDeviceDescription& description : *raw_ids) { wap::SinkInfo info; - info.sink_id = CalculateHMACImpl(name.unique_id); - info.sink_label = name.device_name; + info.sink_id = CalculateHMACImpl(description.unique_id); + info.sink_label = description.device_name; // TODO(joi): Add other parameters. results.push_back(std::move(info)); } @@ -357,15 +360,15 @@ void WebrtcAudioPrivateSetActiveSinkFunction::OnControllerList( base::IntToString(requested_process_id)); SendResponse(false); } else { - // We need to get the output device names, and calculate the HMAC + // We need to get the output device IDs, and calculate the HMAC // for each, to find the raw ID for the ID provided to this API // function call. - GetOutputDeviceNames(); + GetOutputDeviceDescriptions(); } } -void WebrtcAudioPrivateSetActiveSinkFunction::OnOutputDeviceNames( - std::unique_ptr<AudioDeviceNames> device_names) { +void WebrtcAudioPrivateSetActiveSinkFunction::OnOutputDeviceDescriptions( + std::unique_ptr<AudioDeviceDescriptions> device_descriptions) { DCHECK_CURRENTLY_ON(BrowserThread::IO); std::string raw_sink_id; @@ -373,9 +376,9 @@ void WebrtcAudioPrivateSetActiveSinkFunction::OnOutputDeviceNames( DVLOG(2) << "Received default ID, replacing with empty ID."; raw_sink_id = ""; } else { - for (AudioDeviceNames::const_iterator it = device_names->begin(); - it != device_names->end(); - ++it) { + for (AudioDeviceDescriptions::const_iterator it = + device_descriptions->begin(); + it != device_descriptions->end(); ++it) { if (sink_id_ == CalculateHMACImpl(it->unique_id)) { raw_sink_id = it->unique_id; break; @@ -433,7 +436,7 @@ bool WebrtcAudioPrivateGetAssociatedSinkFunction::RunAsync() { void WebrtcAudioPrivateGetAssociatedSinkFunction::GetDevicesOnDeviceThread() { DCHECK(AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); - AudioManager::Get()->GetAudioInputDeviceNames(&source_devices_); + AudioManager::Get()->GetAudioInputDeviceDescriptions(&source_devices_); BrowserThread::PostTask( BrowserThread::IO, @@ -452,9 +455,8 @@ WebrtcAudioPrivateGetAssociatedSinkFunction::GetRawSourceIDOnIOThread() { // Find the raw source ID for source_id_in_origin. std::string raw_source_id; - for (AudioDeviceNames::const_iterator it = source_devices_.begin(); - it != source_devices_.end(); - ++it) { + for (AudioDeviceDescriptions::const_iterator it = source_devices_.begin(); + it != source_devices_.end(); ++it) { const std::string& id = it->unique_id; if (content::DoesMediaDeviceIDMatchHMAC(device_id_salt(), security_origin, source_id_in_origin, id)) { diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h index e10607993d8..fda70d7faee 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h @@ -17,7 +17,7 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/resource_context.h" #include "extensions/browser/browser_context_keyed_api_factory.h" -#include "media/audio/audio_device_name.h" +#include "media/audio/audio_device_description.h" namespace extensions { @@ -54,13 +54,14 @@ class WebrtcAudioPrivateFunction : public ChromeAsyncExtensionFunction { ~WebrtcAudioPrivateFunction() override; protected: - // Retrieves the list of output device names on the appropriate + // Retrieves the list of output device descriptions on the appropriate // thread. Call from UI thread, callback will occur on IO thread. - void GetOutputDeviceNames(); + void GetOutputDeviceDescriptions(); - // Must override this if you call GetOutputDeviceNames. Called on IO thread. - virtual void OnOutputDeviceNames( - std::unique_ptr<media::AudioDeviceNames> device_names); + // Must override this if you call GetOutputDeviceDescriptions. Called on IO + // thread. + virtual void OnOutputDeviceDescriptions( + std::unique_ptr<media::AudioDeviceDescriptions> device_descriptions); // Retrieve the list of AudioOutputController objects. Calls back // via OnControllerList. @@ -119,8 +120,8 @@ class WebrtcAudioPrivateGetSinksFunction : public WebrtcAudioPrivateFunction { // then finish on the UI thread. bool RunAsync() override; void DoQuery(); - void OnOutputDeviceNames( - std::unique_ptr<media::AudioDeviceNames> raw_ids) override; + void OnOutputDeviceDescriptions( + std::unique_ptr<media::AudioDeviceDescriptions> raw_ids) override; void DoneOnUIThread(); }; @@ -156,8 +157,9 @@ class WebrtcAudioPrivateSetActiveSinkFunction void OnControllerList( const content::RenderProcessHost::AudioOutputControllerList& controllers) override; - void OnOutputDeviceNames( - std::unique_ptr<media::AudioDeviceNames> device_names) override; + void OnOutputDeviceDescriptions( + std::unique_ptr<media::AudioDeviceDescriptions> device_descriptions) + override; void SwitchDone(); void DoneOnUIThread(); @@ -204,7 +206,7 @@ class WebrtcAudioPrivateGetAssociatedSinkFunction // Fills in |source_devices_|. Note that these are input devices, // not output devices, so don't use - // |WebrtcAudioPrivateFunction::GetOutputDeviceNames|. + // |WebrtcAudioPrivateFunction::GetOutputDeviceDescriptions|. void GetDevicesOnDeviceThread(); // Takes the parameters of the function, retrieves the raw source @@ -222,7 +224,7 @@ class WebrtcAudioPrivateGetAssociatedSinkFunction std::unique_ptr<api::webrtc_audio_private::GetAssociatedSink::Params> params_; // Audio sources (input devices). Filled in by DoWorkOnDeviceThread. - media::AudioDeviceNames source_devices_; + media::AudioDeviceDescriptions source_devices_; }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc index 2463eb8f6e8..924d427d576 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc @@ -15,7 +15,6 @@ #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" -#include "base/win/windows_version.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h" @@ -40,10 +39,14 @@ #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" +#if defined(OS_WIN) +#include "base/win/windows_version.h" +#endif + using base::JSONWriter; using content::RenderProcessHost; using content::WebContents; -using media::AudioDeviceNames; +using media::AudioDeviceDescriptions; using media::AudioManager; namespace extensions { @@ -129,22 +132,22 @@ class WebrtcAudioPrivateTest : public AudioWaitingExtensionTest { // Synchronously (from the calling thread's point of view) runs the // given enumeration function on the device thread. On return, - // |device_names| has been filled with the device names resulting - // from that call. - void GetAudioDeviceNames( - void (AudioManager::*EnumerationFunc)(AudioDeviceNames*), - AudioDeviceNames* device_names) { + // |device_descriptions| has been filled with the device descriptions + // resulting from that call. + void GetAudioDeviceDescriptions( + void (AudioManager::*EnumerationFunc)(AudioDeviceDescriptions*), + AudioDeviceDescriptions* device_descriptions) { AudioManager* audio_manager = AudioManager::Get(); if (!audio_manager->GetTaskRunner()->BelongsToCurrentThread()) { audio_manager->GetTaskRunner()->PostTask( FROM_HERE, - base::Bind(&WebrtcAudioPrivateTest::GetAudioDeviceNames, - base::Unretained(this), - EnumerationFunc, device_names)); + base::Bind(&WebrtcAudioPrivateTest::GetAudioDeviceDescriptions, + base::Unretained(this), EnumerationFunc, + device_descriptions)); enumeration_event_.Wait(); } else { - (audio_manager->*EnumerationFunc)(device_names); + (audio_manager->*EnumerationFunc)(device_descriptions); enumeration_event_.Signal(); } } @@ -181,8 +184,9 @@ class WebrtcAudioPrivateTest : public AudioWaitingExtensionTest { #if !defined(OS_MACOSX) // http://crbug.com/334579 IN_PROC_BROWSER_TEST_F(WebrtcAudioPrivateTest, GetSinks) { - AudioDeviceNames devices; - GetAudioDeviceNames(&AudioManager::GetAudioOutputDeviceNames, &devices); + AudioDeviceDescriptions devices; + GetAudioDeviceDescriptions(&AudioManager::GetAudioOutputDeviceDescriptions, + &devices); base::ListValue* sink_list = NULL; std::unique_ptr<base::Value> result = InvokeGetSinks(&sink_list); @@ -196,7 +200,7 @@ IN_PROC_BROWSER_TEST_F(WebrtcAudioPrivateTest, GetSinks) { // Iterate through both lists in lockstep and compare. The order // should be identical. size_t ix = 0; - AudioDeviceNames::const_iterator it = devices.begin(); + AudioDeviceDescriptions::const_iterator it = devices.begin(); for (; ix < sink_list->GetSize() && it != devices.end(); ++ix, ++it) { base::DictionaryValue* dict = NULL; @@ -332,18 +336,17 @@ IN_PROC_BROWSER_TEST_F(WebrtcAudioPrivateTest, GetAssociatedSink) { // Get the list of input devices. We can cheat in the unit test and // run this on the main thread since nobody else will be running at // the same time. - AudioDeviceNames devices; - GetAudioDeviceNames(&AudioManager::GetAudioInputDeviceNames, &devices); + AudioDeviceDescriptions devices; + GetAudioDeviceDescriptions(&AudioManager::GetAudioInputDeviceDescriptions, + &devices); // Try to get an associated sink for each source. - for (AudioDeviceNames::const_iterator device = devices.begin(); - device != devices.end(); - ++device) { + for (const auto& device : devices) { scoped_refptr<WebrtcAudioPrivateGetAssociatedSinkFunction> function = new WebrtcAudioPrivateGetAssociatedSinkFunction(); function->set_source_url(source_url_); - std::string raw_device_id = device->unique_id; + std::string raw_device_id = device.unique_id; VLOG(2) << "Trying to find associated sink for device " << raw_device_id; std::string source_id_in_origin; GURL origin(GURL("http://www.google.com/").GetOrigin()); diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc index b000d228473..5d6f56959cf 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc @@ -65,31 +65,30 @@ content::RenderProcessHost* WebrtcLoggingPrivateFunction::RphFromRequest( // Otherwise, use the |tab_id|. If there's no |tab_id| and no // |guest_process_id|, we can't look up the RenderProcessHost. - if (!request.tab_id.get()) - return NULL; + if (!request.tab_id.get()) { + error_ = "No tab ID or guest process ID specified."; + return nullptr; + } int tab_id = *request.tab_id; - content::WebContents* contents = NULL; - if (!ExtensionTabUtil::GetTabById( - tab_id, GetProfile(), true, NULL, NULL, &contents, NULL)) { + content::WebContents* contents = nullptr; + if (!ExtensionTabUtil::GetTabById(tab_id, GetProfile(), true, nullptr, + nullptr, &contents, nullptr)) { error_ = extensions::ErrorUtils::FormatErrorMessage( extensions::tabs_constants::kTabNotFoundError, base::IntToString(tab_id)); - return NULL; + return nullptr; } if (!contents) { - error_ = extensions::ErrorUtils::FormatErrorMessage( - "Web contents for tab not found", - base::IntToString(tab_id)); - return NULL; + error_ = "Web contents for tab not found."; + return nullptr; } GURL expected_origin = contents->GetLastCommittedURL().GetOrigin(); if (expected_origin.spec() != security_origin) { - error_ = extensions::ErrorUtils::FormatErrorMessage( - "Invalid security origin. Expected=" + expected_origin.spec() + - ", actual=" + security_origin, - base::IntToString(tab_id)); - return NULL; + error_ = base::StringPrintf( + "Invalid security origin. Expected=%s, actual=%s", + expected_origin.spec().c_str(), security_origin.c_str()); + return nullptr; } return contents->GetRenderProcessHost(); } diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h index 8fdf3509234..213b75c5434 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h @@ -8,12 +8,14 @@ #include <string> #include "chrome/browser/extensions/chrome_extension_function.h" -#if defined(ENABLE_WEBRTC) +#include "chrome/common/extensions/api/webrtc_logging_private.h" +#include "media/media_features.h" + +#if BUILDFLAG(ENABLE_WEBRTC) #include "chrome/browser/media/audio_debug_recordings_handler.h" #include "chrome/browser/media/webrtc/webrtc_event_log_handler.h" #include "chrome/browser/media/webrtc/webrtc_logging_handler_host.h" #endif -#include "chrome/common/extensions/api/webrtc_logging_private.h" namespace content { @@ -27,7 +29,7 @@ class WebrtcLoggingPrivateFunction : public ChromeAsyncExtensionFunction { protected: ~WebrtcLoggingPrivateFunction() override {} -#if defined(ENABLE_WEBRTC) +#if BUILDFLAG(ENABLE_WEBRTC) // Returns the RenderProcessHost associated with the given |request| // authorized by the |security_origin|. Returns null if unauthorized or // the RPH does not exist. @@ -46,7 +48,7 @@ class WebrtcLoggingPrivateFunctionWithGenericCallback protected: ~WebrtcLoggingPrivateFunctionWithGenericCallback() override {} -#if defined(ENABLE_WEBRTC) +#if BUILDFLAG(ENABLE_WEBRTC) // Finds the appropriate logging handler for performing the task and prepares // a generic callback object for when the task is completed. // If the logging handler can't be found for the given request+origin, the @@ -66,7 +68,7 @@ class WebrtcLoggingPrivateFunctionWithUploadCallback protected: ~WebrtcLoggingPrivateFunctionWithUploadCallback() override {} -#if defined(ENABLE_WEBRTC) +#if BUILDFLAG(ENABLE_WEBRTC) // Must be called on UI thread. void FireCallback(bool success, const std::string& report_id, const std::string& error_message); @@ -78,7 +80,7 @@ class WebrtcLoggingPrivateFunctionWithRecordingDoneCallback protected: ~WebrtcLoggingPrivateFunctionWithRecordingDoneCallback() override {} -#if defined(ENABLE_WEBRTC) +#if BUILDFLAG(ENABLE_WEBRTC) // Must be called on UI thread. void FireErrorCallback(const std::string& error_message); void FireCallback(const std::string& prefix_path, diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc index 8f394423414..8c19e597a32 100644 --- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc +++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc @@ -10,8 +10,8 @@ #include "base/bind.h" #include "base/lazy_instance.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" -#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h index 6a7f2ef009e..821208dcb67 100644 --- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h +++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h @@ -20,11 +20,6 @@ #include "third_party/skia/include/core/SkBitmap.h" class GPUFeatureChecker; -class GURL; - -namespace chrome { -class BitmapFetcher; -} // namespace chrome namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc index 0bdcebc704a..2fb92ddeeb3 100644 --- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc @@ -7,7 +7,6 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/macros.h" -#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/chrome_notification_types.h" @@ -403,7 +402,7 @@ class ExtensionWebstoreGetWebGLStatusTest : public InProcessBrowserTest { std::unique_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult( function.get(), kEmptyArgs, browser())); ASSERT_TRUE(result); - EXPECT_EQ(base::Value::TYPE_STRING, result->GetType()); + EXPECT_EQ(base::Value::Type::STRING, result->GetType()); std::string webgl_status; EXPECT_TRUE(result->GetAsString(&webgl_status)); EXPECT_STREQ(webgl_allowed ? kWebGLStatusAllowed : kWebGLStatusBlocked, |