cc: Remove a TODO in LayerTreeImpl, and reorganize methods.
[chromium-blink-merge.git] / extensions / browser / extension_function_dispatcher.cc
blob68ec6f904f5b4da217b30d019f39327b674c698c
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"
7 #include "base/bind.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/sparse_histogram.h"
13 #include "base/process/process.h"
14 #include "base/values.h"
15 #include "build/build_config.h"
16 #include "content/public/browser/browser_thread.h"
17 #include "content/public/browser/render_frame_host.h"
18 #include "content/public/browser/render_process_host.h"
19 #include "content/public/browser/render_view_host.h"
20 #include "content/public/browser/user_metrics.h"
21 #include "content/public/browser/web_contents.h"
22 #include "content/public/browser/web_contents_observer.h"
23 #include "content/public/common/result_codes.h"
24 #include "extensions/browser/api_activity_monitor.h"
25 #include "extensions/browser/extension_function_registry.h"
26 #include "extensions/browser/extension_registry.h"
27 #include "extensions/browser/extension_system.h"
28 #include "extensions/browser/extensions_browser_client.h"
29 #include "extensions/browser/io_thread_extension_message_filter.h"
30 #include "extensions/browser/process_manager.h"
31 #include "extensions/browser/process_map.h"
32 #include "extensions/browser/quota_service.h"
33 #include "extensions/common/extension_api.h"
34 #include "extensions/common/extension_messages.h"
35 #include "extensions/common/extension_set.h"
36 #include "ipc/ipc_message.h"
37 #include "ipc/ipc_message_macros.h"
39 using content::BrowserThread;
40 using content::RenderViewHost;
42 namespace extensions {
43 namespace {
45 // Notifies the ApiActivityMonitor that an extension API function has been
46 // called. May be called from any thread.
47 void NotifyApiFunctionCalled(const std::string& extension_id,
48 const std::string& api_name,
49 scoped_ptr<base::ListValue> args,
50 content::BrowserContext* browser_context) {
51 // The ApiActivityMonitor can only be accessed from the main (UI) thread. If
52 // we're running on the wrong thread, re-dispatch from the main thread.
53 if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
54 BrowserThread::PostTask(BrowserThread::UI,
55 FROM_HERE,
56 base::Bind(&NotifyApiFunctionCalled,
57 extension_id,
58 api_name,
59 base::Passed(&args),
60 browser_context));
61 return;
63 // The BrowserContext may become invalid after the task above is posted.
64 if (!ExtensionsBrowserClient::Get()->IsValidContext(browser_context))
65 return;
67 ApiActivityMonitor* monitor =
68 ExtensionsBrowserClient::Get()->GetApiActivityMonitor(browser_context);
69 if (monitor)
70 monitor->OnApiFunctionCalled(extension_id, api_name, args.Pass());
73 // Separate copy of ExtensionAPI used for IO thread extension functions. We need
74 // this because ExtensionAPI has mutable data. It should be possible to remove
75 // this once all the extension APIs are updated to the feature system.
76 struct Static {
77 Static() : api(ExtensionAPI::CreateWithDefaultConfiguration()) {}
78 scoped_ptr<ExtensionAPI> api;
80 base::LazyInstance<Static> g_global_io_data = LAZY_INSTANCE_INITIALIZER;
82 // Kills the specified process because it sends us a malformed message.
83 void KillBadMessageSender(base::ProcessHandle process) {
84 NOTREACHED();
85 content::RecordAction(base::UserMetricsAction("BadMessageTerminate_EFD"));
86 if (process)
87 base::KillProcess(process, content::RESULT_CODE_KILLED_BAD_MESSAGE, false);
90 void CommonResponseCallback(IPC::Sender* ipc_sender,
91 int routing_id,
92 base::ProcessHandle peer_process,
93 int request_id,
94 ExtensionFunction::ResponseType type,
95 const base::ListValue& results,
96 const std::string& error) {
97 DCHECK(ipc_sender);
99 if (type == ExtensionFunction::BAD_MESSAGE) {
100 // The renderer has done validation before sending extension api requests.
101 // Therefore, we should never receive a request that is invalid in a way
102 // that JSON validation in the renderer should have caught. It could be an
103 // attacker trying to exploit the browser, so we crash the renderer instead.
104 LOG(ERROR) <<
105 "Terminating renderer because of malformed extension message.";
106 if (content::RenderProcessHost::run_renderer_in_process()) {
107 // In single process mode it is better if we don't suicide but just crash.
108 CHECK(false);
109 } else {
110 KillBadMessageSender(peer_process);
113 return;
116 ipc_sender->Send(new ExtensionMsg_Response(
117 routing_id, request_id, type == ExtensionFunction::SUCCEEDED, results,
118 error));
121 void IOThreadResponseCallback(
122 const base::WeakPtr<IOThreadExtensionMessageFilter>& ipc_sender,
123 int routing_id,
124 int request_id,
125 ExtensionFunction::ResponseType type,
126 const base::ListValue& results,
127 const std::string& error) {
128 if (!ipc_sender.get())
129 return;
131 CommonResponseCallback(ipc_sender.get(),
132 routing_id,
133 ipc_sender->PeerHandle(),
134 request_id,
135 type,
136 results,
137 error);
140 } // namespace
142 class ExtensionFunctionDispatcher::UIThreadResponseCallbackWrapper
143 : public content::WebContentsObserver {
144 public:
145 UIThreadResponseCallbackWrapper(
146 const base::WeakPtr<ExtensionFunctionDispatcher>& dispatcher,
147 RenderViewHost* render_view_host)
148 : content::WebContentsObserver(
149 content::WebContents::FromRenderViewHost(render_view_host)),
150 dispatcher_(dispatcher),
151 render_view_host_(render_view_host),
152 weak_ptr_factory_(this) {
155 ~UIThreadResponseCallbackWrapper() override {}
157 // content::WebContentsObserver overrides.
158 void RenderViewDeleted(RenderViewHost* render_view_host) override {
159 DCHECK_CURRENTLY_ON(BrowserThread::UI);
160 if (render_view_host != render_view_host_)
161 return;
163 if (dispatcher_.get()) {
164 dispatcher_->ui_thread_response_callback_wrappers_
165 .erase(render_view_host);
168 delete this;
171 ExtensionFunction::ResponseCallback CreateCallback(int request_id) {
172 return base::Bind(
173 &UIThreadResponseCallbackWrapper::OnExtensionFunctionCompleted,
174 weak_ptr_factory_.GetWeakPtr(),
175 request_id);
178 private:
179 void OnExtensionFunctionCompleted(int request_id,
180 ExtensionFunction::ResponseType type,
181 const base::ListValue& results,
182 const std::string& error) {
183 CommonResponseCallback(
184 render_view_host_, render_view_host_->GetRoutingID(),
185 render_view_host_->GetProcess()->GetHandle(), request_id, type,
186 results, error);
189 base::WeakPtr<ExtensionFunctionDispatcher> dispatcher_;
190 content::RenderViewHost* render_view_host_;
191 base::WeakPtrFactory<UIThreadResponseCallbackWrapper> weak_ptr_factory_;
193 DISALLOW_COPY_AND_ASSIGN(UIThreadResponseCallbackWrapper);
196 WindowController*
197 ExtensionFunctionDispatcher::Delegate::GetExtensionWindowController() const {
198 return NULL;
201 content::WebContents*
202 ExtensionFunctionDispatcher::Delegate::GetAssociatedWebContents() const {
203 return NULL;
206 content::WebContents*
207 ExtensionFunctionDispatcher::Delegate::GetVisibleWebContents() const {
208 return GetAssociatedWebContents();
211 void ExtensionFunctionDispatcher::GetAllFunctionNames(
212 std::vector<std::string>* names) {
213 ExtensionFunctionRegistry::GetInstance()->GetAllNames(names);
216 bool ExtensionFunctionDispatcher::OverrideFunction(
217 const std::string& name, ExtensionFunctionFactory factory) {
218 return ExtensionFunctionRegistry::GetInstance()->OverrideFunction(name,
219 factory);
222 // static
223 void ExtensionFunctionDispatcher::DispatchOnIOThread(
224 InfoMap* extension_info_map,
225 void* profile_id,
226 int render_process_id,
227 base::WeakPtr<IOThreadExtensionMessageFilter> ipc_sender,
228 int routing_id,
229 const ExtensionHostMsg_Request_Params& params) {
230 const Extension* extension =
231 extension_info_map->extensions().GetByID(params.extension_id);
233 ExtensionFunction::ResponseCallback callback(
234 base::Bind(&IOThreadResponseCallback, ipc_sender, routing_id,
235 params.request_id));
237 scoped_refptr<ExtensionFunction> function(
238 CreateExtensionFunction(params,
239 extension,
240 render_process_id,
241 extension_info_map->process_map(),
242 g_global_io_data.Get().api.get(),
243 profile_id,
244 callback));
245 if (!function.get())
246 return;
248 IOThreadExtensionFunction* function_io =
249 function->AsIOThreadExtensionFunction();
250 if (!function_io) {
251 NOTREACHED();
252 return;
254 function_io->set_ipc_sender(ipc_sender, routing_id);
255 function_io->set_extension_info_map(extension_info_map);
256 if (extension) {
257 function->set_include_incognito(
258 extension_info_map->IsIncognitoEnabled(extension->id()));
261 if (!CheckPermissions(function.get(), params, callback))
262 return;
264 if (!extension) {
265 // Skip all of the UMA, quota, event page, activity logging stuff if there
266 // isn't an extension, e.g. if the function call was from WebUI.
267 function->Run()->Execute();
268 return;
271 QuotaService* quota = extension_info_map->GetQuotaService();
272 std::string violation_error = quota->Assess(extension->id(),
273 function.get(),
274 &params.arguments,
275 base::TimeTicks::Now());
276 if (violation_error.empty()) {
277 scoped_ptr<base::ListValue> args(params.arguments.DeepCopy());
278 NotifyApiFunctionCalled(extension->id(),
279 params.name,
280 args.Pass(),
281 static_cast<content::BrowserContext*>(profile_id));
282 UMA_HISTOGRAM_SPARSE_SLOWLY("Extensions.FunctionCalls",
283 function->histogram_value());
284 function->Run()->Execute();
285 } else {
286 function->OnQuotaExceeded(violation_error);
290 ExtensionFunctionDispatcher::ExtensionFunctionDispatcher(
291 content::BrowserContext* browser_context,
292 Delegate* delegate)
293 : browser_context_(browser_context),
294 delegate_(delegate) {
297 ExtensionFunctionDispatcher::~ExtensionFunctionDispatcher() {
300 void ExtensionFunctionDispatcher::Dispatch(
301 const ExtensionHostMsg_Request_Params& params,
302 RenderViewHost* render_view_host) {
303 UIThreadResponseCallbackWrapperMap::const_iterator
304 iter = ui_thread_response_callback_wrappers_.find(render_view_host);
305 UIThreadResponseCallbackWrapper* callback_wrapper = NULL;
306 if (iter == ui_thread_response_callback_wrappers_.end()) {
307 callback_wrapper = new UIThreadResponseCallbackWrapper(AsWeakPtr(),
308 render_view_host);
309 ui_thread_response_callback_wrappers_[render_view_host] = callback_wrapper;
310 } else {
311 callback_wrapper = iter->second;
314 DispatchWithCallbackInternal(
315 params, render_view_host, NULL,
316 callback_wrapper->CreateCallback(params.request_id));
319 void ExtensionFunctionDispatcher::DispatchWithCallbackInternal(
320 const ExtensionHostMsg_Request_Params& params,
321 RenderViewHost* render_view_host,
322 content::RenderFrameHost* render_frame_host,
323 const ExtensionFunction::ResponseCallback& callback) {
324 DCHECK(render_view_host || render_frame_host);
325 // TODO(yzshen): There is some shared logic between this method and
326 // DispatchOnIOThread(). It is nice to deduplicate.
327 ProcessMap* process_map = ProcessMap::Get(browser_context_);
328 if (!process_map)
329 return;
331 ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context_);
332 const Extension* extension =
333 registry->enabled_extensions().GetByID(params.extension_id);
334 if (!extension) {
335 extension =
336 registry->enabled_extensions().GetHostedAppByURL(params.source_url);
339 int process_id = render_view_host ? render_view_host->GetProcess()->GetID() :
340 render_frame_host->GetProcess()->GetID();
341 scoped_refptr<ExtensionFunction> function(
342 CreateExtensionFunction(params,
343 extension,
344 process_id,
345 *process_map,
346 ExtensionAPI::GetSharedInstance(),
347 browser_context_,
348 callback));
349 if (!function.get())
350 return;
352 UIThreadExtensionFunction* function_ui =
353 function->AsUIThreadExtensionFunction();
354 if (!function_ui) {
355 NOTREACHED();
356 return;
358 if (render_view_host) {
359 function_ui->SetRenderViewHost(render_view_host);
360 } else {
361 function_ui->SetRenderFrameHost(render_frame_host);
363 function_ui->set_dispatcher(AsWeakPtr());
364 function_ui->set_browser_context(browser_context_);
365 if (extension &&
366 ExtensionsBrowserClient::Get()->CanExtensionCrossIncognito(
367 extension, browser_context_)) {
368 function->set_include_incognito(true);
371 if (!CheckPermissions(function.get(), params, callback))
372 return;
374 if (!extension) {
375 // Skip all of the UMA, quota, event page, activity logging stuff if there
376 // isn't an extension, e.g. if the function call was from WebUI.
377 function->Run()->Execute();
378 return;
381 // Fetch the ProcessManager before |this| is possibly invalidated.
382 ProcessManager* process_manager = ProcessManager::Get(browser_context_);
384 ExtensionSystem* extension_system = ExtensionSystem::Get(browser_context_);
385 QuotaService* quota = extension_system->quota_service();
386 std::string violation_error = quota->Assess(extension->id(),
387 function.get(),
388 &params.arguments,
389 base::TimeTicks::Now());
391 if (violation_error.empty()) {
392 scoped_ptr<base::ListValue> args(params.arguments.DeepCopy());
394 // See crbug.com/39178.
395 ExtensionsBrowserClient::Get()->PermitExternalProtocolHandler();
396 NotifyApiFunctionCalled(
397 extension->id(), params.name, args.Pass(), browser_context_);
398 UMA_HISTOGRAM_SPARSE_SLOWLY("Extensions.FunctionCalls",
399 function->histogram_value());
400 function->Run()->Execute();
401 } else {
402 function->OnQuotaExceeded(violation_error);
405 // Note: do not access |this| after this point. We may have been deleted
406 // if function->Run() ended up closing the tab that owns us.
408 // Check if extension was uninstalled by management.uninstall.
409 if (!registry->enabled_extensions().GetByID(params.extension_id))
410 return;
412 // We only adjust the keepalive count for UIThreadExtensionFunction for
413 // now, largely for simplicity's sake. This is OK because currently, only
414 // the webRequest API uses IOThreadExtensionFunction, and that API is not
415 // compatible with lazy background pages.
416 process_manager->IncrementLazyKeepaliveCount(extension);
419 void ExtensionFunctionDispatcher::OnExtensionFunctionCompleted(
420 const Extension* extension) {
421 if (extension) {
422 ProcessManager::Get(browser_context_)
423 ->DecrementLazyKeepaliveCount(extension);
427 // static
428 bool ExtensionFunctionDispatcher::CheckPermissions(
429 ExtensionFunction* function,
430 const ExtensionHostMsg_Request_Params& params,
431 const ExtensionFunction::ResponseCallback& callback) {
432 if (!function->HasPermission()) {
433 LOG(ERROR) << "Permission denied for " << params.name;
434 SendAccessDenied(callback);
435 return false;
437 return true;
440 // static
441 ExtensionFunction* ExtensionFunctionDispatcher::CreateExtensionFunction(
442 const ExtensionHostMsg_Request_Params& params,
443 const Extension* extension,
444 int requesting_process_id,
445 const ProcessMap& process_map,
446 ExtensionAPI* api,
447 void* profile_id,
448 const ExtensionFunction::ResponseCallback& callback) {
449 ExtensionFunction* function =
450 ExtensionFunctionRegistry::GetInstance()->NewFunction(params.name);
451 if (!function) {
452 LOG(ERROR) << "Unknown Extension API - " << params.name;
453 SendAccessDenied(callback);
454 return NULL;
457 function->SetArgs(&params.arguments);
458 function->set_source_url(params.source_url);
459 function->set_request_id(params.request_id);
460 function->set_has_callback(params.has_callback);
461 function->set_user_gesture(params.user_gesture);
462 function->set_extension(extension);
463 function->set_profile_id(profile_id);
464 function->set_response_callback(callback);
465 function->set_source_tab_id(params.source_tab_id);
466 function->set_source_context_type(
467 process_map.GetMostLikelyContextType(extension, requesting_process_id));
469 return function;
472 // static
473 void ExtensionFunctionDispatcher::SendAccessDenied(
474 const ExtensionFunction::ResponseCallback& callback) {
475 base::ListValue empty_list;
476 callback.Run(ExtensionFunction::FAILED, empty_list,
477 "Access to extension API denied.");
480 } // namespace extensions