Reland the ULONG -> SIZE_T change from 317177
[chromium-blink-merge.git] / extensions / browser / extension_host.cc
blob3d18bf9677db0d383a1bce5b96aca6bdbe713626
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/notification_source.h"
17 #include "content/public/browser/notification_types.h"
18 #include "content/public/browser/render_process_host.h"
19 #include "content/public/browser/render_view_host.h"
20 #include "content/public/browser/render_widget_host_view.h"
21 #include "content/public/browser/site_instance.h"
22 #include "content/public/browser/web_contents.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_system.h"
29 #include "extensions/browser/extensions_browser_client.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 registrar_.Add(this,
80 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
81 content::Source<BrowserContext>(browser_context_));
83 // Set up web contents observers and pref observers.
84 delegate_->OnExtensionHostCreated(host_contents());
87 ExtensionHost::~ExtensionHost() {
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 delegate_->GetExtensionHostQueue()->Remove(this);
101 // Immediately stop observing |host_contents_| because its destruction events
102 // (like DidStopLoading, it turns out) can call back into ExtensionHost
103 // re-entrantly, when anything declared after |host_contents_| has already
104 // been destroyed.
105 content::WebContentsObserver::Observe(nullptr);
108 content::RenderProcessHost* ExtensionHost::render_process_host() const {
109 return render_view_host()->GetProcess();
112 RenderViewHost* ExtensionHost::render_view_host() const {
113 // TODO(mpcomplete): This can be null. How do we handle that?
114 return render_view_host_;
117 bool ExtensionHost::IsRenderViewLive() const {
118 return render_view_host()->IsRenderViewLive();
121 void ExtensionHost::CreateRenderViewSoon() {
122 if (render_process_host() && render_process_host()->HasConnection()) {
123 // If the process is already started, go ahead and initialize the RenderView
124 // synchronously. The process creation is the real meaty part that we want
125 // to defer.
126 CreateRenderViewNow();
127 } else {
128 delegate_->GetExtensionHostQueue()->Add(this);
132 void ExtensionHost::CreateRenderViewNow() {
133 LoadInitialURL();
134 if (IsBackgroundPage()) {
135 DCHECK(IsRenderViewLive());
136 if (extension_) {
137 std::string group_name = base::FieldTrialList::FindFullName(
138 "ThrottleExtensionBackgroundPages");
139 if ((group_name == "ThrottlePersistent" &&
140 extensions::BackgroundInfo::HasPersistentBackgroundPage(
141 extension_)) ||
142 group_name == "ThrottleAll") {
143 host_contents_->WasHidden();
146 // Connect orphaned dev-tools instances.
147 delegate_->OnRenderViewCreatedForBackgroundPage(this);
151 void ExtensionHost::Close() {
152 content::NotificationService::current()->Notify(
153 extensions::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
154 content::Source<BrowserContext>(browser_context_),
155 content::Details<ExtensionHost>(this));
158 void ExtensionHost::AddObserver(ExtensionHostObserver* observer) {
159 observer_list_.AddObserver(observer);
162 void ExtensionHost::RemoveObserver(ExtensionHostObserver* observer) {
163 observer_list_.RemoveObserver(observer);
166 void ExtensionHost::OnMessageDispatched(const std::string& event_name,
167 int message_id) {
168 unacked_messages_.insert(message_id);
169 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
170 OnExtensionMessageDispatched(this, event_name, message_id));
173 void ExtensionHost::OnNetworkRequestStarted(uint64 request_id) {
174 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
175 OnNetworkRequestStarted(this, request_id));
178 void ExtensionHost::OnNetworkRequestDone(uint64 request_id) {
179 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
180 OnNetworkRequestDone(this, request_id));
183 const GURL& ExtensionHost::GetURL() const {
184 return host_contents()->GetURL();
187 void ExtensionHost::LoadInitialURL() {
188 load_start_.reset(new base::ElapsedTimer());
189 host_contents_->GetController().LoadURL(
190 initial_url_, content::Referrer(), ui::PAGE_TRANSITION_LINK,
191 std::string());
194 bool ExtensionHost::IsBackgroundPage() const {
195 DCHECK(extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
196 return true;
199 void ExtensionHost::Observe(int type,
200 const content::NotificationSource& source,
201 const content::NotificationDetails& details) {
202 switch (type) {
203 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED:
204 // The extension object will be deleted after this notification has been
205 // sent. Null it out so that dirty pointer issues don't arise in cases
206 // when multiple ExtensionHost objects pointing to the same Extension are
207 // present.
208 if (extension_ == content::Details<UnloadedExtensionInfo>(details)->
209 extension) {
210 extension_ = nullptr;
212 break;
213 default:
214 NOTREACHED() << "Unexpected notification sent.";
215 break;
219 void ExtensionHost::RenderProcessGone(base::TerminationStatus status) {
220 // During browser shutdown, we may use sudden termination on an extension
221 // process, so it is expected to lose our connection to the render view.
222 // Do nothing.
223 RenderProcessHost* process_host = host_contents_->GetRenderProcessHost();
224 if (process_host && process_host->FastShutdownStarted())
225 return;
227 // In certain cases, multiple ExtensionHost objects may have pointed to
228 // the same Extension at some point (one with a background page and a
229 // popup, for example). When the first ExtensionHost goes away, the extension
230 // is unloaded, and any other host that pointed to that extension will have
231 // its pointer to it null'd out so that any attempt to unload a dirty pointer
232 // will be averted.
233 if (!extension_)
234 return;
236 // TODO(aa): This is suspicious. There can be multiple views in an extension,
237 // and they aren't all going to use ExtensionHost. This should be in someplace
238 // more central, like EPM maybe.
239 content::NotificationService::current()->Notify(
240 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
241 content::Source<BrowserContext>(browser_context_),
242 content::Details<ExtensionHost>(this));
245 void ExtensionHost::DidStopLoading(content::RenderViewHost* render_view_host) {
246 bool notify = !did_stop_loading_;
247 did_stop_loading_ = true;
248 OnDidStopLoading();
249 if (notify) {
250 CHECK(load_start_.get());
251 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
252 if (extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_)) {
253 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.EventPageLoadTime2",
254 load_start_->Elapsed());
255 } else {
256 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.BackgroundPageLoadTime2",
257 load_start_->Elapsed());
259 } else if (extension_host_type_ == VIEW_TYPE_EXTENSION_POPUP) {
260 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupLoadTime2",
261 load_start_->Elapsed());
263 // Send the notification last, because it might result in this being
264 // deleted.
265 content::NotificationService::current()->Notify(
266 extensions::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING,
267 content::Source<BrowserContext>(browser_context_),
268 content::Details<ExtensionHost>(this));
272 void ExtensionHost::OnDidStopLoading() {
273 DCHECK(extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
274 // Nothing to do for background pages.
277 void ExtensionHost::DocumentAvailableInMainFrame() {
278 // If the document has already been marked as available for this host, then
279 // bail. No need for the redundant setup. http://crbug.com/31170
280 if (document_element_available_)
281 return;
282 document_element_available_ = true;
284 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
285 ExtensionSystem::Get(browser_context_)
286 ->runtime_data()
287 ->SetBackgroundPageReady(extension_->id(), true);
288 content::NotificationService::current()->Notify(
289 extensions::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY,
290 content::Source<const Extension>(extension_),
291 content::NotificationService::NoDetails());
295 void ExtensionHost::CloseContents(WebContents* contents) {
296 Close();
299 bool ExtensionHost::OnMessageReceived(const IPC::Message& message) {
300 bool handled = true;
301 IPC_BEGIN_MESSAGE_MAP(ExtensionHost, message)
302 IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request, OnRequest)
303 IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck, OnEventAck)
304 IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount,
305 OnIncrementLazyKeepaliveCount)
306 IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount,
307 OnDecrementLazyKeepaliveCount)
308 IPC_MESSAGE_UNHANDLED(handled = false)
309 IPC_END_MESSAGE_MAP()
310 return handled;
313 void ExtensionHost::OnRequest(const ExtensionHostMsg_Request_Params& params) {
314 extension_function_dispatcher_.Dispatch(params, render_view_host());
317 void ExtensionHost::OnEventAck(int message_id) {
318 EventRouter* router = EventRouter::Get(browser_context_);
319 if (router)
320 router->OnEventAck(browser_context_, extension_id());
322 // A compromised renderer could start sending out arbitrary message ids, which
323 // may affect other renderers by causing downstream methods to think that
324 // messages for other extensions have been acked. Make sure that the message
325 // id sent by the renderer is one that this ExtensionHost expects to receive.
326 // This way if a renderer _is_ compromised, it can really only affect itself.
327 if (unacked_messages_.erase(message_id) > 0) {
328 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
329 OnExtensionMessageAcked(this, message_id));
330 } else {
331 // We have received an unexpected message id from the renderer. It might be
332 // compromised or it might have some other issue. Kill it just to be safe.
333 DCHECK(render_process_host());
334 render_process_host()->ReceivedBadMessage();
338 void ExtensionHost::OnIncrementLazyKeepaliveCount() {
339 ProcessManager::Get(browser_context_)
340 ->IncrementLazyKeepaliveCount(extension());
343 void ExtensionHost::OnDecrementLazyKeepaliveCount() {
344 ProcessManager::Get(browser_context_)
345 ->DecrementLazyKeepaliveCount(extension());
348 // content::WebContentsObserver
350 void ExtensionHost::RenderViewCreated(RenderViewHost* render_view_host) {
351 render_view_host_ = render_view_host;
354 void ExtensionHost::RenderViewDeleted(RenderViewHost* render_view_host) {
355 // If our RenderViewHost is deleted, fall back to the host_contents' current
356 // RVH. There is sometimes a small gap between the pending RVH being deleted
357 // and RenderViewCreated being called, so we update it here.
358 if (render_view_host == render_view_host_)
359 render_view_host_ = host_contents_->GetRenderViewHost();
362 content::JavaScriptDialogManager* ExtensionHost::GetJavaScriptDialogManager(
363 WebContents* source) {
364 return delegate_->GetJavaScriptDialogManager();
367 void ExtensionHost::AddNewContents(WebContents* source,
368 WebContents* new_contents,
369 WindowOpenDisposition disposition,
370 const gfx::Rect& initial_rect,
371 bool user_gesture,
372 bool* was_blocked) {
373 // First, if the creating extension view was associated with a tab contents,
374 // use that tab content's delegate. We must be careful here that the
375 // associated tab contents has the same profile as the new tab contents. In
376 // the case of extensions in 'spanning' incognito mode, they can mismatch.
377 // We don't want to end up putting a normal tab into an incognito window, or
378 // vice versa.
379 // Note that we don't do this for popup windows, because we need to associate
380 // those with their extension_app_id.
381 if (disposition != NEW_POPUP) {
382 WebContents* associated_contents = GetAssociatedWebContents();
383 if (associated_contents &&
384 associated_contents->GetBrowserContext() ==
385 new_contents->GetBrowserContext()) {
386 WebContentsDelegate* delegate = associated_contents->GetDelegate();
387 if (delegate) {
388 delegate->AddNewContents(
389 associated_contents, new_contents, disposition, initial_rect,
390 user_gesture, was_blocked);
391 return;
396 delegate_->CreateTab(
397 new_contents, extension_id_, disposition, initial_rect, user_gesture);
400 void ExtensionHost::RenderViewReady() {
401 content::NotificationService::current()->Notify(
402 extensions::NOTIFICATION_EXTENSION_HOST_CREATED,
403 content::Source<BrowserContext>(browser_context_),
404 content::Details<ExtensionHost>(this));
407 void ExtensionHost::RequestMediaAccessPermission(
408 content::WebContents* web_contents,
409 const content::MediaStreamRequest& request,
410 const content::MediaResponseCallback& callback) {
411 delegate_->ProcessMediaAccessRequest(
412 web_contents, request, callback, extension());
415 bool ExtensionHost::CheckMediaAccessPermission(
416 content::WebContents* web_contents,
417 const GURL& security_origin,
418 content::MediaStreamType type) {
419 return delegate_->CheckMediaAccessPermission(
420 web_contents, security_origin, type, extension());
423 bool ExtensionHost::IsNeverVisible(content::WebContents* web_contents) {
424 ViewType view_type = extensions::GetViewType(web_contents);
425 return view_type == extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE;
428 } // namespace extensions