Revert of Output closure-compiled JavaScript files (patchset #10 id:180001 of https...
[chromium-blink-merge.git] / extensions / browser / extension_function_dispatcher.cc
blobfcf4ab4c8ed5bc5e4e0dd87dc0ae101944889f26
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(base::ProcessHandle 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)
94 base::KillProcess(process, content::RESULT_CODE_KILLED_BAD_MESSAGE, false);
97 void CommonResponseCallback(IPC::Sender* ipc_sender,
98 int routing_id,
99 base::ProcessHandle 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 CommonResponseCallback(ipc_sender.get(), routing_id, ipc_sender->PeerHandle(),
140 request_id, type, results, error, histogram_value);
143 } // namespace
145 class ExtensionFunctionDispatcher::UIThreadResponseCallbackWrapper
146 : public content::WebContentsObserver {
147 public:
148 UIThreadResponseCallbackWrapper(
149 const base::WeakPtr<ExtensionFunctionDispatcher>& dispatcher,
150 RenderViewHost* render_view_host)
151 : content::WebContentsObserver(
152 content::WebContents::FromRenderViewHost(render_view_host)),
153 dispatcher_(dispatcher),
154 render_view_host_(render_view_host),
155 weak_ptr_factory_(this) {
158 ~UIThreadResponseCallbackWrapper() override {}
160 // content::WebContentsObserver overrides.
161 void RenderViewDeleted(RenderViewHost* render_view_host) override {
162 DCHECK_CURRENTLY_ON(BrowserThread::UI);
163 if (render_view_host != render_view_host_)
164 return;
166 if (dispatcher_.get()) {
167 dispatcher_->ui_thread_response_callback_wrappers_
168 .erase(render_view_host);
171 delete this;
174 ExtensionFunction::ResponseCallback CreateCallback(int request_id) {
175 return base::Bind(
176 &UIThreadResponseCallbackWrapper::OnExtensionFunctionCompleted,
177 weak_ptr_factory_.GetWeakPtr(),
178 request_id);
181 private:
182 void OnExtensionFunctionCompleted(int request_id,
183 ExtensionFunction::ResponseType type,
184 const base::ListValue& results,
185 const std::string& error,
186 functions::HistogramValue histogram_value) {
187 CommonResponseCallback(render_view_host_, render_view_host_->GetRoutingID(),
188 render_view_host_->GetProcess()->GetHandle(),
189 request_id, type, results, error, histogram_value);
192 base::WeakPtr<ExtensionFunctionDispatcher> dispatcher_;
193 content::RenderViewHost* render_view_host_;
194 base::WeakPtrFactory<UIThreadResponseCallbackWrapper> weak_ptr_factory_;
196 DISALLOW_COPY_AND_ASSIGN(UIThreadResponseCallbackWrapper);
199 WindowController*
200 ExtensionFunctionDispatcher::Delegate::GetExtensionWindowController() const {
201 return NULL;
204 content::WebContents*
205 ExtensionFunctionDispatcher::Delegate::GetAssociatedWebContents() const {
206 return NULL;
209 content::WebContents*
210 ExtensionFunctionDispatcher::Delegate::GetVisibleWebContents() const {
211 return GetAssociatedWebContents();
214 void ExtensionFunctionDispatcher::GetAllFunctionNames(
215 std::vector<std::string>* names) {
216 ExtensionFunctionRegistry::GetInstance()->GetAllNames(names);
219 bool ExtensionFunctionDispatcher::OverrideFunction(
220 const std::string& name, ExtensionFunctionFactory factory) {
221 return ExtensionFunctionRegistry::GetInstance()->OverrideFunction(name,
222 factory);
225 // static
226 void ExtensionFunctionDispatcher::DispatchOnIOThread(
227 InfoMap* extension_info_map,
228 void* profile_id,
229 int render_process_id,
230 base::WeakPtr<IOThreadExtensionMessageFilter> ipc_sender,
231 int routing_id,
232 const ExtensionHostMsg_Request_Params& params) {
233 const Extension* extension =
234 extension_info_map->extensions().GetByID(params.extension_id);
236 ExtensionFunction::ResponseCallback callback(
237 base::Bind(&IOThreadResponseCallback, ipc_sender, routing_id,
238 params.request_id));
240 scoped_refptr<ExtensionFunction> function(
241 CreateExtensionFunction(params,
242 extension,
243 render_process_id,
244 extension_info_map->process_map(),
245 g_global_io_data.Get().api.get(),
246 profile_id,
247 callback));
248 if (!function.get())
249 return;
251 IOThreadExtensionFunction* function_io =
252 function->AsIOThreadExtensionFunction();
253 if (!function_io) {
254 NOTREACHED();
255 return;
257 function_io->set_ipc_sender(ipc_sender, routing_id);
258 function_io->set_extension_info_map(extension_info_map);
259 if (extension) {
260 function->set_include_incognito(
261 extension_info_map->IsIncognitoEnabled(extension->id()));
264 if (!CheckPermissions(function.get(), params, callback))
265 return;
267 if (!extension) {
268 // Skip all of the UMA, quota, event page, activity logging stuff if there
269 // isn't an extension, e.g. if the function call was from WebUI.
270 function->Run()->Execute();
271 return;
274 QuotaService* quota = extension_info_map->GetQuotaService();
275 std::string violation_error = quota->Assess(extension->id(),
276 function.get(),
277 &params.arguments,
278 base::TimeTicks::Now());
279 if (violation_error.empty()) {
280 scoped_ptr<base::ListValue> args(params.arguments.DeepCopy());
281 NotifyApiFunctionCalled(extension->id(),
282 params.name,
283 args.Pass(),
284 static_cast<content::BrowserContext*>(profile_id));
285 UMA_HISTOGRAM_SPARSE_SLOWLY("Extensions.FunctionCalls",
286 function->histogram_value());
287 tracked_objects::ScopedProfile scoped_profile(
288 FROM_HERE_WITH_EXPLICIT_FUNCTION(function->name()),
289 tracked_objects::ScopedProfile::ENABLED);
290 function->Run()->Execute();
291 } else {
292 function->OnQuotaExceeded(violation_error);
296 ExtensionFunctionDispatcher::ExtensionFunctionDispatcher(
297 content::BrowserContext* browser_context,
298 Delegate* delegate)
299 : browser_context_(browser_context),
300 delegate_(delegate) {
303 ExtensionFunctionDispatcher::~ExtensionFunctionDispatcher() {
306 void ExtensionFunctionDispatcher::Dispatch(
307 const ExtensionHostMsg_Request_Params& params,
308 RenderViewHost* render_view_host) {
309 UIThreadResponseCallbackWrapperMap::const_iterator
310 iter = ui_thread_response_callback_wrappers_.find(render_view_host);
311 UIThreadResponseCallbackWrapper* callback_wrapper = NULL;
312 if (iter == ui_thread_response_callback_wrappers_.end()) {
313 callback_wrapper = new UIThreadResponseCallbackWrapper(AsWeakPtr(),
314 render_view_host);
315 ui_thread_response_callback_wrappers_[render_view_host] = callback_wrapper;
316 } else {
317 callback_wrapper = iter->second;
320 DispatchWithCallbackInternal(
321 params, render_view_host, NULL,
322 callback_wrapper->CreateCallback(params.request_id));
325 void ExtensionFunctionDispatcher::DispatchWithCallbackInternal(
326 const ExtensionHostMsg_Request_Params& params,
327 RenderViewHost* render_view_host,
328 content::RenderFrameHost* render_frame_host,
329 const ExtensionFunction::ResponseCallback& callback) {
330 DCHECK(render_view_host || render_frame_host);
331 // TODO(yzshen): There is some shared logic between this method and
332 // DispatchOnIOThread(). It is nice to deduplicate.
333 ProcessMap* process_map = ProcessMap::Get(browser_context_);
334 if (!process_map)
335 return;
337 ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context_);
338 const Extension* extension =
339 registry->enabled_extensions().GetByID(params.extension_id);
340 if (!extension) {
341 extension =
342 registry->enabled_extensions().GetHostedAppByURL(params.source_url);
345 int process_id = render_view_host ? render_view_host->GetProcess()->GetID() :
346 render_frame_host->GetProcess()->GetID();
347 scoped_refptr<ExtensionFunction> function(
348 CreateExtensionFunction(params,
349 extension,
350 process_id,
351 *process_map,
352 ExtensionAPI::GetSharedInstance(),
353 browser_context_,
354 callback));
355 if (!function.get())
356 return;
358 UIThreadExtensionFunction* function_ui =
359 function->AsUIThreadExtensionFunction();
360 if (!function_ui) {
361 NOTREACHED();
362 return;
364 if (render_view_host) {
365 function_ui->SetRenderViewHost(render_view_host);
366 } else {
367 function_ui->SetRenderFrameHost(render_frame_host);
369 function_ui->set_dispatcher(AsWeakPtr());
370 function_ui->set_browser_context(browser_context_);
371 if (extension &&
372 ExtensionsBrowserClient::Get()->CanExtensionCrossIncognito(
373 extension, browser_context_)) {
374 function->set_include_incognito(true);
377 if (!CheckPermissions(function.get(), params, callback))
378 return;
380 if (!extension) {
381 // Skip all of the UMA, quota, event page, activity logging stuff if there
382 // isn't an extension, e.g. if the function call was from WebUI.
383 function->Run()->Execute();
384 return;
387 // Fetch the ProcessManager before |this| is possibly invalidated.
388 ProcessManager* process_manager = ProcessManager::Get(browser_context_);
390 ExtensionSystem* extension_system = ExtensionSystem::Get(browser_context_);
391 QuotaService* quota = extension_system->quota_service();
392 std::string violation_error = quota->Assess(extension->id(),
393 function.get(),
394 &params.arguments,
395 base::TimeTicks::Now());
397 if (violation_error.empty()) {
398 scoped_ptr<base::ListValue> args(params.arguments.DeepCopy());
400 // See crbug.com/39178.
401 ExtensionsBrowserClient::Get()->PermitExternalProtocolHandler();
402 NotifyApiFunctionCalled(
403 extension->id(), params.name, args.Pass(), browser_context_);
404 UMA_HISTOGRAM_SPARSE_SLOWLY("Extensions.FunctionCalls",
405 function->histogram_value());
406 tracked_objects::ScopedProfile scoped_profile(
407 FROM_HERE_WITH_EXPLICIT_FUNCTION(function->name()),
408 tracked_objects::ScopedProfile::ENABLED);
409 function->Run()->Execute();
410 } else {
411 function->OnQuotaExceeded(violation_error);
414 // Note: do not access |this| after this point. We may have been deleted
415 // if function->Run() ended up closing the tab that owns us.
417 // Check if extension was uninstalled by management.uninstall.
418 if (!registry->enabled_extensions().GetByID(params.extension_id))
419 return;
421 // We only adjust the keepalive count for UIThreadExtensionFunction for
422 // now, largely for simplicity's sake. This is OK because currently, only
423 // the webRequest API uses IOThreadExtensionFunction, and that API is not
424 // compatible with lazy background pages.
425 process_manager->IncrementLazyKeepaliveCount(extension);
428 void ExtensionFunctionDispatcher::OnExtensionFunctionCompleted(
429 const Extension* extension) {
430 if (extension) {
431 ProcessManager::Get(browser_context_)
432 ->DecrementLazyKeepaliveCount(extension);
436 // static
437 bool ExtensionFunctionDispatcher::CheckPermissions(
438 ExtensionFunction* function,
439 const ExtensionHostMsg_Request_Params& params,
440 const ExtensionFunction::ResponseCallback& callback) {
441 if (!function->HasPermission()) {
442 LOG(ERROR) << "Permission denied for " << params.name;
443 SendAccessDenied(callback, function->histogram_value());
444 return false;
446 return true;
449 // static
450 ExtensionFunction* ExtensionFunctionDispatcher::CreateExtensionFunction(
451 const ExtensionHostMsg_Request_Params& params,
452 const Extension* extension,
453 int requesting_process_id,
454 const ProcessMap& process_map,
455 ExtensionAPI* api,
456 void* profile_id,
457 const ExtensionFunction::ResponseCallback& callback) {
458 ExtensionFunction* function =
459 ExtensionFunctionRegistry::GetInstance()->NewFunction(params.name);
460 if (!function) {
461 LOG(ERROR) << "Unknown Extension API - " << params.name;
462 SendAccessDenied(callback, function->histogram_value());
463 return NULL;
466 function->SetArgs(&params.arguments);
467 function->set_source_url(params.source_url);
468 function->set_request_id(params.request_id);
469 function->set_has_callback(params.has_callback);
470 function->set_user_gesture(params.user_gesture);
471 function->set_extension(extension);
472 function->set_profile_id(profile_id);
473 function->set_response_callback(callback);
474 function->set_source_tab_id(params.source_tab_id);
475 function->set_source_context_type(
476 process_map.GetMostLikelyContextType(extension, requesting_process_id));
478 return function;
481 // static
482 void ExtensionFunctionDispatcher::SendAccessDenied(
483 const ExtensionFunction::ResponseCallback& callback,
484 functions::HistogramValue histogram_value) {
485 base::ListValue empty_list;
486 callback.Run(ExtensionFunction::FAILED, empty_list,
487 "Access to extension API denied.", histogram_value);
490 } // namespace extensions