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"
7 #include "base/logging.h"
8 #include "base/metrics/field_trial.h"
9 #include "base/metrics/histogram_macros.h"
10 #include "base/profiler/scoped_tracker.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "content/public/browser/browser_context.h"
14 #include "content/public/browser/content_browser_client.h"
15 #include "content/public/browser/native_web_keyboard_event.h"
16 #include "content/public/browser/notification_service.h"
17 #include "content/public/browser/render_process_host.h"
18 #include "content/public/browser/render_view_host.h"
19 #include "content/public/browser/render_widget_host_view.h"
20 #include "content/public/browser/site_instance.h"
21 #include "content/public/browser/web_contents.h"
22 #include "extensions/browser/bad_message.h"
23 #include "extensions/browser/event_router.h"
24 #include "extensions/browser/extension_error.h"
25 #include "extensions/browser/extension_host_delegate.h"
26 #include "extensions/browser/extension_host_observer.h"
27 #include "extensions/browser/extension_host_queue.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/load_monitoring_extension_host_queue.h"
32 #include "extensions/browser/notification_types.h"
33 #include "extensions/browser/process_manager.h"
34 #include "extensions/browser/runtime_data.h"
35 #include "extensions/browser/view_type_utils.h"
36 #include "extensions/common/extension.h"
37 #include "extensions/common/extension_messages.h"
38 #include "extensions/common/extension_urls.h"
39 #include "extensions/common/feature_switch.h"
40 #include "extensions/common/manifest_handlers/background_info.h"
41 #include "ui/base/l10n/l10n_util.h"
42 #include "ui/base/window_open_disposition.h"
44 using content::BrowserContext
;
45 using content::OpenURLParams
;
46 using content::RenderProcessHost
;
47 using content::RenderViewHost
;
48 using content::SiteInstance
;
49 using content::WebContents
;
51 namespace extensions
{
53 ExtensionHost::ExtensionHost(const Extension
* extension
,
54 SiteInstance
* site_instance
,
57 : delegate_(ExtensionsBrowserClient::Get()->CreateExtensionHostDelegate()),
58 extension_(extension
),
59 extension_id_(extension
->id()),
60 browser_context_(site_instance
->GetBrowserContext()),
61 render_view_host_(nullptr),
62 has_loaded_once_(false),
63 document_element_available_(false),
65 extension_function_dispatcher_(browser_context_
, this),
66 extension_host_type_(host_type
) {
67 // Not used for panels, see PanelHost.
68 DCHECK(host_type
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
||
69 host_type
== VIEW_TYPE_EXTENSION_DIALOG
||
70 host_type
== VIEW_TYPE_EXTENSION_POPUP
);
71 host_contents_
.reset(WebContents::Create(
72 WebContents::CreateParams(browser_context_
, site_instance
))),
73 content::WebContentsObserver::Observe(host_contents_
.get());
74 host_contents_
->SetDelegate(this);
75 SetViewType(host_contents_
.get(), host_type
);
77 render_view_host_
= host_contents_
->GetRenderViewHost();
79 // Listen for when an extension is unloaded from the same profile, as it may
80 // be the same extension that this points to.
81 ExtensionRegistry::Get(browser_context_
)->AddObserver(this);
83 // Set up web contents observers and pref observers.
84 delegate_
->OnExtensionHostCreated(host_contents());
87 ExtensionHost::~ExtensionHost() {
88 ExtensionRegistry::Get(browser_context_
)->RemoveObserver(this);
90 if (extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
&&
91 extension_
&& BackgroundInfo::HasLazyBackgroundPage(extension_
) &&
93 UMA_HISTOGRAM_LONG_TIMES("Extensions.EventPageActiveTime2",
94 load_start_
->Elapsed());
97 content::NotificationService::current()->Notify(
98 extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED
,
99 content::Source
<BrowserContext
>(browser_context_
),
100 content::Details
<ExtensionHost
>(this));
101 FOR_EACH_OBSERVER(ExtensionHostObserver
, observer_list_
,
102 OnExtensionHostDestroyed(this));
103 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver
,
104 deferred_start_render_host_observer_list_
,
105 OnDeferredStartRenderHostDestroyed(this));
107 // Remove ourselves from the queue as late as possible (before effectively
108 // destroying self, but after everything else) so that queues that are
109 // monitoring lifetime get a chance to see stop-loading events.
110 delegate_
->GetExtensionHostQueue()->Remove(this);
112 // Deliberately stop observing |host_contents_| because its destruction
113 // events (like DidStopLoading, it turns out) can call back into
114 // ExtensionHost re-entrantly, when anything declared after |host_contents_|
115 // has already been destroyed.
116 content::WebContentsObserver::Observe(nullptr);
119 content::RenderProcessHost
* ExtensionHost::render_process_host() const {
120 return render_view_host()->GetProcess();
123 RenderViewHost
* ExtensionHost::render_view_host() const {
124 // TODO(mpcomplete): This can be null. How do we handle that?
125 return render_view_host_
;
128 bool ExtensionHost::IsRenderViewLive() const {
129 return render_view_host()->IsRenderViewLive();
132 void ExtensionHost::CreateRenderViewSoon() {
133 if (render_process_host() && render_process_host()->HasConnection()) {
134 // If the process is already started, go ahead and initialize the RenderView
135 // synchronously. The process creation is the real meaty part that we want
137 CreateRenderViewNow();
139 delegate_
->GetExtensionHostQueue()->Add(this);
143 void ExtensionHost::CreateRenderViewNow() {
144 // TODO(robliao): Remove ScopedTracker below once crbug.com/464206 is fixed.
145 tracked_objects::ScopedTracker
tracking_profile1(
146 FROM_HERE_WITH_EXPLICIT_FUNCTION(
147 "464206 ExtensionHost::CreateRenderViewNow1"));
149 if (IsBackgroundPage()) {
150 // TODO(robliao): Remove ScopedTracker below once crbug.com/464206 is fixed.
151 tracked_objects::ScopedTracker
tracking_profile2(
152 FROM_HERE_WITH_EXPLICIT_FUNCTION(
153 "464206 ExtensionHost::CreateRenderViewNow2"));
154 DCHECK(IsRenderViewLive());
156 std::string group_name
= base::FieldTrialList::FindFullName(
157 "ThrottleExtensionBackgroundPages");
158 if ((group_name
== "ThrottlePersistent" &&
159 extensions::BackgroundInfo::HasPersistentBackgroundPage(
161 group_name
== "ThrottleAll") {
162 host_contents_
->WasHidden();
165 // TODO(robliao): Remove ScopedTracker below once crbug.com/464206 is fixed.
166 tracked_objects::ScopedTracker
tracking_profile3(
167 FROM_HERE_WITH_EXPLICIT_FUNCTION(
168 "464206 ExtensionHost::CreateRenderViewNow3"));
169 // Connect orphaned dev-tools instances.
170 delegate_
->OnRenderViewCreatedForBackgroundPage(this);
174 void ExtensionHost::AddDeferredStartRenderHostObserver(
175 DeferredStartRenderHostObserver
* observer
) {
176 deferred_start_render_host_observer_list_
.AddObserver(observer
);
179 void ExtensionHost::RemoveDeferredStartRenderHostObserver(
180 DeferredStartRenderHostObserver
* observer
) {
181 deferred_start_render_host_observer_list_
.RemoveObserver(observer
);
184 void ExtensionHost::Close() {
185 content::NotificationService::current()->Notify(
186 extensions::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE
,
187 content::Source
<BrowserContext
>(browser_context_
),
188 content::Details
<ExtensionHost
>(this));
191 void ExtensionHost::AddObserver(ExtensionHostObserver
* observer
) {
192 observer_list_
.AddObserver(observer
);
195 void ExtensionHost::RemoveObserver(ExtensionHostObserver
* observer
) {
196 observer_list_
.RemoveObserver(observer
);
199 void ExtensionHost::OnBackgroundEventDispatched(const std::string
& event_name
,
201 CHECK(IsBackgroundPage());
202 unacked_messages_
.insert(event_id
);
203 FOR_EACH_OBSERVER(ExtensionHostObserver
, observer_list_
,
204 OnBackgroundEventDispatched(this, event_name
, event_id
));
207 void ExtensionHost::OnNetworkRequestStarted(uint64 request_id
) {
208 FOR_EACH_OBSERVER(ExtensionHostObserver
, observer_list_
,
209 OnNetworkRequestStarted(this, request_id
));
212 void ExtensionHost::OnNetworkRequestDone(uint64 request_id
) {
213 FOR_EACH_OBSERVER(ExtensionHostObserver
, observer_list_
,
214 OnNetworkRequestDone(this, request_id
));
217 const GURL
& ExtensionHost::GetURL() const {
218 return host_contents()->GetURL();
221 void ExtensionHost::LoadInitialURL() {
222 load_start_
.reset(new base::ElapsedTimer());
223 host_contents_
->GetController().LoadURL(
224 initial_url_
, content::Referrer(), ui::PAGE_TRANSITION_LINK
,
228 bool ExtensionHost::IsBackgroundPage() const {
229 DCHECK_EQ(extension_host_type_
, VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
233 void ExtensionHost::OnExtensionUnloaded(
234 content::BrowserContext
* browser_context
,
235 const Extension
* extension
,
236 UnloadedExtensionInfo::Reason reason
) {
237 // The extension object will be deleted after this notification has been sent.
238 // Null it out so that dirty pointer issues don't arise in cases when multiple
239 // ExtensionHost objects pointing to the same Extension are present.
240 if (extension_
== extension
) {
241 extension_
= nullptr;
245 void ExtensionHost::RenderProcessGone(base::TerminationStatus status
) {
246 // During browser shutdown, we may use sudden termination on an extension
247 // process, so it is expected to lose our connection to the render view.
249 RenderProcessHost
* process_host
= host_contents_
->GetRenderProcessHost();
250 if (process_host
&& process_host
->FastShutdownStarted())
253 // In certain cases, multiple ExtensionHost objects may have pointed to
254 // the same Extension at some point (one with a background page and a
255 // popup, for example). When the first ExtensionHost goes away, the extension
256 // is unloaded, and any other host that pointed to that extension will have
257 // its pointer to it null'd out so that any attempt to unload a dirty pointer
262 // TODO(aa): This is suspicious. There can be multiple views in an extension,
263 // and they aren't all going to use ExtensionHost. This should be in someplace
264 // more central, like EPM maybe.
265 content::NotificationService::current()->Notify(
266 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
267 content::Source
<BrowserContext
>(browser_context_
),
268 content::Details
<ExtensionHost
>(this));
271 void ExtensionHost::DidStartLoading() {
272 if (!has_loaded_once_
) {
273 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver
,
274 deferred_start_render_host_observer_list_
,
275 OnDeferredStartRenderHostDidStartFirstLoad(this));
279 void ExtensionHost::DidStopLoading() {
280 // Only record UMA for the first load. Subsequent loads will likely behave
281 // quite different, and it's first load we're most interested in.
282 bool first_load
= !has_loaded_once_
;
283 has_loaded_once_
= true;
285 RecordStopLoadingUMA();
286 OnDidStopFirstLoad();
287 content::NotificationService::current()->Notify(
288 extensions::NOTIFICATION_EXTENSION_HOST_DID_STOP_FIRST_LOAD
,
289 content::Source
<BrowserContext
>(browser_context_
),
290 content::Details
<ExtensionHost
>(this));
291 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver
,
292 deferred_start_render_host_observer_list_
,
293 OnDeferredStartRenderHostDidStopFirstLoad(this));
297 void ExtensionHost::OnDidStopFirstLoad() {
298 DCHECK_EQ(extension_host_type_
, VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
299 // Nothing to do for background pages.
302 void ExtensionHost::DocumentAvailableInMainFrame() {
303 // If the document has already been marked as available for this host, then
304 // bail. No need for the redundant setup. http://crbug.com/31170
305 if (document_element_available_
)
307 document_element_available_
= true;
309 if (extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
) {
310 ExtensionSystem::Get(browser_context_
)
312 ->SetBackgroundPageReady(extension_
->id(), true);
313 content::NotificationService::current()->Notify(
314 extensions::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY
,
315 content::Source
<const Extension
>(extension_
),
316 content::NotificationService::NoDetails());
320 void ExtensionHost::CloseContents(WebContents
* contents
) {
324 bool ExtensionHost::OnMessageReceived(const IPC::Message
& message
) {
326 IPC_BEGIN_MESSAGE_MAP(ExtensionHost
, message
)
327 IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request
, OnRequest
)
328 IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck
, OnEventAck
)
329 IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount
,
330 OnIncrementLazyKeepaliveCount
)
331 IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount
,
332 OnDecrementLazyKeepaliveCount
)
333 IPC_MESSAGE_UNHANDLED(handled
= false)
334 IPC_END_MESSAGE_MAP()
338 void ExtensionHost::OnRequest(const ExtensionHostMsg_Request_Params
& params
) {
339 extension_function_dispatcher_
.Dispatch(params
, render_view_host());
342 void ExtensionHost::OnEventAck(int event_id
) {
343 EventRouter
* router
= EventRouter::Get(browser_context_
);
345 router
->OnEventAck(browser_context_
, extension_id());
347 // This should always be false since event acks are only sent by extensions
348 // with lazy background pages but it doesn't hurt to be extra careful.
349 if (!IsBackgroundPage()) {
350 NOTREACHED() << "Received EventAck from extension " << extension_id()
351 << ", which does not have a lazy background page.";
355 // A compromised renderer could start sending out arbitrary event ids, which
356 // may affect other renderers by causing downstream methods to think that
357 // events for other extensions have been acked. Make sure that the event id
358 // sent by the renderer is one that this ExtensionHost expects to receive.
359 // This way if a renderer _is_ compromised, it can really only affect itself.
360 if (unacked_messages_
.erase(event_id
) > 0) {
361 FOR_EACH_OBSERVER(ExtensionHostObserver
, observer_list_
,
362 OnBackgroundEventAcked(this, event_id
));
364 // We have received an unexpected event id from the renderer. It might be
365 // compromised or it might have some other issue. Kill it just to be safe.
366 DCHECK(render_process_host());
367 LOG(ERROR
) << "Killing renderer for extension " << extension_id() << " for "
368 << "sending an EventAck message with a bad event id.";
369 bad_message::ReceivedBadMessage(render_process_host(),
370 bad_message::EH_BAD_EVENT_ID
);
374 void ExtensionHost::OnIncrementLazyKeepaliveCount() {
375 ProcessManager::Get(browser_context_
)
376 ->IncrementLazyKeepaliveCount(extension());
379 void ExtensionHost::OnDecrementLazyKeepaliveCount() {
380 ProcessManager::Get(browser_context_
)
381 ->DecrementLazyKeepaliveCount(extension());
384 // content::WebContentsObserver
386 void ExtensionHost::RenderViewCreated(RenderViewHost
* render_view_host
) {
387 render_view_host_
= render_view_host
;
390 void ExtensionHost::RenderViewDeleted(RenderViewHost
* render_view_host
) {
391 // If our RenderViewHost is deleted, fall back to the host_contents' current
392 // RVH. There is sometimes a small gap between the pending RVH being deleted
393 // and RenderViewCreated being called, so we update it here.
394 if (render_view_host
== render_view_host_
)
395 render_view_host_
= host_contents_
->GetRenderViewHost();
398 content::JavaScriptDialogManager
* ExtensionHost::GetJavaScriptDialogManager(
399 WebContents
* source
) {
400 return delegate_
->GetJavaScriptDialogManager();
403 void ExtensionHost::AddNewContents(WebContents
* source
,
404 WebContents
* new_contents
,
405 WindowOpenDisposition disposition
,
406 const gfx::Rect
& initial_rect
,
409 // First, if the creating extension view was associated with a tab contents,
410 // use that tab content's delegate. We must be careful here that the
411 // associated tab contents has the same profile as the new tab contents. In
412 // the case of extensions in 'spanning' incognito mode, they can mismatch.
413 // We don't want to end up putting a normal tab into an incognito window, or
415 // Note that we don't do this for popup windows, because we need to associate
416 // those with their extension_app_id.
417 if (disposition
!= NEW_POPUP
) {
418 WebContents
* associated_contents
= GetAssociatedWebContents();
419 if (associated_contents
&&
420 associated_contents
->GetBrowserContext() ==
421 new_contents
->GetBrowserContext()) {
422 WebContentsDelegate
* delegate
= associated_contents
->GetDelegate();
424 delegate
->AddNewContents(
425 associated_contents
, new_contents
, disposition
, initial_rect
,
426 user_gesture
, was_blocked
);
432 delegate_
->CreateTab(
433 new_contents
, extension_id_
, disposition
, initial_rect
, user_gesture
);
436 void ExtensionHost::RenderViewReady() {
437 content::NotificationService::current()->Notify(
438 extensions::NOTIFICATION_EXTENSION_HOST_CREATED
,
439 content::Source
<BrowserContext
>(browser_context_
),
440 content::Details
<ExtensionHost
>(this));
443 void ExtensionHost::RequestMediaAccessPermission(
444 content::WebContents
* web_contents
,
445 const content::MediaStreamRequest
& request
,
446 const content::MediaResponseCallback
& callback
) {
447 delegate_
->ProcessMediaAccessRequest(
448 web_contents
, request
, callback
, extension());
451 bool ExtensionHost::CheckMediaAccessPermission(
452 content::WebContents
* web_contents
,
453 const GURL
& security_origin
,
454 content::MediaStreamType type
) {
455 return delegate_
->CheckMediaAccessPermission(
456 web_contents
, security_origin
, type
, extension());
459 bool ExtensionHost::IsNeverVisible(content::WebContents
* web_contents
) {
460 ViewType view_type
= extensions::GetViewType(web_contents
);
461 return view_type
== extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
;
464 void ExtensionHost::RecordStopLoadingUMA() {
465 CHECK(load_start_
.get());
466 if (extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
) {
467 if (extension_
&& BackgroundInfo::HasLazyBackgroundPage(extension_
)) {
468 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.EventPageLoadTime2",
469 load_start_
->Elapsed());
471 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.BackgroundPageLoadTime2",
472 load_start_
->Elapsed());
474 } else if (extension_host_type_
== VIEW_TYPE_EXTENSION_POPUP
) {
475 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupLoadTime2",
476 load_start_
->Elapsed());
480 } // namespace extensions