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 "extensions/browser/extension_function_dispatcher.h"
8 #include "base/json/json_string_value_serializer.h"
9 #include "base/lazy_instance.h"
10 #include "base/logging.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/metrics/histogram_macros.h"
13 #include "base/metrics/sparse_histogram.h"
14 #include "base/process/process.h"
15 #include "base/profiler/scoped_profile.h"
16 #include "base/values.h"
17 #include "build/build_config.h"
18 #include "content/public/browser/browser_thread.h"
19 #include "content/public/browser/render_frame_host.h"
20 #include "content/public/browser/render_process_host.h"
21 #include "content/public/browser/render_view_host.h"
22 #include "content/public/browser/user_metrics.h"
23 #include "content/public/browser/web_contents.h"
24 #include "content/public/browser/web_contents_observer.h"
25 #include "content/public/common/result_codes.h"
26 #include "extensions/browser/api_activity_monitor.h"
27 #include "extensions/browser/extension_function_registry.h"
28 #include "extensions/browser/extension_registry.h"
29 #include "extensions/browser/extension_system.h"
30 #include "extensions/browser/extensions_browser_client.h"
31 #include "extensions/browser/io_thread_extension_message_filter.h"
32 #include "extensions/browser/process_manager.h"
33 #include "extensions/browser/process_map.h"
34 #include "extensions/browser/quota_service.h"
35 #include "extensions/common/extension_api.h"
36 #include "extensions/common/extension_messages.h"
37 #include "extensions/common/extension_set.h"
38 #include "ipc/ipc_message.h"
39 #include "ipc/ipc_message_macros.h"
41 using content::BrowserThread
;
42 using content::RenderViewHost
;
44 namespace extensions
{
47 // Notifies the ApiActivityMonitor that an extension API function has been
48 // called. May be called from any thread.
49 void NotifyApiFunctionCalled(const std::string
& extension_id
,
50 const std::string
& api_name
,
51 scoped_ptr
<base::ListValue
> args
,
52 content::BrowserContext
* browser_context
) {
53 // The ApiActivityMonitor can only be accessed from the main (UI) thread. If
54 // we're running on the wrong thread, re-dispatch from the main thread.
55 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
)) {
56 BrowserThread::PostTask(BrowserThread::UI
,
58 base::Bind(&NotifyApiFunctionCalled
,
65 // The BrowserContext may become invalid after the task above is posted.
66 if (!ExtensionsBrowserClient::Get()->IsValidContext(browser_context
))
69 ApiActivityMonitor
* monitor
=
70 ExtensionsBrowserClient::Get()->GetApiActivityMonitor(browser_context
);
72 monitor
->OnApiFunctionCalled(extension_id
, api_name
, args
.Pass());
75 // Separate copy of ExtensionAPI used for IO thread extension functions. We need
76 // this because ExtensionAPI has mutable data. It should be possible to remove
77 // this once all the extension APIs are updated to the feature system.
79 Static() : api(ExtensionAPI::CreateWithDefaultConfiguration()) {}
80 scoped_ptr
<ExtensionAPI
> api
;
82 base::LazyInstance
<Static
> g_global_io_data
= LAZY_INSTANCE_INITIALIZER
;
84 // Kills the specified process because it sends us a malformed message.
85 // Track the specific function's |histogram_value|, as this may indicate a bug
86 // in that API's implementation on the renderer.
87 void KillBadMessageSender(const base::Process
& process
,
88 functions::HistogramValue histogram_value
) {
90 content::RecordAction(base::UserMetricsAction("BadMessageTerminate_EFD"));
91 UMA_HISTOGRAM_ENUMERATION("Extensions.BadMessageFunctionName",
92 histogram_value
, functions::ENUM_BOUNDARY
);
93 if (process
.IsValid())
94 process
.Terminate(content::RESULT_CODE_KILLED_BAD_MESSAGE
, false);
97 void CommonResponseCallback(IPC::Sender
* ipc_sender
,
99 const base::Process
& peer_process
,
101 ExtensionFunction::ResponseType type
,
102 const base::ListValue
& results
,
103 const std::string
& error
,
104 functions::HistogramValue histogram_value
) {
107 if (type
== ExtensionFunction::BAD_MESSAGE
) {
108 // The renderer has done validation before sending extension api requests.
109 // Therefore, we should never receive a request that is invalid in a way
110 // that JSON validation in the renderer should have caught. It could be an
111 // attacker trying to exploit the browser, so we crash the renderer instead.
113 "Terminating renderer because of malformed extension message.";
114 if (content::RenderProcessHost::run_renderer_in_process()) {
115 // In single process mode it is better if we don't suicide but just crash.
118 KillBadMessageSender(peer_process
, histogram_value
);
123 ipc_sender
->Send(new ExtensionMsg_Response(
124 routing_id
, request_id
, type
== ExtensionFunction::SUCCEEDED
, results
,
128 void IOThreadResponseCallback(
129 const base::WeakPtr
<IOThreadExtensionMessageFilter
>& ipc_sender
,
132 ExtensionFunction::ResponseType type
,
133 const base::ListValue
& results
,
134 const std::string
& error
,
135 functions::HistogramValue histogram_value
) {
136 if (!ipc_sender
.get())
139 base::Process peer_process
=
140 base::Process::DeprecatedGetProcessFromHandle(ipc_sender
->PeerHandle());
141 CommonResponseCallback(ipc_sender
.get(), routing_id
, peer_process
, request_id
,
142 type
, results
, error
, histogram_value
);
147 class ExtensionFunctionDispatcher::UIThreadResponseCallbackWrapper
148 : public content::WebContentsObserver
{
150 UIThreadResponseCallbackWrapper(
151 const base::WeakPtr
<ExtensionFunctionDispatcher
>& dispatcher
,
152 RenderViewHost
* render_view_host
)
153 : content::WebContentsObserver(
154 content::WebContents::FromRenderViewHost(render_view_host
)),
155 dispatcher_(dispatcher
),
156 render_view_host_(render_view_host
),
157 weak_ptr_factory_(this) {
160 ~UIThreadResponseCallbackWrapper() override
{}
162 // content::WebContentsObserver overrides.
163 void RenderViewDeleted(RenderViewHost
* render_view_host
) override
{
164 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
165 if (render_view_host
!= render_view_host_
)
168 if (dispatcher_
.get()) {
169 dispatcher_
->ui_thread_response_callback_wrappers_
170 .erase(render_view_host
);
176 ExtensionFunction::ResponseCallback
CreateCallback(int request_id
) {
178 &UIThreadResponseCallbackWrapper::OnExtensionFunctionCompleted
,
179 weak_ptr_factory_
.GetWeakPtr(),
184 void OnExtensionFunctionCompleted(int request_id
,
185 ExtensionFunction::ResponseType type
,
186 const base::ListValue
& results
,
187 const std::string
& error
,
188 functions::HistogramValue histogram_value
) {
189 base::Process process
=
190 content::RenderProcessHost::run_renderer_in_process()
191 ? base::Process::Current()
192 : base::Process::DeprecatedGetProcessFromHandle(
193 render_view_host_
->GetProcess()->GetHandle());
194 CommonResponseCallback(render_view_host_
, render_view_host_
->GetRoutingID(),
195 process
, request_id
, type
, results
, error
,
199 base::WeakPtr
<ExtensionFunctionDispatcher
> dispatcher_
;
200 content::RenderViewHost
* render_view_host_
;
201 base::WeakPtrFactory
<UIThreadResponseCallbackWrapper
> weak_ptr_factory_
;
203 DISALLOW_COPY_AND_ASSIGN(UIThreadResponseCallbackWrapper
);
207 ExtensionFunctionDispatcher::Delegate::GetExtensionWindowController() const {
211 content::WebContents
*
212 ExtensionFunctionDispatcher::Delegate::GetAssociatedWebContents() const {
216 content::WebContents
*
217 ExtensionFunctionDispatcher::Delegate::GetVisibleWebContents() const {
218 return GetAssociatedWebContents();
221 void ExtensionFunctionDispatcher::GetAllFunctionNames(
222 std::vector
<std::string
>* names
) {
223 ExtensionFunctionRegistry::GetInstance()->GetAllNames(names
);
226 bool ExtensionFunctionDispatcher::OverrideFunction(
227 const std::string
& name
, ExtensionFunctionFactory factory
) {
228 return ExtensionFunctionRegistry::GetInstance()->OverrideFunction(name
,
233 void ExtensionFunctionDispatcher::DispatchOnIOThread(
234 InfoMap
* extension_info_map
,
236 int render_process_id
,
237 base::WeakPtr
<IOThreadExtensionMessageFilter
> ipc_sender
,
239 const ExtensionHostMsg_Request_Params
& params
) {
240 const Extension
* extension
=
241 extension_info_map
->extensions().GetByID(params
.extension_id
);
243 ExtensionFunction::ResponseCallback
callback(
244 base::Bind(&IOThreadResponseCallback
, ipc_sender
, routing_id
,
247 scoped_refptr
<ExtensionFunction
> function(
248 CreateExtensionFunction(params
,
251 extension_info_map
->process_map(),
252 g_global_io_data
.Get().api
.get(),
258 IOThreadExtensionFunction
* function_io
=
259 function
->AsIOThreadExtensionFunction();
264 function_io
->set_ipc_sender(ipc_sender
, routing_id
);
265 function_io
->set_extension_info_map(extension_info_map
);
267 function
->set_include_incognito(
268 extension_info_map
->IsIncognitoEnabled(extension
->id()));
271 if (!CheckPermissions(function
.get(), params
, callback
))
275 // Skip all of the UMA, quota, event page, activity logging stuff if there
276 // isn't an extension, e.g. if the function call was from WebUI.
277 function
->Run()->Execute();
281 QuotaService
* quota
= extension_info_map
->GetQuotaService();
282 std::string violation_error
= quota
->Assess(extension
->id(),
285 base::TimeTicks::Now());
286 if (violation_error
.empty()) {
287 scoped_ptr
<base::ListValue
> args(params
.arguments
.DeepCopy());
288 NotifyApiFunctionCalled(extension
->id(),
291 static_cast<content::BrowserContext
*>(profile_id
));
292 UMA_HISTOGRAM_SPARSE_SLOWLY("Extensions.FunctionCalls",
293 function
->histogram_value());
294 tracked_objects::ScopedProfile
scoped_profile(
295 FROM_HERE_WITH_EXPLICIT_FUNCTION(function
->name()),
296 tracked_objects::ScopedProfile::ENABLED
);
297 function
->Run()->Execute();
299 function
->OnQuotaExceeded(violation_error
);
303 ExtensionFunctionDispatcher::ExtensionFunctionDispatcher(
304 content::BrowserContext
* browser_context
,
306 : browser_context_(browser_context
),
307 delegate_(delegate
) {
310 ExtensionFunctionDispatcher::~ExtensionFunctionDispatcher() {
313 void ExtensionFunctionDispatcher::Dispatch(
314 const ExtensionHostMsg_Request_Params
& params
,
315 RenderViewHost
* render_view_host
) {
316 UIThreadResponseCallbackWrapperMap::const_iterator
317 iter
= ui_thread_response_callback_wrappers_
.find(render_view_host
);
318 UIThreadResponseCallbackWrapper
* callback_wrapper
= NULL
;
319 if (iter
== ui_thread_response_callback_wrappers_
.end()) {
320 callback_wrapper
= new UIThreadResponseCallbackWrapper(AsWeakPtr(),
322 ui_thread_response_callback_wrappers_
[render_view_host
] = callback_wrapper
;
324 callback_wrapper
= iter
->second
;
327 DispatchWithCallbackInternal(
328 params
, render_view_host
, NULL
,
329 callback_wrapper
->CreateCallback(params
.request_id
));
332 void ExtensionFunctionDispatcher::DispatchWithCallbackInternal(
333 const ExtensionHostMsg_Request_Params
& params
,
334 RenderViewHost
* render_view_host
,
335 content::RenderFrameHost
* render_frame_host
,
336 const ExtensionFunction::ResponseCallback
& callback
) {
337 DCHECK(render_view_host
|| render_frame_host
);
338 // TODO(yzshen): There is some shared logic between this method and
339 // DispatchOnIOThread(). It is nice to deduplicate.
340 ProcessMap
* process_map
= ProcessMap::Get(browser_context_
);
344 ExtensionRegistry
* registry
= ExtensionRegistry::Get(browser_context_
);
345 const Extension
* extension
=
346 registry
->enabled_extensions().GetByID(params
.extension_id
);
349 registry
->enabled_extensions().GetHostedAppByURL(params
.source_url
);
352 int process_id
= render_view_host
? render_view_host
->GetProcess()->GetID() :
353 render_frame_host
->GetProcess()->GetID();
354 scoped_refptr
<ExtensionFunction
> function(
355 CreateExtensionFunction(params
,
359 ExtensionAPI::GetSharedInstance(),
365 UIThreadExtensionFunction
* function_ui
=
366 function
->AsUIThreadExtensionFunction();
371 if (render_view_host
) {
372 function_ui
->SetRenderViewHost(render_view_host
);
374 function_ui
->SetRenderFrameHost(render_frame_host
);
376 function_ui
->set_dispatcher(AsWeakPtr());
377 function_ui
->set_browser_context(browser_context_
);
379 ExtensionsBrowserClient::Get()->CanExtensionCrossIncognito(
380 extension
, browser_context_
)) {
381 function
->set_include_incognito(true);
384 if (!CheckPermissions(function
.get(), params
, callback
))
388 // Skip all of the UMA, quota, event page, activity logging stuff if there
389 // isn't an extension, e.g. if the function call was from WebUI.
390 function
->Run()->Execute();
394 // Fetch the ProcessManager before |this| is possibly invalidated.
395 ProcessManager
* process_manager
= ProcessManager::Get(browser_context_
);
397 ExtensionSystem
* extension_system
= ExtensionSystem::Get(browser_context_
);
398 QuotaService
* quota
= extension_system
->quota_service();
399 std::string violation_error
= quota
->Assess(extension
->id(),
402 base::TimeTicks::Now());
404 if (violation_error
.empty()) {
405 scoped_ptr
<base::ListValue
> args(params
.arguments
.DeepCopy());
407 // See crbug.com/39178.
408 ExtensionsBrowserClient::Get()->PermitExternalProtocolHandler();
409 NotifyApiFunctionCalled(
410 extension
->id(), params
.name
, args
.Pass(), browser_context_
);
411 UMA_HISTOGRAM_SPARSE_SLOWLY("Extensions.FunctionCalls",
412 function
->histogram_value());
413 tracked_objects::ScopedProfile
scoped_profile(
414 FROM_HERE_WITH_EXPLICIT_FUNCTION(function
->name()),
415 tracked_objects::ScopedProfile::ENABLED
);
416 function
->Run()->Execute();
418 function
->OnQuotaExceeded(violation_error
);
421 // Note: do not access |this| after this point. We may have been deleted
422 // if function->Run() ended up closing the tab that owns us.
424 // Check if extension was uninstalled by management.uninstall.
425 if (!registry
->enabled_extensions().GetByID(params
.extension_id
))
428 // We only adjust the keepalive count for UIThreadExtensionFunction for
429 // now, largely for simplicity's sake. This is OK because currently, only
430 // the webRequest API uses IOThreadExtensionFunction, and that API is not
431 // compatible with lazy background pages.
432 process_manager
->IncrementLazyKeepaliveCount(extension
);
435 void ExtensionFunctionDispatcher::OnExtensionFunctionCompleted(
436 const Extension
* extension
) {
438 ProcessManager::Get(browser_context_
)
439 ->DecrementLazyKeepaliveCount(extension
);
444 bool ExtensionFunctionDispatcher::CheckPermissions(
445 ExtensionFunction
* function
,
446 const ExtensionHostMsg_Request_Params
& params
,
447 const ExtensionFunction::ResponseCallback
& callback
) {
448 if (!function
->HasPermission()) {
449 LOG(ERROR
) << "Permission denied for " << params
.name
;
450 SendAccessDenied(callback
, function
->histogram_value());
457 ExtensionFunction
* ExtensionFunctionDispatcher::CreateExtensionFunction(
458 const ExtensionHostMsg_Request_Params
& params
,
459 const Extension
* extension
,
460 int requesting_process_id
,
461 const ProcessMap
& process_map
,
464 const ExtensionFunction::ResponseCallback
& callback
) {
465 ExtensionFunction
* function
=
466 ExtensionFunctionRegistry::GetInstance()->NewFunction(params
.name
);
468 LOG(ERROR
) << "Unknown Extension API - " << params
.name
;
469 SendAccessDenied(callback
, function
->histogram_value());
473 function
->SetArgs(¶ms
.arguments
);
474 function
->set_source_url(params
.source_url
);
475 function
->set_request_id(params
.request_id
);
476 function
->set_has_callback(params
.has_callback
);
477 function
->set_user_gesture(params
.user_gesture
);
478 function
->set_extension(extension
);
479 function
->set_profile_id(profile_id
);
480 function
->set_response_callback(callback
);
481 function
->set_source_tab_id(params
.source_tab_id
);
482 function
->set_source_context_type(
483 process_map
.GetMostLikelyContextType(extension
, requesting_process_id
));
489 void ExtensionFunctionDispatcher::SendAccessDenied(
490 const ExtensionFunction::ResponseCallback
& callback
,
491 functions::HistogramValue histogram_value
) {
492 base::ListValue empty_list
;
493 callback
.Run(ExtensionFunction::FAILED
, empty_list
,
494 "Access to extension API denied.", histogram_value
);
497 } // namespace extensions