ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / extensions / browser / extension_host.cc
blob61d0626dcc597fce162653412b1a66351d482615
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/strings/string_util.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "content/public/browser/browser_context.h"
13 #include "content/public/browser/content_browser_client.h"
14 #include "content/public/browser/native_web_keyboard_event.h"
15 #include "content/public/browser/notification_service.h"
16 #include "content/public/browser/render_process_host.h"
17 #include "content/public/browser/render_view_host.h"
18 #include "content/public/browser/render_widget_host_view.h"
19 #include "content/public/browser/site_instance.h"
20 #include "content/public/browser/web_contents.h"
21 #include "extensions/browser/event_router.h"
22 #include "extensions/browser/extension_error.h"
23 #include "extensions/browser/extension_host_delegate.h"
24 #include "extensions/browser/extension_host_observer.h"
25 #include "extensions/browser/extension_host_queue.h"
26 #include "extensions/browser/extension_registry.h"
27 #include "extensions/browser/extension_system.h"
28 #include "extensions/browser/extensions_browser_client.h"
29 #include "extensions/browser/load_monitoring_extension_host_queue.h"
30 #include "extensions/browser/notification_types.h"
31 #include "extensions/browser/process_manager.h"
32 #include "extensions/browser/runtime_data.h"
33 #include "extensions/browser/view_type_utils.h"
34 #include "extensions/common/extension.h"
35 #include "extensions/common/extension_messages.h"
36 #include "extensions/common/extension_urls.h"
37 #include "extensions/common/feature_switch.h"
38 #include "extensions/common/manifest_handlers/background_info.h"
39 #include "ui/base/l10n/l10n_util.h"
40 #include "ui/base/window_open_disposition.h"
42 using content::BrowserContext;
43 using content::OpenURLParams;
44 using content::RenderProcessHost;
45 using content::RenderViewHost;
46 using content::SiteInstance;
47 using content::WebContents;
49 namespace extensions {
51 ExtensionHost::ExtensionHost(const Extension* extension,
52 SiteInstance* site_instance,
53 const GURL& url,
54 ViewType host_type)
55 : delegate_(ExtensionsBrowserClient::Get()->CreateExtensionHostDelegate()),
56 extension_(extension),
57 extension_id_(extension->id()),
58 browser_context_(site_instance->GetBrowserContext()),
59 render_view_host_(nullptr),
60 did_stop_loading_(false),
61 document_element_available_(false),
62 initial_url_(url),
63 extension_function_dispatcher_(browser_context_, this),
64 extension_host_type_(host_type) {
65 // Not used for panels, see PanelHost.
66 DCHECK(host_type == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE ||
67 host_type == VIEW_TYPE_EXTENSION_DIALOG ||
68 host_type == VIEW_TYPE_EXTENSION_POPUP);
69 host_contents_.reset(WebContents::Create(
70 WebContents::CreateParams(browser_context_, site_instance))),
71 content::WebContentsObserver::Observe(host_contents_.get());
72 host_contents_->SetDelegate(this);
73 SetViewType(host_contents_.get(), host_type);
75 render_view_host_ = host_contents_->GetRenderViewHost();
77 // Listen for when an extension is unloaded from the same profile, as it may
78 // be the same extension that this points to.
79 ExtensionRegistry::Get(browser_context_)->AddObserver(this);
81 // Set up web contents observers and pref observers.
82 delegate_->OnExtensionHostCreated(host_contents());
85 ExtensionHost::~ExtensionHost() {
86 ExtensionRegistry::Get(browser_context_)->RemoveObserver(this);
88 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE &&
89 extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_) &&
90 load_start_.get()) {
91 UMA_HISTOGRAM_LONG_TIMES("Extensions.EventPageActiveTime2",
92 load_start_->Elapsed());
94 content::NotificationService::current()->Notify(
95 extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED,
96 content::Source<BrowserContext>(browser_context_),
97 content::Details<ExtensionHost>(this));
98 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
99 OnExtensionHostDestroyed(this));
100 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver,
101 deferred_start_render_host_observer_list_,
102 OnDeferredStartRenderHostDestroyed(this));
103 delegate_->GetExtensionHostQueue()->Remove(this);
104 // Immediately stop observing |host_contents_| because its destruction events
105 // (like DidStopLoading, it turns out) can call back into ExtensionHost
106 // re-entrantly, when anything declared after |host_contents_| has already
107 // been destroyed.
108 content::WebContentsObserver::Observe(nullptr);
111 content::RenderProcessHost* ExtensionHost::render_process_host() const {
112 return render_view_host()->GetProcess();
115 RenderViewHost* ExtensionHost::render_view_host() const {
116 // TODO(mpcomplete): This can be null. How do we handle that?
117 return render_view_host_;
120 bool ExtensionHost::IsRenderViewLive() const {
121 return render_view_host()->IsRenderViewLive();
124 void ExtensionHost::CreateRenderViewSoon() {
125 if (render_process_host() && render_process_host()->HasConnection()) {
126 // If the process is already started, go ahead and initialize the RenderView
127 // synchronously. The process creation is the real meaty part that we want
128 // to defer.
129 CreateRenderViewNow();
130 } else {
131 delegate_->GetExtensionHostQueue()->Add(this);
135 void ExtensionHost::CreateRenderViewNow() {
136 LoadInitialURL();
137 if (IsBackgroundPage()) {
138 DCHECK(IsRenderViewLive());
139 if (extension_) {
140 std::string group_name = base::FieldTrialList::FindFullName(
141 "ThrottleExtensionBackgroundPages");
142 if ((group_name == "ThrottlePersistent" &&
143 extensions::BackgroundInfo::HasPersistentBackgroundPage(
144 extension_)) ||
145 group_name == "ThrottleAll") {
146 host_contents_->WasHidden();
149 // Connect orphaned dev-tools instances.
150 delegate_->OnRenderViewCreatedForBackgroundPage(this);
154 void ExtensionHost::AddDeferredStartRenderHostObserver(
155 DeferredStartRenderHostObserver* observer) {
156 deferred_start_render_host_observer_list_.AddObserver(observer);
159 void ExtensionHost::RemoveDeferredStartRenderHostObserver(
160 DeferredStartRenderHostObserver* observer) {
161 deferred_start_render_host_observer_list_.RemoveObserver(observer);
164 void ExtensionHost::Close() {
165 content::NotificationService::current()->Notify(
166 extensions::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
167 content::Source<BrowserContext>(browser_context_),
168 content::Details<ExtensionHost>(this));
171 void ExtensionHost::AddObserver(ExtensionHostObserver* observer) {
172 observer_list_.AddObserver(observer);
175 void ExtensionHost::RemoveObserver(ExtensionHostObserver* observer) {
176 observer_list_.RemoveObserver(observer);
179 void ExtensionHost::OnMessageDispatched(const std::string& event_name,
180 int message_id) {
181 unacked_messages_.insert(message_id);
182 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
183 OnExtensionMessageDispatched(this, event_name, message_id));
186 void ExtensionHost::OnNetworkRequestStarted(uint64 request_id) {
187 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
188 OnNetworkRequestStarted(this, request_id));
191 void ExtensionHost::OnNetworkRequestDone(uint64 request_id) {
192 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
193 OnNetworkRequestDone(this, request_id));
196 const GURL& ExtensionHost::GetURL() const {
197 return host_contents()->GetURL();
200 void ExtensionHost::LoadInitialURL() {
201 load_start_.reset(new base::ElapsedTimer());
202 host_contents_->GetController().LoadURL(
203 initial_url_, content::Referrer(), ui::PAGE_TRANSITION_LINK,
204 std::string());
207 bool ExtensionHost::IsBackgroundPage() const {
208 DCHECK(extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
209 return true;
212 void ExtensionHost::OnExtensionUnloaded(
213 content::BrowserContext* browser_context,
214 const Extension* extension,
215 UnloadedExtensionInfo::Reason reason) {
216 // The extension object will be deleted after this notification has been sent.
217 // Null it out so that dirty pointer issues don't arise in cases when multiple
218 // ExtensionHost objects pointing to the same Extension are present.
219 if (extension_ == extension) {
220 extension_ = nullptr;
224 void ExtensionHost::RenderProcessGone(base::TerminationStatus status) {
225 // During browser shutdown, we may use sudden termination on an extension
226 // process, so it is expected to lose our connection to the render view.
227 // Do nothing.
228 RenderProcessHost* process_host = host_contents_->GetRenderProcessHost();
229 if (process_host && process_host->FastShutdownStarted())
230 return;
232 // In certain cases, multiple ExtensionHost objects may have pointed to
233 // the same Extension at some point (one with a background page and a
234 // popup, for example). When the first ExtensionHost goes away, the extension
235 // is unloaded, and any other host that pointed to that extension will have
236 // its pointer to it null'd out so that any attempt to unload a dirty pointer
237 // will be averted.
238 if (!extension_)
239 return;
241 // TODO(aa): This is suspicious. There can be multiple views in an extension,
242 // and they aren't all going to use ExtensionHost. This should be in someplace
243 // more central, like EPM maybe.
244 content::NotificationService::current()->Notify(
245 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
246 content::Source<BrowserContext>(browser_context_),
247 content::Details<ExtensionHost>(this));
250 void ExtensionHost::DidStartLoading(content::RenderViewHost* render_view_host) {
251 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver,
252 deferred_start_render_host_observer_list_,
253 OnDeferredStartRenderHostDidStartLoading(this));
256 void ExtensionHost::DidStopLoading(content::RenderViewHost* render_view_host) {
257 bool notify = !did_stop_loading_;
258 did_stop_loading_ = true;
259 OnDidStopLoading();
260 if (notify) {
261 CHECK(load_start_.get());
262 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
263 if (extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_)) {
264 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.EventPageLoadTime2",
265 load_start_->Elapsed());
266 } else {
267 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.BackgroundPageLoadTime2",
268 load_start_->Elapsed());
270 } else if (extension_host_type_ == VIEW_TYPE_EXTENSION_POPUP) {
271 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupLoadTime2",
272 load_start_->Elapsed());
274 content::NotificationService::current()->Notify(
275 extensions::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING,
276 content::Source<BrowserContext>(browser_context_),
277 content::Details<ExtensionHost>(this));
278 FOR_EACH_OBSERVER(DeferredStartRenderHostObserver,
279 deferred_start_render_host_observer_list_,
280 OnDeferredStartRenderHostDidStopLoading(this));
284 void ExtensionHost::OnDidStopLoading() {
285 DCHECK(extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
286 // Nothing to do for background pages.
289 void ExtensionHost::DocumentAvailableInMainFrame() {
290 // If the document has already been marked as available for this host, then
291 // bail. No need for the redundant setup. http://crbug.com/31170
292 if (document_element_available_)
293 return;
294 document_element_available_ = true;
296 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
297 ExtensionSystem::Get(browser_context_)
298 ->runtime_data()
299 ->SetBackgroundPageReady(extension_->id(), true);
300 content::NotificationService::current()->Notify(
301 extensions::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY,
302 content::Source<const Extension>(extension_),
303 content::NotificationService::NoDetails());
307 void ExtensionHost::CloseContents(WebContents* contents) {
308 Close();
311 bool ExtensionHost::OnMessageReceived(const IPC::Message& message) {
312 bool handled = true;
313 IPC_BEGIN_MESSAGE_MAP(ExtensionHost, message)
314 IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request, OnRequest)
315 IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck, OnEventAck)
316 IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount,
317 OnIncrementLazyKeepaliveCount)
318 IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount,
319 OnDecrementLazyKeepaliveCount)
320 IPC_MESSAGE_UNHANDLED(handled = false)
321 IPC_END_MESSAGE_MAP()
322 return handled;
325 void ExtensionHost::OnRequest(const ExtensionHostMsg_Request_Params& params) {
326 extension_function_dispatcher_.Dispatch(params, render_view_host());
329 void ExtensionHost::OnEventAck(int message_id) {
330 EventRouter* router = EventRouter::Get(browser_context_);
331 if (router)
332 router->OnEventAck(browser_context_, extension_id());
334 // A compromised renderer could start sending out arbitrary message ids, which
335 // may affect other renderers by causing downstream methods to think that
336 // messages for other extensions have been acked. Make sure that the message
337 // id sent by the renderer is one that this ExtensionHost expects to receive.
338 // This way if a renderer _is_ compromised, it can really only affect itself.
339 if (unacked_messages_.erase(message_id) > 0) {
340 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
341 OnExtensionMessageAcked(this, message_id));
342 } else {
343 // We have received an unexpected message id from the renderer. It might be
344 // compromised or it might have some other issue. Kill it just to be safe.
345 DCHECK(render_process_host());
346 render_process_host()->ReceivedBadMessage();
350 void ExtensionHost::OnIncrementLazyKeepaliveCount() {
351 ProcessManager::Get(browser_context_)
352 ->IncrementLazyKeepaliveCount(extension());
355 void ExtensionHost::OnDecrementLazyKeepaliveCount() {
356 ProcessManager::Get(browser_context_)
357 ->DecrementLazyKeepaliveCount(extension());
360 // content::WebContentsObserver
362 void ExtensionHost::RenderViewCreated(RenderViewHost* render_view_host) {
363 render_view_host_ = render_view_host;
366 void ExtensionHost::RenderViewDeleted(RenderViewHost* render_view_host) {
367 // If our RenderViewHost is deleted, fall back to the host_contents' current
368 // RVH. There is sometimes a small gap between the pending RVH being deleted
369 // and RenderViewCreated being called, so we update it here.
370 if (render_view_host == render_view_host_)
371 render_view_host_ = host_contents_->GetRenderViewHost();
374 content::JavaScriptDialogManager* ExtensionHost::GetJavaScriptDialogManager(
375 WebContents* source) {
376 return delegate_->GetJavaScriptDialogManager();
379 void ExtensionHost::AddNewContents(WebContents* source,
380 WebContents* new_contents,
381 WindowOpenDisposition disposition,
382 const gfx::Rect& initial_rect,
383 bool user_gesture,
384 bool* was_blocked) {
385 // First, if the creating extension view was associated with a tab contents,
386 // use that tab content's delegate. We must be careful here that the
387 // associated tab contents has the same profile as the new tab contents. In
388 // the case of extensions in 'spanning' incognito mode, they can mismatch.
389 // We don't want to end up putting a normal tab into an incognito window, or
390 // vice versa.
391 // Note that we don't do this for popup windows, because we need to associate
392 // those with their extension_app_id.
393 if (disposition != NEW_POPUP) {
394 WebContents* associated_contents = GetAssociatedWebContents();
395 if (associated_contents &&
396 associated_contents->GetBrowserContext() ==
397 new_contents->GetBrowserContext()) {
398 WebContentsDelegate* delegate = associated_contents->GetDelegate();
399 if (delegate) {
400 delegate->AddNewContents(
401 associated_contents, new_contents, disposition, initial_rect,
402 user_gesture, was_blocked);
403 return;
408 delegate_->CreateTab(
409 new_contents, extension_id_, disposition, initial_rect, user_gesture);
412 void ExtensionHost::RenderViewReady() {
413 content::NotificationService::current()->Notify(
414 extensions::NOTIFICATION_EXTENSION_HOST_CREATED,
415 content::Source<BrowserContext>(browser_context_),
416 content::Details<ExtensionHost>(this));
419 void ExtensionHost::RequestMediaAccessPermission(
420 content::WebContents* web_contents,
421 const content::MediaStreamRequest& request,
422 const content::MediaResponseCallback& callback) {
423 delegate_->ProcessMediaAccessRequest(
424 web_contents, request, callback, extension());
427 bool ExtensionHost::CheckMediaAccessPermission(
428 content::WebContents* web_contents,
429 const GURL& security_origin,
430 content::MediaStreamType type) {
431 return delegate_->CheckMediaAccessPermission(
432 web_contents, security_origin, type, extension());
435 bool ExtensionHost::IsNeverVisible(content::WebContents* web_contents) {
436 ViewType view_type = extensions::GetViewType(web_contents);
437 return view_type == extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE;
440 } // namespace extensions