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_host.h"
10 #include "base/logging.h"
11 #include "base/memory/singleton.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/field_trial.h"
15 #include "base/metrics/histogram.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "content/public/browser/browser_context.h"
19 #include "content/public/browser/content_browser_client.h"
20 #include "content/public/browser/native_web_keyboard_event.h"
21 #include "content/public/browser/notification_service.h"
22 #include "content/public/browser/notification_source.h"
23 #include "content/public/browser/notification_types.h"
24 #include "content/public/browser/render_process_host.h"
25 #include "content/public/browser/render_view_host.h"
26 #include "content/public/browser/render_widget_host_view.h"
27 #include "content/public/browser/site_instance.h"
28 #include "content/public/browser/web_contents.h"
29 #include "extensions/browser/event_router.h"
30 #include "extensions/browser/extension_error.h"
31 #include "extensions/browser/extension_host_delegate.h"
32 #include "extensions/browser/extension_host_observer.h"
33 #include "extensions/browser/extension_system.h"
34 #include "extensions/browser/extensions_browser_client.h"
35 #include "extensions/browser/notification_types.h"
36 #include "extensions/browser/process_manager.h"
37 #include "extensions/browser/runtime_data.h"
38 #include "extensions/browser/view_type_utils.h"
39 #include "extensions/common/extension.h"
40 #include "extensions/common/extension_messages.h"
41 #include "extensions/common/extension_urls.h"
42 #include "extensions/common/feature_switch.h"
43 #include "extensions/common/manifest_handlers/background_info.h"
44 #include "ui/base/l10n/l10n_util.h"
45 #include "ui/base/window_open_disposition.h"
47 using content::BrowserContext
;
48 using content::OpenURLParams
;
49 using content::RenderProcessHost
;
50 using content::RenderViewHost
;
51 using content::SiteInstance
;
52 using content::WebContents
;
54 namespace extensions
{
56 // Helper class that rate-limits the creation of renderer processes for
57 // ExtensionHosts, to avoid blocking the UI.
58 class ExtensionHost::ProcessCreationQueue
{
60 static ProcessCreationQueue
* GetInstance() {
61 return Singleton
<ProcessCreationQueue
>::get();
64 // Add a host to the queue for RenderView creation.
65 void CreateSoon(ExtensionHost
* host
) {
66 queue_
.push_back(host
);
70 // Remove a host from the queue (in case it's being deleted).
71 void Remove(ExtensionHost
* host
) {
72 Queue::iterator it
= std::find(queue_
.begin(), queue_
.end(), host
);
73 if (it
!= queue_
.end())
78 friend class Singleton
<ProcessCreationQueue
>;
79 friend struct DefaultSingletonTraits
<ProcessCreationQueue
>;
80 ProcessCreationQueue()
81 : pending_create_(false),
84 // Queue up a delayed task to process the next ExtensionHost in the queue.
86 if (!pending_create_
) {
87 base::MessageLoop::current()->PostTask(FROM_HERE
,
88 base::Bind(&ProcessCreationQueue::ProcessOneHost
,
89 ptr_factory_
.GetWeakPtr()));
90 pending_create_
= true;
94 // Create the RenderView for the next host in the queue.
95 void ProcessOneHost() {
96 pending_create_
= false;
98 return; // can happen on shutdown
100 queue_
.front()->CreateRenderViewNow();
107 typedef std::list
<ExtensionHost
*> Queue
;
109 bool pending_create_
;
110 base::WeakPtrFactory
<ProcessCreationQueue
> ptr_factory_
;
116 ExtensionHost::ExtensionHost(const Extension
* extension
,
117 SiteInstance
* site_instance
,
120 : delegate_(ExtensionsBrowserClient::Get()->CreateExtensionHostDelegate()),
121 extension_(extension
),
122 extension_id_(extension
->id()),
123 browser_context_(site_instance
->GetBrowserContext()),
124 render_view_host_(NULL
),
125 did_stop_loading_(false),
126 document_element_available_(false),
128 extension_function_dispatcher_(browser_context_
, this),
129 extension_host_type_(host_type
) {
130 // Not used for panels, see PanelHost.
131 DCHECK(host_type
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
||
132 host_type
== VIEW_TYPE_EXTENSION_DIALOG
||
133 host_type
== VIEW_TYPE_EXTENSION_INFOBAR
||
134 host_type
== VIEW_TYPE_EXTENSION_POPUP
);
135 host_contents_
.reset(WebContents::Create(
136 WebContents::CreateParams(browser_context_
, site_instance
))),
137 content::WebContentsObserver::Observe(host_contents_
.get());
138 host_contents_
->SetDelegate(this);
139 SetViewType(host_contents_
.get(), host_type
);
141 render_view_host_
= host_contents_
->GetRenderViewHost();
143 // Listen for when an extension is unloaded from the same profile, as it may
144 // be the same extension that this points to.
146 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
147 content::Source
<BrowserContext
>(browser_context_
));
149 // Set up web contents observers and pref observers.
150 delegate_
->OnExtensionHostCreated(host_contents());
153 ExtensionHost::~ExtensionHost() {
154 if (extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
&&
155 extension_
&& BackgroundInfo::HasLazyBackgroundPage(extension_
)) {
156 UMA_HISTOGRAM_LONG_TIMES("Extensions.EventPageActiveTime",
157 since_created_
.Elapsed());
159 content::NotificationService::current()->Notify(
160 extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED
,
161 content::Source
<BrowserContext
>(browser_context_
),
162 content::Details
<ExtensionHost
>(this));
163 FOR_EACH_OBSERVER(ExtensionHostObserver
, observer_list_
,
164 OnExtensionHostDestroyed(this));
165 ProcessCreationQueue::GetInstance()->Remove(this);
168 content::RenderProcessHost
* ExtensionHost::render_process_host() const {
169 return render_view_host()->GetProcess();
172 RenderViewHost
* ExtensionHost::render_view_host() const {
173 // TODO(mpcomplete): This can be NULL. How do we handle that?
174 return render_view_host_
;
177 bool ExtensionHost::IsRenderViewLive() const {
178 return render_view_host()->IsRenderViewLive();
181 void ExtensionHost::CreateRenderViewSoon() {
182 if ((render_process_host() && render_process_host()->HasConnection())) {
183 // If the process is already started, go ahead and initialize the RenderView
184 // synchronously. The process creation is the real meaty part that we want
186 CreateRenderViewNow();
188 ProcessCreationQueue::GetInstance()->CreateSoon(this);
192 void ExtensionHost::CreateRenderViewNow() {
194 if (IsBackgroundPage()) {
195 DCHECK(IsRenderViewLive());
197 std::string group_name
= base::FieldTrialList::FindFullName(
198 "ThrottleExtensionBackgroundPages");
199 if ((group_name
== "ThrottlePersistent" &&
200 extensions::BackgroundInfo::HasPersistentBackgroundPage(
202 group_name
== "ThrottleAll") {
203 host_contents_
->WasHidden();
206 // Connect orphaned dev-tools instances.
207 delegate_
->OnRenderViewCreatedForBackgroundPage(this);
211 void ExtensionHost::AddObserver(ExtensionHostObserver
* observer
) {
212 observer_list_
.AddObserver(observer
);
215 void ExtensionHost::RemoveObserver(ExtensionHostObserver
* observer
) {
216 observer_list_
.RemoveObserver(observer
);
219 void ExtensionHost::OnMessageDispatched(const std::string
& event_name
,
221 unacked_messages_
.insert(message_id
);
222 FOR_EACH_OBSERVER(ExtensionHostObserver
, observer_list_
,
223 OnExtensionMessageDispatched(this, event_name
, message_id
));
226 void ExtensionHost::OnNetworkRequestStarted(uint64 request_id
) {
227 FOR_EACH_OBSERVER(ExtensionHostObserver
, observer_list_
,
228 OnNetworkRequestStarted(this, request_id
));
231 void ExtensionHost::OnNetworkRequestDone(uint64 request_id
) {
232 FOR_EACH_OBSERVER(ExtensionHostObserver
, observer_list_
,
233 OnNetworkRequestDone(this, request_id
));
236 const GURL
& ExtensionHost::GetURL() const {
237 return host_contents()->GetURL();
240 void ExtensionHost::LoadInitialURL() {
241 host_contents_
->GetController().LoadURL(
242 initial_url_
, content::Referrer(), ui::PAGE_TRANSITION_LINK
,
246 bool ExtensionHost::IsBackgroundPage() const {
247 DCHECK(extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
251 void ExtensionHost::Close() {
252 content::NotificationService::current()->Notify(
253 extensions::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE
,
254 content::Source
<BrowserContext
>(browser_context_
),
255 content::Details
<ExtensionHost
>(this));
258 void ExtensionHost::Observe(int type
,
259 const content::NotificationSource
& source
,
260 const content::NotificationDetails
& details
) {
262 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
:
263 // The extension object will be deleted after this notification has been
264 // sent. NULL it out so that dirty pointer issues don't arise in cases
265 // when multiple ExtensionHost objects pointing to the same Extension are
267 if (extension_
== content::Details
<UnloadedExtensionInfo
>(details
)->
273 NOTREACHED() << "Unexpected notification sent.";
278 void ExtensionHost::RenderProcessGone(base::TerminationStatus status
) {
279 // During browser shutdown, we may use sudden termination on an extension
280 // process, so it is expected to lose our connection to the render view.
282 RenderProcessHost
* process_host
= host_contents_
->GetRenderProcessHost();
283 if (process_host
&& process_host
->FastShutdownStarted())
286 // In certain cases, multiple ExtensionHost objects may have pointed to
287 // the same Extension at some point (one with a background page and a
288 // popup, for example). When the first ExtensionHost goes away, the extension
289 // is unloaded, and any other host that pointed to that extension will have
290 // its pointer to it NULLed out so that any attempt to unload a dirty pointer
295 // TODO(aa): This is suspicious. There can be multiple views in an extension,
296 // and they aren't all going to use ExtensionHost. This should be in someplace
297 // more central, like EPM maybe.
298 content::NotificationService::current()->Notify(
299 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
300 content::Source
<BrowserContext
>(browser_context_
),
301 content::Details
<ExtensionHost
>(this));
304 void ExtensionHost::DidStopLoading(content::RenderViewHost
* render_view_host
) {
305 bool notify
= !did_stop_loading_
;
306 did_stop_loading_
= true;
309 if (extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
) {
310 if (extension_
&& BackgroundInfo::HasLazyBackgroundPage(extension_
)) {
311 UMA_HISTOGRAM_TIMES("Extensions.EventPageLoadTime",
312 since_created_
.Elapsed());
314 UMA_HISTOGRAM_TIMES("Extensions.BackgroundPageLoadTime",
315 since_created_
.Elapsed());
317 } else if (extension_host_type_
== VIEW_TYPE_EXTENSION_DIALOG
) {
318 UMA_HISTOGRAM_TIMES("Extensions.DialogLoadTime",
319 since_created_
.Elapsed());
320 } else if (extension_host_type_
== VIEW_TYPE_EXTENSION_POPUP
) {
321 UMA_HISTOGRAM_TIMES("Extensions.PopupLoadTime",
322 since_created_
.Elapsed());
323 } else if (extension_host_type_
== VIEW_TYPE_EXTENSION_INFOBAR
) {
324 UMA_HISTOGRAM_TIMES("Extensions.InfobarLoadTime",
325 since_created_
.Elapsed());
328 // Send the notification last, because it might result in this being
330 content::NotificationService::current()->Notify(
331 extensions::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING
,
332 content::Source
<BrowserContext
>(browser_context_
),
333 content::Details
<ExtensionHost
>(this));
337 void ExtensionHost::OnDidStopLoading() {
338 DCHECK(extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
339 // Nothing to do for background pages.
342 void ExtensionHost::DocumentAvailableInMainFrame() {
343 // If the document has already been marked as available for this host, then
344 // bail. No need for the redundant setup. http://crbug.com/31170
345 if (document_element_available_
)
347 document_element_available_
= true;
348 OnDocumentAvailable();
351 void ExtensionHost::OnDocumentAvailable() {
352 DCHECK(extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
353 ExtensionSystem::Get(browser_context_
)
355 ->SetBackgroundPageReady(extension_
->id(), true);
356 content::NotificationService::current()->Notify(
357 extensions::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY
,
358 content::Source
<const Extension
>(extension_
),
359 content::NotificationService::NoDetails());
362 void ExtensionHost::CloseContents(WebContents
* contents
) {
366 bool ExtensionHost::OnMessageReceived(const IPC::Message
& message
) {
368 IPC_BEGIN_MESSAGE_MAP(ExtensionHost
, message
)
369 IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request
, OnRequest
)
370 IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck
, OnEventAck
)
371 IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount
,
372 OnIncrementLazyKeepaliveCount
)
373 IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount
,
374 OnDecrementLazyKeepaliveCount
)
375 IPC_MESSAGE_UNHANDLED(handled
= false)
376 IPC_END_MESSAGE_MAP()
380 void ExtensionHost::OnRequest(const ExtensionHostMsg_Request_Params
& params
) {
381 extension_function_dispatcher_
.Dispatch(params
, render_view_host());
384 void ExtensionHost::OnEventAck(int message_id
) {
385 EventRouter
* router
= EventRouter::Get(browser_context_
);
387 router
->OnEventAck(browser_context_
, extension_id());
389 // A compromised renderer could start sending out arbitrary message ids, which
390 // may affect other renderers by causing downstream methods to think that
391 // messages for other extensions have been acked. Make sure that the message
392 // id sent by the renderer is one that this ExtensionHost expects to receive.
393 // This way if a renderer _is_ compromised, it can really only affect itself.
394 if (unacked_messages_
.erase(message_id
) > 0) {
395 FOR_EACH_OBSERVER(ExtensionHostObserver
, observer_list_
,
396 OnExtensionMessageAcked(this, message_id
));
398 // We have received an unexpected message id from the renderer. It might be
399 // compromised or it might have some other issue. Kill it just to be safe.
400 DCHECK(render_process_host());
401 render_process_host()->ReceivedBadMessage();
405 void ExtensionHost::OnIncrementLazyKeepaliveCount() {
406 ProcessManager::Get(browser_context_
)
407 ->IncrementLazyKeepaliveCount(extension());
410 void ExtensionHost::OnDecrementLazyKeepaliveCount() {
411 ProcessManager::Get(browser_context_
)
412 ->DecrementLazyKeepaliveCount(extension());
415 // content::WebContentsObserver
417 void ExtensionHost::RenderViewCreated(RenderViewHost
* render_view_host
) {
418 render_view_host_
= render_view_host
;
421 void ExtensionHost::RenderViewDeleted(RenderViewHost
* render_view_host
) {
422 // If our RenderViewHost is deleted, fall back to the host_contents' current
423 // RVH. There is sometimes a small gap between the pending RVH being deleted
424 // and RenderViewCreated being called, so we update it here.
425 if (render_view_host
== render_view_host_
)
426 render_view_host_
= host_contents_
->GetRenderViewHost();
429 content::JavaScriptDialogManager
* ExtensionHost::GetJavaScriptDialogManager(
430 WebContents
* source
) {
431 return delegate_
->GetJavaScriptDialogManager();
434 void ExtensionHost::AddNewContents(WebContents
* source
,
435 WebContents
* new_contents
,
436 WindowOpenDisposition disposition
,
437 const gfx::Rect
& initial_rect
,
440 // First, if the creating extension view was associated with a tab contents,
441 // use that tab content's delegate. We must be careful here that the
442 // associated tab contents has the same profile as the new tab contents. In
443 // the case of extensions in 'spanning' incognito mode, they can mismatch.
444 // We don't want to end up putting a normal tab into an incognito window, or
446 // Note that we don't do this for popup windows, because we need to associate
447 // those with their extension_app_id.
448 if (disposition
!= NEW_POPUP
) {
449 WebContents
* associated_contents
= GetAssociatedWebContents();
450 if (associated_contents
&&
451 associated_contents
->GetBrowserContext() ==
452 new_contents
->GetBrowserContext()) {
453 WebContentsDelegate
* delegate
= associated_contents
->GetDelegate();
455 delegate
->AddNewContents(
456 associated_contents
, new_contents
, disposition
, initial_rect
,
457 user_gesture
, was_blocked
);
463 delegate_
->CreateTab(
464 new_contents
, extension_id_
, disposition
, initial_rect
, user_gesture
);
467 void ExtensionHost::RenderViewReady() {
468 content::NotificationService::current()->Notify(
469 extensions::NOTIFICATION_EXTENSION_HOST_CREATED
,
470 content::Source
<BrowserContext
>(browser_context_
),
471 content::Details
<ExtensionHost
>(this));
474 void ExtensionHost::RequestMediaAccessPermission(
475 content::WebContents
* web_contents
,
476 const content::MediaStreamRequest
& request
,
477 const content::MediaResponseCallback
& callback
) {
478 delegate_
->ProcessMediaAccessRequest(
479 web_contents
, request
, callback
, extension());
482 bool ExtensionHost::CheckMediaAccessPermission(
483 content::WebContents
* web_contents
,
484 const GURL
& security_origin
,
485 content::MediaStreamType type
) {
486 return delegate_
->CheckMediaAccessPermission(
487 web_contents
, security_origin
, type
, extension());
490 bool ExtensionHost::IsNeverVisible(content::WebContents
* web_contents
) {
491 ViewType view_type
= extensions::GetViewType(web_contents
);
492 return view_type
== extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
;
495 } // namespace extensions