Remove linux_chromium_gn_dbg from the chromium CQ.
[chromium-blink-merge.git] / extensions / browser / extension_host.cc
blobdf7b74d754d6df61fb5ed111b2bb64b6f7140bee
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/extension_web_contents_observer.h"
31 #include "extensions/browser/extensions_browser_client.h"
32 #include "extensions/browser/load_monitoring_extension_host_queue.h"
33 #include "extensions/browser/notification_types.h"
34 #include "extensions/browser/process_manager.h"
35 #include "extensions/browser/runtime_data.h"
36 #include "extensions/browser/view_type_utils.h"
37 #include "extensions/common/extension.h"
38 #include "extensions/common/extension_messages.h"
39 #include "extensions/common/extension_urls.h"
40 #include "extensions/common/feature_switch.h"
41 #include "extensions/common/manifest_handlers/background_info.h"
42 #include "ui/base/l10n/l10n_util.h"
43 #include "ui/base/window_open_disposition.h"
45 using content::BrowserContext;
46 using content::OpenURLParams;
47 using content::RenderProcessHost;
48 using content::RenderViewHost;
49 using content::SiteInstance;
50 using content::WebContents;
52 namespace extensions {
54 ExtensionHost::ExtensionHost(const Extension* extension,
55 SiteInstance* site_instance,
56 const GURL& url,
57 ViewType host_type)
58 : delegate_(ExtensionsBrowserClient::Get()->CreateExtensionHostDelegate()),
59 extension_(extension),
60 extension_id_(extension->id()),
61 browser_context_(site_instance->GetBrowserContext()),
62 render_view_host_(nullptr),
63 is_render_view_creation_pending_(false),
64 has_loaded_once_(false),
65 document_element_available_(false),
66 initial_url_(url),
67 extension_host_type_(host_type) {
68 // Not used for panels, see PanelHost.
69 DCHECK(host_type == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE ||
70 host_type == VIEW_TYPE_EXTENSION_DIALOG ||
71 host_type == VIEW_TYPE_EXTENSION_POPUP);
72 host_contents_.reset(WebContents::Create(
73 WebContents::CreateParams(browser_context_, site_instance))),
74 content::WebContentsObserver::Observe(host_contents_.get());
75 host_contents_->SetDelegate(this);
76 SetViewType(host_contents_.get(), host_type);
78 render_view_host_ = host_contents_->GetRenderViewHost();
80 // Listen for when an extension is unloaded from the same profile, as it may
81 // be the same extension that this points to.
82 ExtensionRegistry::Get(browser_context_)->AddObserver(this);
84 // Set up web contents observers and pref observers.
85 delegate_->OnExtensionHostCreated(host_contents());
87 ExtensionWebContentsObserver::GetForWebContents(host_contents())->
88 dispatcher()->set_delegate(this);
91 ExtensionHost::~ExtensionHost() {
92 ExtensionRegistry::Get(browser_context_)->RemoveObserver(this);
94 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE &&
95 extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_) &&
96 load_start_.get()) {
97 UMA_HISTOGRAM_LONG_TIMES("Extensions.EventPageActiveTime2",
98 load_start_->Elapsed());
101 content::NotificationService::current()->Notify(
102 extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED,
103 content::Source<BrowserContext>(browser_context_),
104 content::Details<ExtensionHost>(this));
105 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
106 OnExtensionHostDestroyed(this));
107 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver,
108 deferred_start_render_host_observer_list_,
109 OnDeferredStartRenderHostDestroyed(this));
111 // Remove ourselves from the queue as late as possible (before effectively
112 // destroying self, but after everything else) so that queues that are
113 // monitoring lifetime get a chance to see stop-loading events.
114 delegate_->GetExtensionHostQueue()->Remove(this);
116 // Deliberately stop observing |host_contents_| because its destruction
117 // events (like DidStopLoading, it turns out) can call back into
118 // ExtensionHost re-entrantly, when anything declared after |host_contents_|
119 // has already been destroyed.
120 content::WebContentsObserver::Observe(nullptr);
123 content::RenderProcessHost* ExtensionHost::render_process_host() const {
124 return render_view_host()->GetProcess();
127 RenderViewHost* ExtensionHost::render_view_host() const {
128 // TODO(mpcomplete): This can be null. How do we handle that?
129 return render_view_host_;
132 bool ExtensionHost::IsRenderViewLive() const {
133 return render_view_host()->IsRenderViewLive();
136 void ExtensionHost::CreateRenderViewSoon() {
137 if (render_process_host() && render_process_host()->HasConnection()) {
138 // If the process is already started, go ahead and initialize the RenderView
139 // synchronously. The process creation is the real meaty part that we want
140 // to defer.
141 CreateRenderViewNow();
142 } else {
143 delegate_->GetExtensionHostQueue()->Add(this);
147 void ExtensionHost::CreateRenderViewNow() {
148 // TODO(robliao): Remove ScopedTracker below once crbug.com/464206 is fixed.
149 tracked_objects::ScopedTracker tracking_profile1(
150 FROM_HERE_WITH_EXPLICIT_FUNCTION(
151 "464206 ExtensionHost::CreateRenderViewNow1"));
152 if (!ExtensionRegistry::Get(browser_context_)
153 ->ready_extensions()
154 .Contains(extension_->id())) {
155 is_render_view_creation_pending_ = true;
156 return;
158 is_render_view_creation_pending_ = false;
159 LoadInitialURL();
160 if (IsBackgroundPage()) {
161 // TODO(robliao): Remove ScopedTracker below once crbug.com/464206 is fixed.
162 tracked_objects::ScopedTracker tracking_profile2(
163 FROM_HERE_WITH_EXPLICIT_FUNCTION(
164 "464206 ExtensionHost::CreateRenderViewNow2"));
165 DCHECK(IsRenderViewLive());
166 if (extension_) {
167 std::string group_name = base::FieldTrialList::FindFullName(
168 "ThrottleExtensionBackgroundPages");
169 if ((group_name == "ThrottlePersistent" &&
170 extensions::BackgroundInfo::HasPersistentBackgroundPage(
171 extension_)) ||
172 group_name == "ThrottleAll") {
173 host_contents_->WasHidden();
176 // TODO(robliao): Remove ScopedTracker below once crbug.com/464206 is fixed.
177 tracked_objects::ScopedTracker tracking_profile3(
178 FROM_HERE_WITH_EXPLICIT_FUNCTION(
179 "464206 ExtensionHost::CreateRenderViewNow3"));
180 // Connect orphaned dev-tools instances.
181 delegate_->OnRenderViewCreatedForBackgroundPage(this);
185 void ExtensionHost::AddDeferredStartRenderHostObserver(
186 DeferredStartRenderHostObserver* observer) {
187 deferred_start_render_host_observer_list_.AddObserver(observer);
190 void ExtensionHost::RemoveDeferredStartRenderHostObserver(
191 DeferredStartRenderHostObserver* observer) {
192 deferred_start_render_host_observer_list_.RemoveObserver(observer);
195 void ExtensionHost::Close() {
196 content::NotificationService::current()->Notify(
197 extensions::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
198 content::Source<BrowserContext>(browser_context_),
199 content::Details<ExtensionHost>(this));
202 void ExtensionHost::AddObserver(ExtensionHostObserver* observer) {
203 observer_list_.AddObserver(observer);
206 void ExtensionHost::RemoveObserver(ExtensionHostObserver* observer) {
207 observer_list_.RemoveObserver(observer);
210 void ExtensionHost::OnBackgroundEventDispatched(const std::string& event_name,
211 int event_id) {
212 CHECK(IsBackgroundPage());
213 unacked_messages_.insert(event_id);
214 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
215 OnBackgroundEventDispatched(this, event_name, event_id));
218 void ExtensionHost::OnNetworkRequestStarted(uint64 request_id) {
219 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
220 OnNetworkRequestStarted(this, request_id));
223 void ExtensionHost::OnNetworkRequestDone(uint64 request_id) {
224 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
225 OnNetworkRequestDone(this, request_id));
228 const GURL& ExtensionHost::GetURL() const {
229 return host_contents()->GetURL();
232 void ExtensionHost::LoadInitialURL() {
233 load_start_.reset(new base::ElapsedTimer());
234 host_contents_->GetController().LoadURL(
235 initial_url_, content::Referrer(), ui::PAGE_TRANSITION_LINK,
236 std::string());
239 bool ExtensionHost::IsBackgroundPage() const {
240 DCHECK_EQ(extension_host_type_, VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
241 return true;
244 void ExtensionHost::OnExtensionReady(content::BrowserContext* browser_context,
245 const Extension* extension) {
246 if (is_render_view_creation_pending_)
247 CreateRenderViewNow();
250 void ExtensionHost::OnExtensionUnloaded(
251 content::BrowserContext* browser_context,
252 const Extension* extension,
253 UnloadedExtensionInfo::Reason reason) {
254 // The extension object will be deleted after this notification has been sent.
255 // Null it out so that dirty pointer issues don't arise in cases when multiple
256 // ExtensionHost objects pointing to the same Extension are present.
257 if (extension_ == extension) {
258 extension_ = nullptr;
262 void ExtensionHost::RenderProcessGone(base::TerminationStatus status) {
263 // During browser shutdown, we may use sudden termination on an extension
264 // process, so it is expected to lose our connection to the render view.
265 // Do nothing.
266 RenderProcessHost* process_host = host_contents_->GetRenderProcessHost();
267 if (process_host && process_host->FastShutdownStarted())
268 return;
270 // In certain cases, multiple ExtensionHost objects may have pointed to
271 // the same Extension at some point (one with a background page and a
272 // popup, for example). When the first ExtensionHost goes away, the extension
273 // is unloaded, and any other host that pointed to that extension will have
274 // its pointer to it null'd out so that any attempt to unload a dirty pointer
275 // will be averted.
276 if (!extension_)
277 return;
279 // TODO(aa): This is suspicious. There can be multiple views in an extension,
280 // and they aren't all going to use ExtensionHost. This should be in someplace
281 // more central, like EPM maybe.
282 content::NotificationService::current()->Notify(
283 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
284 content::Source<BrowserContext>(browser_context_),
285 content::Details<ExtensionHost>(this));
288 void ExtensionHost::DidStartLoading() {
289 if (!has_loaded_once_) {
290 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver,
291 deferred_start_render_host_observer_list_,
292 OnDeferredStartRenderHostDidStartFirstLoad(this));
296 void ExtensionHost::DidStopLoading() {
297 // Only record UMA for the first load. Subsequent loads will likely behave
298 // quite different, and it's first load we're most interested in.
299 bool first_load = !has_loaded_once_;
300 has_loaded_once_ = true;
301 if (first_load) {
302 RecordStopLoadingUMA();
303 OnDidStopFirstLoad();
304 content::NotificationService::current()->Notify(
305 extensions::NOTIFICATION_EXTENSION_HOST_DID_STOP_FIRST_LOAD,
306 content::Source<BrowserContext>(browser_context_),
307 content::Details<ExtensionHost>(this));
308 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver,
309 deferred_start_render_host_observer_list_,
310 OnDeferredStartRenderHostDidStopFirstLoad(this));
314 void ExtensionHost::OnDidStopFirstLoad() {
315 DCHECK_EQ(extension_host_type_, VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
316 // Nothing to do for background pages.
319 void ExtensionHost::DocumentAvailableInMainFrame() {
320 // If the document has already been marked as available for this host, then
321 // bail. No need for the redundant setup. http://crbug.com/31170
322 if (document_element_available_)
323 return;
324 document_element_available_ = true;
326 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
327 ExtensionSystem::Get(browser_context_)
328 ->runtime_data()
329 ->SetBackgroundPageReady(extension_->id(), true);
330 content::NotificationService::current()->Notify(
331 extensions::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY,
332 content::Source<const Extension>(extension_),
333 content::NotificationService::NoDetails());
337 void ExtensionHost::CloseContents(WebContents* contents) {
338 Close();
341 bool ExtensionHost::OnMessageReceived(const IPC::Message& message,
342 content::RenderFrameHost* host) {
343 bool handled = true;
344 IPC_BEGIN_MESSAGE_MAP(ExtensionHost, message)
345 IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck, OnEventAck)
346 IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount,
347 OnIncrementLazyKeepaliveCount)
348 IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount,
349 OnDecrementLazyKeepaliveCount)
350 IPC_MESSAGE_UNHANDLED(handled = false)
351 IPC_END_MESSAGE_MAP()
352 return handled;
355 void ExtensionHost::OnEventAck(int event_id) {
356 EventRouter* router = EventRouter::Get(browser_context_);
357 if (router)
358 router->OnEventAck(browser_context_, extension_id());
360 // This should always be false since event acks are only sent by extensions
361 // with lazy background pages but it doesn't hurt to be extra careful.
362 if (!IsBackgroundPage()) {
363 NOTREACHED() << "Received EventAck from extension " << extension_id()
364 << ", which does not have a lazy background page.";
365 return;
368 // A compromised renderer could start sending out arbitrary event ids, which
369 // may affect other renderers by causing downstream methods to think that
370 // events for other extensions have been acked. Make sure that the event id
371 // sent by the renderer is one that this ExtensionHost expects to receive.
372 // This way if a renderer _is_ compromised, it can really only affect itself.
373 if (unacked_messages_.erase(event_id) > 0) {
374 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
375 OnBackgroundEventAcked(this, event_id));
376 } else {
377 // We have received an unexpected event id from the renderer. It might be
378 // compromised or it might have some other issue. Kill it just to be safe.
379 DCHECK(render_process_host());
380 LOG(ERROR) << "Killing renderer for extension " << extension_id() << " for "
381 << "sending an EventAck message with a bad event id.";
382 bad_message::ReceivedBadMessage(render_process_host(),
383 bad_message::EH_BAD_EVENT_ID);
387 void ExtensionHost::OnIncrementLazyKeepaliveCount() {
388 ProcessManager::Get(browser_context_)
389 ->IncrementLazyKeepaliveCount(extension());
392 void ExtensionHost::OnDecrementLazyKeepaliveCount() {
393 ProcessManager::Get(browser_context_)
394 ->DecrementLazyKeepaliveCount(extension());
397 // content::WebContentsObserver
399 void ExtensionHost::RenderViewCreated(RenderViewHost* render_view_host) {
400 render_view_host_ = render_view_host;
403 void ExtensionHost::RenderViewDeleted(RenderViewHost* render_view_host) {
404 // If our RenderViewHost is deleted, fall back to the host_contents' current
405 // RVH. There is sometimes a small gap between the pending RVH being deleted
406 // and RenderViewCreated being called, so we update it here.
407 if (render_view_host == render_view_host_)
408 render_view_host_ = host_contents_->GetRenderViewHost();
411 content::JavaScriptDialogManager* ExtensionHost::GetJavaScriptDialogManager(
412 WebContents* source) {
413 return delegate_->GetJavaScriptDialogManager();
416 void ExtensionHost::AddNewContents(WebContents* source,
417 WebContents* new_contents,
418 WindowOpenDisposition disposition,
419 const gfx::Rect& initial_rect,
420 bool user_gesture,
421 bool* was_blocked) {
422 // First, if the creating extension view was associated with a tab contents,
423 // use that tab content's delegate. We must be careful here that the
424 // associated tab contents has the same profile as the new tab contents. In
425 // the case of extensions in 'spanning' incognito mode, they can mismatch.
426 // We don't want to end up putting a normal tab into an incognito window, or
427 // vice versa.
428 // Note that we don't do this for popup windows, because we need to associate
429 // those with their extension_app_id.
430 if (disposition != NEW_POPUP) {
431 WebContents* associated_contents = GetAssociatedWebContents();
432 if (associated_contents &&
433 associated_contents->GetBrowserContext() ==
434 new_contents->GetBrowserContext()) {
435 WebContentsDelegate* delegate = associated_contents->GetDelegate();
436 if (delegate) {
437 delegate->AddNewContents(
438 associated_contents, new_contents, disposition, initial_rect,
439 user_gesture, was_blocked);
440 return;
445 delegate_->CreateTab(
446 new_contents, extension_id_, disposition, initial_rect, user_gesture);
449 void ExtensionHost::RenderViewReady() {
450 content::NotificationService::current()->Notify(
451 extensions::NOTIFICATION_EXTENSION_HOST_CREATED,
452 content::Source<BrowserContext>(browser_context_),
453 content::Details<ExtensionHost>(this));
456 void ExtensionHost::RequestMediaAccessPermission(
457 content::WebContents* web_contents,
458 const content::MediaStreamRequest& request,
459 const content::MediaResponseCallback& callback) {
460 delegate_->ProcessMediaAccessRequest(
461 web_contents, request, callback, extension());
464 bool ExtensionHost::CheckMediaAccessPermission(
465 content::WebContents* web_contents,
466 const GURL& security_origin,
467 content::MediaStreamType type) {
468 return delegate_->CheckMediaAccessPermission(
469 web_contents, security_origin, type, extension());
472 bool ExtensionHost::IsNeverVisible(content::WebContents* web_contents) {
473 ViewType view_type = extensions::GetViewType(web_contents);
474 return view_type == extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE;
477 void ExtensionHost::RecordStopLoadingUMA() {
478 CHECK(load_start_.get());
479 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
480 if (extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_)) {
481 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.EventPageLoadTime2",
482 load_start_->Elapsed());
483 } else {
484 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.BackgroundPageLoadTime2",
485 load_start_->Elapsed());
487 } else if (extension_host_type_ == VIEW_TYPE_EXTENSION_POPUP) {
488 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupLoadTime2",
489 load_start_->Elapsed());
490 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupCreateTime",
491 create_start_.Elapsed());
495 } // namespace extensions