Finish refactoring of DomCodeToUsLayoutKeyboardCode().
[chromium-blink-merge.git] / extensions / browser / extension_host.cc
blob80d0e5bdf6bb20a04d6b3cf39f8d8fb63b852d6c
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 std::string group_name = base::FieldTrialList::FindFullName(
160 "ThrottleExtensionBackgroundPages");
161 if ((group_name == "ThrottlePersistent" &&
162 extensions::BackgroundInfo::HasPersistentBackgroundPage(
163 extension_)) ||
164 group_name == "ThrottleAll") {
165 host_contents_->WasHidden();
168 // TODO(robliao): Remove ScopedTracker below once crbug.com/464206 is fixed.
169 tracked_objects::ScopedTracker tracking_profile3(
170 FROM_HERE_WITH_EXPLICIT_FUNCTION(
171 "464206 ExtensionHost::CreateRenderViewNow3"));
172 // Connect orphaned dev-tools instances.
173 delegate_->OnRenderViewCreatedForBackgroundPage(this);
177 void ExtensionHost::AddDeferredStartRenderHostObserver(
178 DeferredStartRenderHostObserver* observer) {
179 deferred_start_render_host_observer_list_.AddObserver(observer);
182 void ExtensionHost::RemoveDeferredStartRenderHostObserver(
183 DeferredStartRenderHostObserver* observer) {
184 deferred_start_render_host_observer_list_.RemoveObserver(observer);
187 void ExtensionHost::Close() {
188 content::NotificationService::current()->Notify(
189 extensions::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
190 content::Source<BrowserContext>(browser_context_),
191 content::Details<ExtensionHost>(this));
194 void ExtensionHost::AddObserver(ExtensionHostObserver* observer) {
195 observer_list_.AddObserver(observer);
198 void ExtensionHost::RemoveObserver(ExtensionHostObserver* observer) {
199 observer_list_.RemoveObserver(observer);
202 void ExtensionHost::OnBackgroundEventDispatched(const std::string& event_name,
203 int event_id) {
204 CHECK(IsBackgroundPage());
205 unacked_messages_.insert(event_id);
206 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
207 OnBackgroundEventDispatched(this, event_name, event_id));
210 void ExtensionHost::OnNetworkRequestStarted(uint64 request_id) {
211 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
212 OnNetworkRequestStarted(this, request_id));
215 void ExtensionHost::OnNetworkRequestDone(uint64 request_id) {
216 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
217 OnNetworkRequestDone(this, request_id));
220 const GURL& ExtensionHost::GetURL() const {
221 return host_contents()->GetURL();
224 void ExtensionHost::LoadInitialURL() {
225 load_start_.reset(new base::ElapsedTimer());
226 host_contents_->GetController().LoadURL(
227 initial_url_, content::Referrer(), ui::PAGE_TRANSITION_LINK,
228 std::string());
231 bool ExtensionHost::IsBackgroundPage() const {
232 DCHECK_EQ(extension_host_type_, VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
233 return true;
236 void ExtensionHost::OnExtensionUnloaded(
237 content::BrowserContext* browser_context,
238 const Extension* extension,
239 UnloadedExtensionInfo::Reason reason) {
240 // The extension object will be deleted after this notification has been sent.
241 // Null it out so that dirty pointer issues don't arise in cases when multiple
242 // ExtensionHost objects pointing to the same Extension are present.
243 if (extension_ == extension) {
244 extension_ = nullptr;
248 void ExtensionHost::RenderProcessGone(base::TerminationStatus status) {
249 // During browser shutdown, we may use sudden termination on an extension
250 // process, so it is expected to lose our connection to the render view.
251 // Do nothing.
252 RenderProcessHost* process_host = host_contents_->GetRenderProcessHost();
253 if (process_host && process_host->FastShutdownStarted())
254 return;
256 // In certain cases, multiple ExtensionHost objects may have pointed to
257 // the same Extension at some point (one with a background page and a
258 // popup, for example). When the first ExtensionHost goes away, the extension
259 // is unloaded, and any other host that pointed to that extension will have
260 // its pointer to it null'd out so that any attempt to unload a dirty pointer
261 // will be averted.
262 if (!extension_)
263 return;
265 // TODO(aa): This is suspicious. There can be multiple views in an extension,
266 // and they aren't all going to use ExtensionHost. This should be in someplace
267 // more central, like EPM maybe.
268 content::NotificationService::current()->Notify(
269 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
270 content::Source<BrowserContext>(browser_context_),
271 content::Details<ExtensionHost>(this));
274 void ExtensionHost::DidStartLoading() {
275 if (!has_loaded_once_) {
276 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver,
277 deferred_start_render_host_observer_list_,
278 OnDeferredStartRenderHostDidStartFirstLoad(this));
282 void ExtensionHost::DidStopLoading() {
283 // Only record UMA for the first load. Subsequent loads will likely behave
284 // quite different, and it's first load we're most interested in.
285 bool first_load = !has_loaded_once_;
286 has_loaded_once_ = true;
287 if (first_load) {
288 RecordStopLoadingUMA();
289 OnDidStopFirstLoad();
290 content::NotificationService::current()->Notify(
291 extensions::NOTIFICATION_EXTENSION_HOST_DID_STOP_FIRST_LOAD,
292 content::Source<BrowserContext>(browser_context_),
293 content::Details<ExtensionHost>(this));
294 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver,
295 deferred_start_render_host_observer_list_,
296 OnDeferredStartRenderHostDidStopFirstLoad(this));
300 void ExtensionHost::OnDidStopFirstLoad() {
301 DCHECK_EQ(extension_host_type_, VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
302 // Nothing to do for background pages.
305 void ExtensionHost::DocumentAvailableInMainFrame() {
306 // If the document has already been marked as available for this host, then
307 // bail. No need for the redundant setup. http://crbug.com/31170
308 if (document_element_available_)
309 return;
310 document_element_available_ = true;
312 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
313 ExtensionSystem::Get(browser_context_)
314 ->runtime_data()
315 ->SetBackgroundPageReady(extension_->id(), true);
316 content::NotificationService::current()->Notify(
317 extensions::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY,
318 content::Source<const Extension>(extension_),
319 content::NotificationService::NoDetails());
323 void ExtensionHost::CloseContents(WebContents* contents) {
324 Close();
327 bool ExtensionHost::OnMessageReceived(const IPC::Message& message,
328 content::RenderFrameHost* host) {
329 bool handled = true;
330 IPC_BEGIN_MESSAGE_MAP(ExtensionHost, message)
331 IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck, OnEventAck)
332 IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount,
333 OnIncrementLazyKeepaliveCount)
334 IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount,
335 OnDecrementLazyKeepaliveCount)
336 IPC_MESSAGE_UNHANDLED(handled = false)
337 IPC_END_MESSAGE_MAP()
338 return handled;
341 void ExtensionHost::OnEventAck(int event_id) {
342 EventRouter* router = EventRouter::Get(browser_context_);
343 if (router)
344 router->OnEventAck(browser_context_, extension_id());
346 // This should always be false since event acks are only sent by extensions
347 // with lazy background pages but it doesn't hurt to be extra careful.
348 if (!IsBackgroundPage()) {
349 NOTREACHED() << "Received EventAck from extension " << extension_id()
350 << ", which does not have a lazy background page.";
351 return;
354 // A compromised renderer could start sending out arbitrary event ids, which
355 // may affect other renderers by causing downstream methods to think that
356 // events for other extensions have been acked. Make sure that the event id
357 // sent by the renderer is one that this ExtensionHost expects to receive.
358 // This way if a renderer _is_ compromised, it can really only affect itself.
359 if (unacked_messages_.erase(event_id) > 0) {
360 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
361 OnBackgroundEventAcked(this, event_id));
362 } else {
363 // We have received an unexpected event id from the renderer. It might be
364 // compromised or it might have some other issue. Kill it just to be safe.
365 DCHECK(render_process_host());
366 LOG(ERROR) << "Killing renderer for extension " << extension_id() << " for "
367 << "sending an EventAck message with a bad event id.";
368 bad_message::ReceivedBadMessage(render_process_host(),
369 bad_message::EH_BAD_EVENT_ID);
373 void ExtensionHost::OnIncrementLazyKeepaliveCount() {
374 ProcessManager::Get(browser_context_)
375 ->IncrementLazyKeepaliveCount(extension());
378 void ExtensionHost::OnDecrementLazyKeepaliveCount() {
379 ProcessManager::Get(browser_context_)
380 ->DecrementLazyKeepaliveCount(extension());
383 // content::WebContentsObserver
385 void ExtensionHost::RenderViewCreated(RenderViewHost* render_view_host) {
386 render_view_host_ = render_view_host;
389 void ExtensionHost::RenderViewDeleted(RenderViewHost* render_view_host) {
390 // If our RenderViewHost is deleted, fall back to the host_contents' current
391 // RVH. There is sometimes a small gap between the pending RVH being deleted
392 // and RenderViewCreated being called, so we update it here.
393 if (render_view_host == render_view_host_)
394 render_view_host_ = host_contents_->GetRenderViewHost();
397 content::JavaScriptDialogManager* ExtensionHost::GetJavaScriptDialogManager(
398 WebContents* source) {
399 return delegate_->GetJavaScriptDialogManager();
402 void ExtensionHost::AddNewContents(WebContents* source,
403 WebContents* new_contents,
404 WindowOpenDisposition disposition,
405 const gfx::Rect& initial_rect,
406 bool user_gesture,
407 bool* was_blocked) {
408 // First, if the creating extension view was associated with a tab contents,
409 // use that tab content's delegate. We must be careful here that the
410 // associated tab contents has the same profile as the new tab contents. In
411 // the case of extensions in 'spanning' incognito mode, they can mismatch.
412 // We don't want to end up putting a normal tab into an incognito window, or
413 // vice versa.
414 // Note that we don't do this for popup windows, because we need to associate
415 // those with their extension_app_id.
416 if (disposition != NEW_POPUP) {
417 WebContents* associated_contents = GetAssociatedWebContents();
418 if (associated_contents &&
419 associated_contents->GetBrowserContext() ==
420 new_contents->GetBrowserContext()) {
421 WebContentsDelegate* delegate = associated_contents->GetDelegate();
422 if (delegate) {
423 delegate->AddNewContents(
424 associated_contents, new_contents, disposition, initial_rect,
425 user_gesture, was_blocked);
426 return;
431 delegate_->CreateTab(
432 new_contents, extension_id_, disposition, initial_rect, user_gesture);
435 void ExtensionHost::RenderViewReady() {
436 content::NotificationService::current()->Notify(
437 extensions::NOTIFICATION_EXTENSION_HOST_CREATED,
438 content::Source<BrowserContext>(browser_context_),
439 content::Details<ExtensionHost>(this));
442 void ExtensionHost::RequestMediaAccessPermission(
443 content::WebContents* web_contents,
444 const content::MediaStreamRequest& request,
445 const content::MediaResponseCallback& callback) {
446 delegate_->ProcessMediaAccessRequest(
447 web_contents, request, callback, extension());
450 bool ExtensionHost::CheckMediaAccessPermission(
451 content::WebContents* web_contents,
452 const GURL& security_origin,
453 content::MediaStreamType type) {
454 return delegate_->CheckMediaAccessPermission(
455 web_contents, security_origin, type, extension());
458 bool ExtensionHost::IsNeverVisible(content::WebContents* web_contents) {
459 ViewType view_type = extensions::GetViewType(web_contents);
460 return view_type == extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE;
463 void ExtensionHost::RecordStopLoadingUMA() {
464 CHECK(load_start_.get());
465 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
466 if (extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_)) {
467 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.EventPageLoadTime2",
468 load_start_->Elapsed());
469 } else {
470 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.BackgroundPageLoadTime2",
471 load_start_->Elapsed());
473 } else if (extension_host_type_ == VIEW_TYPE_EXTENSION_POPUP) {
474 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupLoadTime2",
475 load_start_->Elapsed());
476 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupCreateTime",
477 create_start_.Elapsed());
481 } // namespace extensions