Remove unused parameter.
[chromium-blink-merge.git] / extensions / browser / extension_function_dispatcher.cc
blob1fa43ec9c2fb955fbb53761ad423bfc2977e25f7
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/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 {
45 namespace {
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,
57 FROM_HERE,
58 base::Bind(&NotifyApiFunctionCalled,
59 extension_id,
60 api_name,
61 base::Passed(&args),
62 browser_context));
63 return;
65 // The BrowserContext may become invalid after the task above is posted.
66 if (!ExtensionsBrowserClient::Get()->IsValidContext(browser_context))
67 return;
69 ApiActivityMonitor* monitor =
70 ExtensionsBrowserClient::Get()->GetApiActivityMonitor(browser_context);
71 if (monitor)
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.
78 struct Static {
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) {
89 NOTREACHED();
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,
98 int routing_id,
99 const base::Process& peer_process,
100 int request_id,
101 ExtensionFunction::ResponseType type,
102 const base::ListValue& results,
103 const std::string& error,
104 functions::HistogramValue histogram_value) {
105 DCHECK(ipc_sender);
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.
112 LOG(ERROR) <<
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.
116 CHECK(false);
117 } else {
118 KillBadMessageSender(peer_process, histogram_value);
120 return;
123 ipc_sender->Send(new ExtensionMsg_Response(
124 routing_id, request_id, type == ExtensionFunction::SUCCEEDED, results,
125 error));
128 void IOThreadResponseCallback(
129 const base::WeakPtr<IOThreadExtensionMessageFilter>& ipc_sender,
130 int routing_id,
131 int request_id,
132 ExtensionFunction::ResponseType type,
133 const base::ListValue& results,
134 const std::string& error,
135 functions::HistogramValue histogram_value) {
136 if (!ipc_sender.get())
137 return;
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);
145 } // namespace
147 class ExtensionFunctionDispatcher::UIThreadResponseCallbackWrapper
148 : public content::WebContentsObserver {
149 public:
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_)
166 return;
168 if (dispatcher_.get()) {
169 dispatcher_->ui_thread_response_callback_wrappers_
170 .erase(render_view_host);
173 delete this;
176 ExtensionFunction::ResponseCallback CreateCallback(int request_id) {
177 return base::Bind(
178 &UIThreadResponseCallbackWrapper::OnExtensionFunctionCompleted,
179 weak_ptr_factory_.GetWeakPtr(),
180 request_id);
183 private:
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 = base::Process::DeprecatedGetProcessFromHandle(
190 render_view_host_->GetProcess()->GetHandle());
191 CommonResponseCallback(render_view_host_, render_view_host_->GetRoutingID(),
192 process, request_id, type, results, error,
193 histogram_value);
196 base::WeakPtr<ExtensionFunctionDispatcher> dispatcher_;
197 content::RenderViewHost* render_view_host_;
198 base::WeakPtrFactory<UIThreadResponseCallbackWrapper> weak_ptr_factory_;
200 DISALLOW_COPY_AND_ASSIGN(UIThreadResponseCallbackWrapper);
203 WindowController*
204 ExtensionFunctionDispatcher::Delegate::GetExtensionWindowController() const {
205 return NULL;
208 content::WebContents*
209 ExtensionFunctionDispatcher::Delegate::GetAssociatedWebContents() const {
210 return NULL;
213 content::WebContents*
214 ExtensionFunctionDispatcher::Delegate::GetVisibleWebContents() const {
215 return GetAssociatedWebContents();
218 void ExtensionFunctionDispatcher::GetAllFunctionNames(
219 std::vector<std::string>* names) {
220 ExtensionFunctionRegistry::GetInstance()->GetAllNames(names);
223 bool ExtensionFunctionDispatcher::OverrideFunction(
224 const std::string& name, ExtensionFunctionFactory factory) {
225 return ExtensionFunctionRegistry::GetInstance()->OverrideFunction(name,
226 factory);
229 // static
230 void ExtensionFunctionDispatcher::DispatchOnIOThread(
231 InfoMap* extension_info_map,
232 void* profile_id,
233 int render_process_id,
234 base::WeakPtr<IOThreadExtensionMessageFilter> ipc_sender,
235 int routing_id,
236 const ExtensionHostMsg_Request_Params& params) {
237 const Extension* extension =
238 extension_info_map->extensions().GetByID(params.extension_id);
240 ExtensionFunction::ResponseCallback callback(
241 base::Bind(&IOThreadResponseCallback, ipc_sender, routing_id,
242 params.request_id));
244 scoped_refptr<ExtensionFunction> function(
245 CreateExtensionFunction(params,
246 extension,
247 render_process_id,
248 extension_info_map->process_map(),
249 g_global_io_data.Get().api.get(),
250 profile_id,
251 callback));
252 if (!function.get())
253 return;
255 IOThreadExtensionFunction* function_io =
256 function->AsIOThreadExtensionFunction();
257 if (!function_io) {
258 NOTREACHED();
259 return;
261 function_io->set_ipc_sender(ipc_sender, routing_id);
262 function_io->set_extension_info_map(extension_info_map);
263 if (extension) {
264 function->set_include_incognito(
265 extension_info_map->IsIncognitoEnabled(extension->id()));
268 if (!CheckPermissions(function.get(), params, callback))
269 return;
271 if (!extension) {
272 // Skip all of the UMA, quota, event page, activity logging stuff if there
273 // isn't an extension, e.g. if the function call was from WebUI.
274 function->Run()->Execute();
275 return;
278 QuotaService* quota = extension_info_map->GetQuotaService();
279 std::string violation_error = quota->Assess(extension->id(),
280 function.get(),
281 &params.arguments,
282 base::TimeTicks::Now());
283 if (violation_error.empty()) {
284 scoped_ptr<base::ListValue> args(params.arguments.DeepCopy());
285 NotifyApiFunctionCalled(extension->id(),
286 params.name,
287 args.Pass(),
288 static_cast<content::BrowserContext*>(profile_id));
289 UMA_HISTOGRAM_SPARSE_SLOWLY("Extensions.FunctionCalls",
290 function->histogram_value());
291 tracked_objects::ScopedProfile scoped_profile(
292 FROM_HERE_WITH_EXPLICIT_FUNCTION(function->name()),
293 tracked_objects::ScopedProfile::ENABLED);
294 function->Run()->Execute();
295 } else {
296 function->OnQuotaExceeded(violation_error);
300 ExtensionFunctionDispatcher::ExtensionFunctionDispatcher(
301 content::BrowserContext* browser_context,
302 Delegate* delegate)
303 : browser_context_(browser_context),
304 delegate_(delegate) {
307 ExtensionFunctionDispatcher::~ExtensionFunctionDispatcher() {
310 void ExtensionFunctionDispatcher::Dispatch(
311 const ExtensionHostMsg_Request_Params& params,
312 RenderViewHost* render_view_host) {
313 UIThreadResponseCallbackWrapperMap::const_iterator
314 iter = ui_thread_response_callback_wrappers_.find(render_view_host);
315 UIThreadResponseCallbackWrapper* callback_wrapper = NULL;
316 if (iter == ui_thread_response_callback_wrappers_.end()) {
317 callback_wrapper = new UIThreadResponseCallbackWrapper(AsWeakPtr(),
318 render_view_host);
319 ui_thread_response_callback_wrappers_[render_view_host] = callback_wrapper;
320 } else {
321 callback_wrapper = iter->second;
324 DispatchWithCallbackInternal(
325 params, render_view_host, NULL,
326 callback_wrapper->CreateCallback(params.request_id));
329 void ExtensionFunctionDispatcher::DispatchWithCallbackInternal(
330 const ExtensionHostMsg_Request_Params& params,
331 RenderViewHost* render_view_host,
332 content::RenderFrameHost* render_frame_host,
333 const ExtensionFunction::ResponseCallback& callback) {
334 DCHECK(render_view_host || render_frame_host);
335 // TODO(yzshen): There is some shared logic between this method and
336 // DispatchOnIOThread(). It is nice to deduplicate.
337 ProcessMap* process_map = ProcessMap::Get(browser_context_);
338 if (!process_map)
339 return;
341 ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context_);
342 const Extension* extension =
343 registry->enabled_extensions().GetByID(params.extension_id);
344 if (!extension) {
345 extension =
346 registry->enabled_extensions().GetHostedAppByURL(params.source_url);
349 int process_id = render_view_host ? render_view_host->GetProcess()->GetID() :
350 render_frame_host->GetProcess()->GetID();
351 scoped_refptr<ExtensionFunction> function(
352 CreateExtensionFunction(params,
353 extension,
354 process_id,
355 *process_map,
356 ExtensionAPI::GetSharedInstance(),
357 browser_context_,
358 callback));
359 if (!function.get())
360 return;
362 UIThreadExtensionFunction* function_ui =
363 function->AsUIThreadExtensionFunction();
364 if (!function_ui) {
365 NOTREACHED();
366 return;
368 if (render_view_host) {
369 function_ui->SetRenderViewHost(render_view_host);
370 } else {
371 function_ui->SetRenderFrameHost(render_frame_host);
373 function_ui->set_dispatcher(AsWeakPtr());
374 function_ui->set_browser_context(browser_context_);
375 if (extension &&
376 ExtensionsBrowserClient::Get()->CanExtensionCrossIncognito(
377 extension, browser_context_)) {
378 function->set_include_incognito(true);
381 if (!CheckPermissions(function.get(), params, callback))
382 return;
384 if (!extension) {
385 // Skip all of the UMA, quota, event page, activity logging stuff if there
386 // isn't an extension, e.g. if the function call was from WebUI.
387 function->Run()->Execute();
388 return;
391 // Fetch the ProcessManager before |this| is possibly invalidated.
392 ProcessManager* process_manager = ProcessManager::Get(browser_context_);
394 ExtensionSystem* extension_system = ExtensionSystem::Get(browser_context_);
395 QuotaService* quota = extension_system->quota_service();
396 std::string violation_error = quota->Assess(extension->id(),
397 function.get(),
398 &params.arguments,
399 base::TimeTicks::Now());
401 if (violation_error.empty()) {
402 scoped_ptr<base::ListValue> args(params.arguments.DeepCopy());
404 // See crbug.com/39178.
405 ExtensionsBrowserClient::Get()->PermitExternalProtocolHandler();
406 NotifyApiFunctionCalled(
407 extension->id(), params.name, args.Pass(), browser_context_);
408 UMA_HISTOGRAM_SPARSE_SLOWLY("Extensions.FunctionCalls",
409 function->histogram_value());
410 tracked_objects::ScopedProfile scoped_profile(
411 FROM_HERE_WITH_EXPLICIT_FUNCTION(function->name()),
412 tracked_objects::ScopedProfile::ENABLED);
413 function->Run()->Execute();
414 } else {
415 function->OnQuotaExceeded(violation_error);
418 // Note: do not access |this| after this point. We may have been deleted
419 // if function->Run() ended up closing the tab that owns us.
421 // Check if extension was uninstalled by management.uninstall.
422 if (!registry->enabled_extensions().GetByID(params.extension_id))
423 return;
425 // We only adjust the keepalive count for UIThreadExtensionFunction for
426 // now, largely for simplicity's sake. This is OK because currently, only
427 // the webRequest API uses IOThreadExtensionFunction, and that API is not
428 // compatible with lazy background pages.
429 process_manager->IncrementLazyKeepaliveCount(extension);
432 void ExtensionFunctionDispatcher::OnExtensionFunctionCompleted(
433 const Extension* extension) {
434 if (extension) {
435 ProcessManager::Get(browser_context_)
436 ->DecrementLazyKeepaliveCount(extension);
440 // static
441 bool ExtensionFunctionDispatcher::CheckPermissions(
442 ExtensionFunction* function,
443 const ExtensionHostMsg_Request_Params& params,
444 const ExtensionFunction::ResponseCallback& callback) {
445 if (!function->HasPermission()) {
446 LOG(ERROR) << "Permission denied for " << params.name;
447 SendAccessDenied(callback, function->histogram_value());
448 return false;
450 return true;
453 // static
454 ExtensionFunction* ExtensionFunctionDispatcher::CreateExtensionFunction(
455 const ExtensionHostMsg_Request_Params& params,
456 const Extension* extension,
457 int requesting_process_id,
458 const ProcessMap& process_map,
459 ExtensionAPI* api,
460 void* profile_id,
461 const ExtensionFunction::ResponseCallback& callback) {
462 ExtensionFunction* function =
463 ExtensionFunctionRegistry::GetInstance()->NewFunction(params.name);
464 if (!function) {
465 LOG(ERROR) << "Unknown Extension API - " << params.name;
466 SendAccessDenied(callback, function->histogram_value());
467 return NULL;
470 function->SetArgs(&params.arguments);
471 function->set_source_url(params.source_url);
472 function->set_request_id(params.request_id);
473 function->set_has_callback(params.has_callback);
474 function->set_user_gesture(params.user_gesture);
475 function->set_extension(extension);
476 function->set_profile_id(profile_id);
477 function->set_response_callback(callback);
478 function->set_source_tab_id(params.source_tab_id);
479 function->set_source_context_type(
480 process_map.GetMostLikelyContextType(extension, requesting_process_id));
482 return function;
485 // static
486 void ExtensionFunctionDispatcher::SendAccessDenied(
487 const ExtensionFunction::ResponseCallback& callback,
488 functions::HistogramValue histogram_value) {
489 base::ListValue empty_list;
490 callback.Run(ExtensionFunction::FAILED, empty_list,
491 "Access to extension API denied.", histogram_value);
494 } // namespace extensions