Adding instrumentation to locate the source of jankiness
[chromium-blink-merge.git] / chrome / browser / extensions / active_script_controller.cc
blobf3b73b933f6c266192b7e870578f072b3ef13e7f
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/active_script_controller.h"
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/metrics/histogram.h"
11 #include "base/stl_util.h"
12 #include "chrome/browser/extensions/active_tab_permission_granter.h"
13 #include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
14 #include "chrome/browser/extensions/extension_action.h"
15 #include "chrome/browser/extensions/extension_action_manager.h"
16 #include "chrome/browser/extensions/extension_util.h"
17 #include "chrome/browser/extensions/permissions_updater.h"
18 #include "chrome/browser/extensions/tab_helper.h"
19 #include "chrome/browser/profiles/profile.h"
20 #include "chrome/browser/sessions/session_tab_helper.h"
21 #include "chrome/common/extensions/api/extension_action/action_info.h"
22 #include "components/crx_file/id_util.h"
23 #include "content/public/browser/navigation_controller.h"
24 #include "content/public/browser/navigation_details.h"
25 #include "content/public/browser/navigation_entry.h"
26 #include "content/public/browser/render_view_host.h"
27 #include "content/public/browser/web_contents.h"
28 #include "extensions/browser/extension_registry.h"
29 #include "extensions/common/extension.h"
30 #include "extensions/common/extension_messages.h"
31 #include "extensions/common/extension_set.h"
32 #include "extensions/common/feature_switch.h"
33 #include "extensions/common/manifest.h"
34 #include "extensions/common/permissions/permission_set.h"
35 #include "extensions/common/permissions/permissions_data.h"
36 #include "ipc/ipc_message_macros.h"
38 namespace extensions {
40 namespace {
42 // Returns true if the extension should be regarded as a "permitted" extension
43 // for the case of metrics. We need this because we only actually withhold
44 // permissions if the switch is enabled, but want to record metrics in all
45 // cases.
46 // "ExtensionWouldHaveHadHostPermissionsWithheldIfSwitchWasOn()" would be
47 // more accurate, but too long.
48 bool ShouldRecordExtension(const Extension* extension) {
49 return extension->ShouldDisplayInExtensionSettings() &&
50 !Manifest::IsPolicyLocation(extension->location()) &&
51 !Manifest::IsComponentLocation(extension->location()) &&
52 !PermissionsData::CanExecuteScriptEverywhere(extension) &&
53 extension->permissions_data()
54 ->active_permissions()
55 ->ShouldWarnAllHosts();
58 } // namespace
60 ActiveScriptController::ActiveScriptController(
61 content::WebContents* web_contents)
62 : content::WebContentsObserver(web_contents),
63 browser_context_(web_contents->GetBrowserContext()),
64 enabled_(FeatureSwitch::scripts_require_action()->IsEnabled()),
65 extension_registry_observer_(this) {
66 CHECK(web_contents);
67 extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_));
70 ActiveScriptController::~ActiveScriptController() {
71 LogUMA();
74 // static
75 ActiveScriptController* ActiveScriptController::GetForWebContents(
76 content::WebContents* web_contents) {
77 if (!web_contents)
78 return NULL;
79 TabHelper* tab_helper = TabHelper::FromWebContents(web_contents);
80 return tab_helper ? tab_helper->active_script_controller() : NULL;
83 void ActiveScriptController::OnActiveTabPermissionGranted(
84 const Extension* extension) {
85 RunPendingForExtension(extension);
88 void ActiveScriptController::OnAdInjectionDetected(
89 const std::set<std::string>& ad_injectors) {
90 // We're only interested in data if there are ad injectors detected.
91 if (ad_injectors.empty())
92 return;
94 size_t num_preventable_ad_injectors =
95 base::STLSetIntersection<std::set<std::string> >(
96 ad_injectors, permitted_extensions_).size();
98 UMA_HISTOGRAM_COUNTS_100(
99 "Extensions.ActiveScriptController.PreventableAdInjectors",
100 num_preventable_ad_injectors);
101 UMA_HISTOGRAM_COUNTS_100(
102 "Extensions.ActiveScriptController.UnpreventableAdInjectors",
103 ad_injectors.size() - num_preventable_ad_injectors);
106 void ActiveScriptController::AlwaysRunOnVisibleOrigin(
107 const Extension* extension) {
108 const GURL& url = web_contents()->GetVisibleURL();
109 URLPatternSet new_explicit_hosts;
110 URLPatternSet new_scriptable_hosts;
112 scoped_refptr<const PermissionSet> withheld_permissions =
113 extension->permissions_data()->withheld_permissions();
114 if (withheld_permissions->explicit_hosts().MatchesURL(url)) {
115 new_explicit_hosts.AddOrigin(UserScript::ValidUserScriptSchemes(),
116 url.GetOrigin());
118 if (withheld_permissions->scriptable_hosts().MatchesURL(url)) {
119 new_scriptable_hosts.AddOrigin(UserScript::ValidUserScriptSchemes(),
120 url.GetOrigin());
123 scoped_refptr<PermissionSet> new_permissions =
124 new PermissionSet(APIPermissionSet(),
125 ManifestPermissionSet(),
126 new_explicit_hosts,
127 new_scriptable_hosts);
129 // Update permissions for the session. This adds |new_permissions| to active
130 // permissions and granted permissions.
131 // TODO(devlin): Make sure that the permission is removed from
132 // withheld_permissions if appropriate.
133 PermissionsUpdater(browser_context_).AddPermissions(extension,
134 new_permissions.get());
136 // Allow current tab to run injection.
137 OnClicked(extension);
140 void ActiveScriptController::OnClicked(const Extension* extension) {
141 DCHECK(ContainsKey(pending_requests_, extension->id()));
142 RunPendingForExtension(extension);
145 bool ActiveScriptController::WantsToRun(const Extension* extension) {
146 return enabled_ && pending_requests_.count(extension->id()) > 0;
149 PermissionsData::AccessType
150 ActiveScriptController::RequiresUserConsentForScriptInjection(
151 const Extension* extension,
152 UserScript::InjectionType type) {
153 CHECK(extension);
155 // If the feature is not enabled, we automatically allow all extensions to
156 // run scripts.
157 if (!enabled_)
158 permitted_extensions_.insert(extension->id());
160 // Allow the extension if it's been explicitly granted permission.
161 if (permitted_extensions_.count(extension->id()) > 0)
162 return PermissionsData::ACCESS_ALLOWED;
164 GURL url = web_contents()->GetVisibleURL();
165 int tab_id = SessionTabHelper::IdForTab(web_contents());
166 switch (type) {
167 case UserScript::CONTENT_SCRIPT:
168 return extension->permissions_data()->GetContentScriptAccess(
169 extension, url, url, tab_id, -1, NULL);
170 case UserScript::PROGRAMMATIC_SCRIPT:
171 return extension->permissions_data()->GetPageAccess(
172 extension, url, url, tab_id, -1, NULL);
175 NOTREACHED();
176 return PermissionsData::ACCESS_DENIED;
179 void ActiveScriptController::RequestScriptInjection(
180 const Extension* extension,
181 const base::Closure& callback) {
182 CHECK(extension);
183 PendingRequestList& list = pending_requests_[extension->id()];
184 list.push_back(callback);
186 // If this was the first entry, we need to notify that a new extension wants
187 // to run.
188 if (list.size() == 1u)
189 NotifyChange(extension);
192 void ActiveScriptController::RunPendingForExtension(
193 const Extension* extension) {
194 DCHECK(extension);
196 content::NavigationEntry* visible_entry =
197 web_contents()->GetController().GetVisibleEntry();
198 // Refuse to run if there's no visible entry, because we have no idea of
199 // determining if it's the proper page. This should rarely, if ever, happen.
200 if (!visible_entry)
201 return;
203 // We add this to the list of permitted extensions and erase pending entries
204 // *before* running them to guard against the crazy case where running the
205 // callbacks adds more entries.
206 permitted_extensions_.insert(extension->id());
208 PendingRequestMap::iterator iter = pending_requests_.find(extension->id());
209 if (iter == pending_requests_.end())
210 return;
212 PendingRequestList requests;
213 iter->second.swap(requests);
214 pending_requests_.erase(extension->id());
216 // Clicking to run the extension counts as granting it permission to run on
217 // the given tab.
218 // The extension may already have active tab at this point, but granting
219 // it twice is essentially a no-op.
220 TabHelper::FromWebContents(web_contents())->
221 active_tab_permission_granter()->GrantIfRequested(extension);
223 // Run all pending injections for the given extension.
224 for (PendingRequestList::iterator request = requests.begin();
225 request != requests.end();
226 ++request) {
227 request->Run();
230 // The extension ran, so we need to update the ExtensionActionAPI that we no
231 // longer want to act.
232 NotifyChange(extension);
235 void ActiveScriptController::OnRequestScriptInjectionPermission(
236 const std::string& extension_id,
237 UserScript::InjectionType script_type,
238 int64 request_id) {
239 if (!crx_file::id_util::IdIsValid(extension_id)) {
240 NOTREACHED() << "'" << extension_id << "' is not a valid id.";
241 return;
244 const Extension* extension =
245 ExtensionRegistry::Get(browser_context_)
246 ->enabled_extensions().GetByID(extension_id);
247 // We shouldn't allow extensions which are no longer enabled to run any
248 // scripts. Ignore the request.
249 if (!extension)
250 return;
252 // If the request id is -1, that signals that the content script has already
253 // ran (because this feature is not enabled). Add the extension to the list of
254 // permitted extensions (for metrics), and return immediately.
255 if (request_id == -1) {
256 if (ShouldRecordExtension(extension)) {
257 DCHECK(!enabled_);
258 permitted_extensions_.insert(extension->id());
260 return;
263 switch (RequiresUserConsentForScriptInjection(extension, script_type)) {
264 case PermissionsData::ACCESS_ALLOWED:
265 PermitScriptInjection(request_id);
266 break;
267 case PermissionsData::ACCESS_WITHHELD:
268 // This base::Unretained() is safe, because the callback is only invoked
269 // by this object.
270 RequestScriptInjection(
271 extension,
272 base::Bind(&ActiveScriptController::PermitScriptInjection,
273 base::Unretained(this),
274 request_id));
275 break;
276 case PermissionsData::ACCESS_DENIED:
277 // We should usually only get a "deny access" if the page changed (as the
278 // renderer wouldn't have requested permission if the answer was always
279 // "no"). Just let the request fizzle and die.
280 break;
284 void ActiveScriptController::PermitScriptInjection(int64 request_id) {
285 // This only sends the response to the renderer - the process of adding the
286 // extension to the list of |permitted_extensions_| is done elsewhere.
287 content::RenderViewHost* render_view_host =
288 web_contents()->GetRenderViewHost();
289 if (render_view_host) {
290 render_view_host->Send(new ExtensionMsg_PermitScriptInjection(
291 render_view_host->GetRoutingID(), request_id));
295 void ActiveScriptController::NotifyChange(const Extension* extension) {
296 ExtensionActionAPI* extension_action_api =
297 ExtensionActionAPI::Get(browser_context_);
298 ExtensionAction* extension_action =
299 ExtensionActionManager::Get(browser_context_)->
300 GetExtensionAction(*extension);
301 // If the extension has an action, we need to notify that it's updated.
302 if (extension_action) {
303 extension_action_api->NotifyChange(
304 extension_action, web_contents(), browser_context_);
307 // We also notify that page actions may have changed.
308 extension_action_api->NotifyPageActionsChanged(web_contents());
311 void ActiveScriptController::LogUMA() const {
312 UMA_HISTOGRAM_COUNTS_100(
313 "Extensions.ActiveScriptController.ShownActiveScriptsOnPage",
314 pending_requests_.size());
316 // We only log the permitted extensions metric if the feature is enabled,
317 // because otherwise the data will be boring (100% allowed).
318 if (enabled_) {
319 UMA_HISTOGRAM_COUNTS_100(
320 "Extensions.ActiveScriptController.PermittedExtensions",
321 permitted_extensions_.size());
322 UMA_HISTOGRAM_COUNTS_100(
323 "Extensions.ActiveScriptController.DeniedExtensions",
324 pending_requests_.size());
328 bool ActiveScriptController::OnMessageReceived(const IPC::Message& message) {
329 bool handled = true;
330 IPC_BEGIN_MESSAGE_MAP(ActiveScriptController, message)
331 IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestScriptInjectionPermission,
332 OnRequestScriptInjectionPermission)
333 IPC_MESSAGE_UNHANDLED(handled = false)
334 IPC_END_MESSAGE_MAP()
335 return handled;
338 void ActiveScriptController::DidNavigateMainFrame(
339 const content::LoadCommittedDetails& details,
340 const content::FrameNavigateParams& params) {
341 if (details.is_in_page)
342 return;
344 LogUMA();
345 permitted_extensions_.clear();
346 pending_requests_.clear();
349 void ActiveScriptController::OnExtensionUnloaded(
350 content::BrowserContext* browser_context,
351 const Extension* extension,
352 UnloadedExtensionInfo::Reason reason) {
353 PendingRequestMap::iterator iter = pending_requests_.find(extension->id());
354 if (iter != pending_requests_.end()) {
355 pending_requests_.erase(iter);
356 ExtensionActionAPI::Get(browser_context_)->
357 NotifyPageActionsChanged(web_contents());
361 } // namespace extensions