[Android] Add tests for toolbar of Chrome Custom Tabs
[chromium-blink-merge.git] / extensions / browser / extension_host.cc
blobc3e041ae9bf92e005425f71520c98a92bcd0d5b5
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 has_loaded_once_(false),
64 document_element_available_(false),
65 initial_url_(url),
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());
86 ExtensionWebContentsObserver::GetForWebContents(host_contents())->
87 dispatcher()->set_delegate(this);
90 ExtensionHost::~ExtensionHost() {
91 ExtensionRegistry::Get(browser_context_)->RemoveObserver(this);
93 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE &&
94 extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_) &&
95 load_start_.get()) {
96 UMA_HISTOGRAM_LONG_TIMES("Extensions.EventPageActiveTime2",
97 load_start_->Elapsed());
100 content::NotificationService::current()->Notify(
101 extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED,
102 content::Source<BrowserContext>(browser_context_),
103 content::Details<ExtensionHost>(this));
104 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
105 OnExtensionHostDestroyed(this));
106 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver,
107 deferred_start_render_host_observer_list_,
108 OnDeferredStartRenderHostDestroyed(this));
110 // Remove ourselves from the queue as late as possible (before effectively
111 // destroying self, but after everything else) so that queues that are
112 // monitoring lifetime get a chance to see stop-loading events.
113 delegate_->GetExtensionHostQueue()->Remove(this);
115 // Deliberately stop observing |host_contents_| because its destruction
116 // events (like DidStopLoading, it turns out) can call back into
117 // ExtensionHost re-entrantly, when anything declared after |host_contents_|
118 // has already been destroyed.
119 content::WebContentsObserver::Observe(nullptr);
122 content::RenderProcessHost* ExtensionHost::render_process_host() const {
123 return render_view_host()->GetProcess();
126 RenderViewHost* ExtensionHost::render_view_host() const {
127 // TODO(mpcomplete): This can be null. How do we handle that?
128 return render_view_host_;
131 bool ExtensionHost::IsRenderViewLive() const {
132 return render_view_host()->IsRenderViewLive();
135 void ExtensionHost::CreateRenderViewSoon() {
136 if (render_process_host() && render_process_host()->HasConnection()) {
137 // If the process is already started, go ahead and initialize the RenderView
138 // synchronously. The process creation is the real meaty part that we want
139 // to defer.
140 CreateRenderViewNow();
141 } else {
142 delegate_->GetExtensionHostQueue()->Add(this);
146 void ExtensionHost::CreateRenderViewNow() {
147 // TODO(robliao): Remove ScopedTracker below once crbug.com/464206 is fixed.
148 tracked_objects::ScopedTracker tracking_profile1(
149 FROM_HERE_WITH_EXPLICIT_FUNCTION(
150 "464206 ExtensionHost::CreateRenderViewNow1"));
151 LoadInitialURL();
152 if (IsBackgroundPage()) {
153 // TODO(robliao): Remove ScopedTracker below once crbug.com/464206 is fixed.
154 tracked_objects::ScopedTracker tracking_profile2(
155 FROM_HERE_WITH_EXPLICIT_FUNCTION(
156 "464206 ExtensionHost::CreateRenderViewNow2"));
157 DCHECK(IsRenderViewLive());
158 if (extension_) {
159 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(extension_) &&
160 base::FieldTrialList::FindFullName(
161 "ThrottleExtensionBackgroundPages") != "Disabled") {
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,
200 int event_id) {
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,
225 std::string());
228 bool ExtensionHost::IsBackgroundPage() const {
229 DCHECK_EQ(extension_host_type_, VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
230 return true;
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.
248 // Do nothing.
249 RenderProcessHost* process_host = host_contents_->GetRenderProcessHost();
250 if (process_host && process_host->FastShutdownStarted())
251 return;
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
258 // will be averted.
259 if (!extension_)
260 return;
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;
284 if (first_load) {
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_)
306 return;
307 document_element_available_ = true;
309 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
310 ExtensionSystem::Get(browser_context_)
311 ->runtime_data()
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) {
321 Close();
324 bool ExtensionHost::OnMessageReceived(const IPC::Message& message) {
325 bool handled = true;
326 IPC_BEGIN_MESSAGE_MAP(ExtensionHost, message)
327 IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck, OnEventAck)
328 IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount,
329 OnIncrementLazyKeepaliveCount)
330 IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount,
331 OnDecrementLazyKeepaliveCount)
332 IPC_MESSAGE_UNHANDLED(handled = false)
333 IPC_END_MESSAGE_MAP()
334 return handled;
337 void ExtensionHost::OnEventAck(int event_id) {
338 EventRouter* router = EventRouter::Get(browser_context_);
339 if (router)
340 router->OnEventAck(browser_context_, extension_id());
342 // This should always be false since event acks are only sent by extensions
343 // with lazy background pages but it doesn't hurt to be extra careful.
344 if (!IsBackgroundPage()) {
345 NOTREACHED() << "Received EventAck from extension " << extension_id()
346 << ", which does not have a lazy background page.";
347 return;
350 // A compromised renderer could start sending out arbitrary event ids, which
351 // may affect other renderers by causing downstream methods to think that
352 // events for other extensions have been acked. Make sure that the event id
353 // sent by the renderer is one that this ExtensionHost expects to receive.
354 // This way if a renderer _is_ compromised, it can really only affect itself.
355 if (unacked_messages_.erase(event_id) > 0) {
356 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
357 OnBackgroundEventAcked(this, event_id));
358 } else {
359 // We have received an unexpected event id from the renderer. It might be
360 // compromised or it might have some other issue. Kill it just to be safe.
361 DCHECK(render_process_host());
362 LOG(ERROR) << "Killing renderer for extension " << extension_id() << " for "
363 << "sending an EventAck message with a bad event id.";
364 bad_message::ReceivedBadMessage(render_process_host(),
365 bad_message::EH_BAD_EVENT_ID);
369 void ExtensionHost::OnIncrementLazyKeepaliveCount() {
370 ProcessManager::Get(browser_context_)
371 ->IncrementLazyKeepaliveCount(extension());
374 void ExtensionHost::OnDecrementLazyKeepaliveCount() {
375 ProcessManager::Get(browser_context_)
376 ->DecrementLazyKeepaliveCount(extension());
379 // content::WebContentsObserver
381 void ExtensionHost::RenderViewCreated(RenderViewHost* render_view_host) {
382 render_view_host_ = render_view_host;
385 void ExtensionHost::RenderViewDeleted(RenderViewHost* render_view_host) {
386 // If our RenderViewHost is deleted, fall back to the host_contents' current
387 // RVH. There is sometimes a small gap between the pending RVH being deleted
388 // and RenderViewCreated being called, so we update it here.
389 if (render_view_host == render_view_host_)
390 render_view_host_ = host_contents_->GetRenderViewHost();
393 content::JavaScriptDialogManager* ExtensionHost::GetJavaScriptDialogManager(
394 WebContents* source) {
395 return delegate_->GetJavaScriptDialogManager();
398 void ExtensionHost::AddNewContents(WebContents* source,
399 WebContents* new_contents,
400 WindowOpenDisposition disposition,
401 const gfx::Rect& initial_rect,
402 bool user_gesture,
403 bool* was_blocked) {
404 // First, if the creating extension view was associated with a tab contents,
405 // use that tab content's delegate. We must be careful here that the
406 // associated tab contents has the same profile as the new tab contents. In
407 // the case of extensions in 'spanning' incognito mode, they can mismatch.
408 // We don't want to end up putting a normal tab into an incognito window, or
409 // vice versa.
410 // Note that we don't do this for popup windows, because we need to associate
411 // those with their extension_app_id.
412 if (disposition != NEW_POPUP) {
413 WebContents* associated_contents = GetAssociatedWebContents();
414 if (associated_contents &&
415 associated_contents->GetBrowserContext() ==
416 new_contents->GetBrowserContext()) {
417 WebContentsDelegate* delegate = associated_contents->GetDelegate();
418 if (delegate) {
419 delegate->AddNewContents(
420 associated_contents, new_contents, disposition, initial_rect,
421 user_gesture, was_blocked);
422 return;
427 delegate_->CreateTab(
428 new_contents, extension_id_, disposition, initial_rect, user_gesture);
431 void ExtensionHost::RenderViewReady() {
432 content::NotificationService::current()->Notify(
433 extensions::NOTIFICATION_EXTENSION_HOST_CREATED,
434 content::Source<BrowserContext>(browser_context_),
435 content::Details<ExtensionHost>(this));
438 void ExtensionHost::RequestMediaAccessPermission(
439 content::WebContents* web_contents,
440 const content::MediaStreamRequest& request,
441 const content::MediaResponseCallback& callback) {
442 delegate_->ProcessMediaAccessRequest(
443 web_contents, request, callback, extension());
446 bool ExtensionHost::CheckMediaAccessPermission(
447 content::WebContents* web_contents,
448 const GURL& security_origin,
449 content::MediaStreamType type) {
450 return delegate_->CheckMediaAccessPermission(
451 web_contents, security_origin, type, extension());
454 bool ExtensionHost::IsNeverVisible(content::WebContents* web_contents) {
455 ViewType view_type = extensions::GetViewType(web_contents);
456 return view_type == extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE;
459 void ExtensionHost::RecordStopLoadingUMA() {
460 CHECK(load_start_.get());
461 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
462 if (extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_)) {
463 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.EventPageLoadTime2",
464 load_start_->Elapsed());
465 } else {
466 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.BackgroundPageLoadTime2",
467 load_start_->Elapsed());
469 } else if (extension_host_type_ == VIEW_TYPE_EXTENSION_POPUP) {
470 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupLoadTime2",
471 load_start_->Elapsed());
472 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupCreateTime",
473 create_start_.Elapsed());
477 } // namespace extensions