[Smart Lock] Record a detailed UMA metric for each unlock attempt by Smart Lock users.
[chromium-blink-merge.git] / extensions / browser / extension_host.cc
blobe6424531e6c2ccfaf262320a5b8d60981c0b2824
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 <list>
9 #include "base/bind.h"
10 #include "base/logging.h"
11 #include "base/memory/singleton.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/field_trial.h"
15 #include "base/metrics/histogram_macros.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "content/public/browser/browser_context.h"
19 #include "content/public/browser/content_browser_client.h"
20 #include "content/public/browser/native_web_keyboard_event.h"
21 #include "content/public/browser/notification_service.h"
22 #include "content/public/browser/notification_source.h"
23 #include "content/public/browser/notification_types.h"
24 #include "content/public/browser/render_process_host.h"
25 #include "content/public/browser/render_view_host.h"
26 #include "content/public/browser/render_widget_host_view.h"
27 #include "content/public/browser/site_instance.h"
28 #include "content/public/browser/web_contents.h"
29 #include "extensions/browser/event_router.h"
30 #include "extensions/browser/extension_error.h"
31 #include "extensions/browser/extension_host_delegate.h"
32 #include "extensions/browser/extension_host_observer.h"
33 #include "extensions/browser/extension_system.h"
34 #include "extensions/browser/extensions_browser_client.h"
35 #include "extensions/browser/notification_types.h"
36 #include "extensions/browser/process_manager.h"
37 #include "extensions/browser/runtime_data.h"
38 #include "extensions/browser/view_type_utils.h"
39 #include "extensions/common/extension.h"
40 #include "extensions/common/extension_messages.h"
41 #include "extensions/common/extension_urls.h"
42 #include "extensions/common/feature_switch.h"
43 #include "extensions/common/manifest_handlers/background_info.h"
44 #include "ui/base/l10n/l10n_util.h"
45 #include "ui/base/window_open_disposition.h"
47 using content::BrowserContext;
48 using content::OpenURLParams;
49 using content::RenderProcessHost;
50 using content::RenderViewHost;
51 using content::SiteInstance;
52 using content::WebContents;
54 namespace extensions {
56 // Helper class that rate-limits the creation of renderer processes for
57 // ExtensionHosts, to avoid blocking the UI.
58 class ExtensionHost::ProcessCreationQueue {
59 public:
60 static ProcessCreationQueue* GetInstance() {
61 return Singleton<ProcessCreationQueue>::get();
64 // Add a host to the queue for RenderView creation.
65 void CreateSoon(ExtensionHost* host) {
66 queue_.push_back(host);
67 PostTask();
70 // Remove a host from the queue (in case it's being deleted).
71 void Remove(ExtensionHost* host) {
72 Queue::iterator it = std::find(queue_.begin(), queue_.end(), host);
73 if (it != queue_.end())
74 queue_.erase(it);
77 private:
78 friend class Singleton<ProcessCreationQueue>;
79 friend struct DefaultSingletonTraits<ProcessCreationQueue>;
80 ProcessCreationQueue()
81 : pending_create_(false),
82 ptr_factory_(this) {}
84 // Queue up a delayed task to process the next ExtensionHost in the queue.
85 void PostTask() {
86 if (!pending_create_) {
87 base::MessageLoop::current()->PostTask(FROM_HERE,
88 base::Bind(&ProcessCreationQueue::ProcessOneHost,
89 ptr_factory_.GetWeakPtr()));
90 pending_create_ = true;
94 // Create the RenderView for the next host in the queue.
95 void ProcessOneHost() {
96 pending_create_ = false;
97 if (queue_.empty())
98 return; // can happen on shutdown
100 queue_.front()->CreateRenderViewNow();
101 queue_.pop_front();
103 if (!queue_.empty())
104 PostTask();
107 typedef std::list<ExtensionHost*> Queue;
108 Queue queue_;
109 bool pending_create_;
110 base::WeakPtrFactory<ProcessCreationQueue> ptr_factory_;
113 ////////////////
114 // ExtensionHost
116 ExtensionHost::ExtensionHost(const Extension* extension,
117 SiteInstance* site_instance,
118 const GURL& url,
119 ViewType host_type)
120 : delegate_(ExtensionsBrowserClient::Get()->CreateExtensionHostDelegate()),
121 extension_(extension),
122 extension_id_(extension->id()),
123 browser_context_(site_instance->GetBrowserContext()),
124 render_view_host_(NULL),
125 did_stop_loading_(false),
126 document_element_available_(false),
127 initial_url_(url),
128 extension_function_dispatcher_(browser_context_, this),
129 extension_host_type_(host_type) {
130 // Not used for panels, see PanelHost.
131 DCHECK(host_type == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE ||
132 host_type == VIEW_TYPE_EXTENSION_DIALOG ||
133 host_type == VIEW_TYPE_EXTENSION_INFOBAR ||
134 host_type == VIEW_TYPE_EXTENSION_POPUP);
135 host_contents_.reset(WebContents::Create(
136 WebContents::CreateParams(browser_context_, site_instance))),
137 content::WebContentsObserver::Observe(host_contents_.get());
138 host_contents_->SetDelegate(this);
139 SetViewType(host_contents_.get(), host_type);
141 render_view_host_ = host_contents_->GetRenderViewHost();
143 // Listen for when an extension is unloaded from the same profile, as it may
144 // be the same extension that this points to.
145 registrar_.Add(this,
146 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
147 content::Source<BrowserContext>(browser_context_));
149 // Set up web contents observers and pref observers.
150 delegate_->OnExtensionHostCreated(host_contents());
153 ExtensionHost::~ExtensionHost() {
154 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE &&
155 extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_) &&
156 load_start_.get()) {
157 UMA_HISTOGRAM_LONG_TIMES("Extensions.EventPageActiveTime2",
158 load_start_->Elapsed());
160 content::NotificationService::current()->Notify(
161 extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED,
162 content::Source<BrowserContext>(browser_context_),
163 content::Details<ExtensionHost>(this));
164 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
165 OnExtensionHostDestroyed(this));
166 ProcessCreationQueue::GetInstance()->Remove(this);
169 content::RenderProcessHost* ExtensionHost::render_process_host() const {
170 return render_view_host()->GetProcess();
173 RenderViewHost* ExtensionHost::render_view_host() const {
174 // TODO(mpcomplete): This can be NULL. How do we handle that?
175 return render_view_host_;
178 bool ExtensionHost::IsRenderViewLive() const {
179 return render_view_host()->IsRenderViewLive();
182 void ExtensionHost::CreateRenderViewSoon() {
183 if (render_process_host() && render_process_host()->HasConnection()) {
184 // If the process is already started, go ahead and initialize the RenderView
185 // synchronously. The process creation is the real meaty part that we want
186 // to defer.
187 CreateRenderViewNow();
188 } else {
189 ProcessCreationQueue::GetInstance()->CreateSoon(this);
193 void ExtensionHost::Close() {
194 content::NotificationService::current()->Notify(
195 extensions::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
196 content::Source<BrowserContext>(browser_context_),
197 content::Details<ExtensionHost>(this));
200 void ExtensionHost::CreateRenderViewNow() {
201 LoadInitialURL();
202 if (IsBackgroundPage()) {
203 DCHECK(IsRenderViewLive());
204 if (extension_) {
205 std::string group_name = base::FieldTrialList::FindFullName(
206 "ThrottleExtensionBackgroundPages");
207 if ((group_name == "ThrottlePersistent" &&
208 extensions::BackgroundInfo::HasPersistentBackgroundPage(
209 extension_)) ||
210 group_name == "ThrottleAll") {
211 host_contents_->WasHidden();
214 // Connect orphaned dev-tools instances.
215 delegate_->OnRenderViewCreatedForBackgroundPage(this);
219 void ExtensionHost::AddObserver(ExtensionHostObserver* observer) {
220 observer_list_.AddObserver(observer);
223 void ExtensionHost::RemoveObserver(ExtensionHostObserver* observer) {
224 observer_list_.RemoveObserver(observer);
227 void ExtensionHost::OnMessageDispatched(const std::string& event_name,
228 int message_id) {
229 unacked_messages_.insert(message_id);
230 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
231 OnExtensionMessageDispatched(this, event_name, message_id));
234 void ExtensionHost::OnNetworkRequestStarted(uint64 request_id) {
235 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
236 OnNetworkRequestStarted(this, request_id));
239 void ExtensionHost::OnNetworkRequestDone(uint64 request_id) {
240 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
241 OnNetworkRequestDone(this, request_id));
244 const GURL& ExtensionHost::GetURL() const {
245 return host_contents()->GetURL();
248 void ExtensionHost::LoadInitialURL() {
249 load_start_.reset(new base::ElapsedTimer());
250 host_contents_->GetController().LoadURL(
251 initial_url_, content::Referrer(), ui::PAGE_TRANSITION_LINK,
252 std::string());
255 bool ExtensionHost::IsBackgroundPage() const {
256 DCHECK(extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
257 return true;
260 void ExtensionHost::Observe(int type,
261 const content::NotificationSource& source,
262 const content::NotificationDetails& details) {
263 switch (type) {
264 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED:
265 // The extension object will be deleted after this notification has been
266 // sent. NULL it out so that dirty pointer issues don't arise in cases
267 // when multiple ExtensionHost objects pointing to the same Extension are
268 // present.
269 if (extension_ == content::Details<UnloadedExtensionInfo>(details)->
270 extension) {
271 extension_ = NULL;
273 break;
274 default:
275 NOTREACHED() << "Unexpected notification sent.";
276 break;
280 void ExtensionHost::RenderProcessGone(base::TerminationStatus status) {
281 // During browser shutdown, we may use sudden termination on an extension
282 // process, so it is expected to lose our connection to the render view.
283 // Do nothing.
284 RenderProcessHost* process_host = host_contents_->GetRenderProcessHost();
285 if (process_host && process_host->FastShutdownStarted())
286 return;
288 // In certain cases, multiple ExtensionHost objects may have pointed to
289 // the same Extension at some point (one with a background page and a
290 // popup, for example). When the first ExtensionHost goes away, the extension
291 // is unloaded, and any other host that pointed to that extension will have
292 // its pointer to it NULLed out so that any attempt to unload a dirty pointer
293 // will be averted.
294 if (!extension_)
295 return;
297 // TODO(aa): This is suspicious. There can be multiple views in an extension,
298 // and they aren't all going to use ExtensionHost. This should be in someplace
299 // more central, like EPM maybe.
300 content::NotificationService::current()->Notify(
301 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
302 content::Source<BrowserContext>(browser_context_),
303 content::Details<ExtensionHost>(this));
306 void ExtensionHost::DidStopLoading(content::RenderViewHost* render_view_host) {
307 bool notify = !did_stop_loading_;
308 did_stop_loading_ = true;
309 OnDidStopLoading();
310 if (notify) {
311 // Log metrics. It's tempting to CHECK(load_start_) here, but it's possible
312 // to get a DidStopLoading even if we never started loading, in convoluted
313 // notification and observer chains.
314 if (load_start_.get()) {
315 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
316 if (extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_)) {
317 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.EventPageLoadTime2",
318 load_start_->Elapsed());
319 } else {
320 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.BackgroundPageLoadTime2",
321 load_start_->Elapsed());
323 } else if (extension_host_type_ == VIEW_TYPE_EXTENSION_POPUP) {
324 UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupLoadTime2",
325 load_start_->Elapsed());
329 // Send the notification last, because it might result in this being
330 // deleted.
331 content::NotificationService::current()->Notify(
332 extensions::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING,
333 content::Source<BrowserContext>(browser_context_),
334 content::Details<ExtensionHost>(this));
338 void ExtensionHost::OnDidStopLoading() {
339 DCHECK(extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
340 // Nothing to do for background pages.
343 void ExtensionHost::DocumentAvailableInMainFrame() {
344 // If the document has already been marked as available for this host, then
345 // bail. No need for the redundant setup. http://crbug.com/31170
346 if (document_element_available_)
347 return;
348 document_element_available_ = true;
349 OnDocumentAvailable();
352 void ExtensionHost::OnDocumentAvailable() {
353 DCHECK(extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
354 ExtensionSystem::Get(browser_context_)
355 ->runtime_data()
356 ->SetBackgroundPageReady(extension_->id(), true);
357 content::NotificationService::current()->Notify(
358 extensions::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY,
359 content::Source<const Extension>(extension_),
360 content::NotificationService::NoDetails());
363 void ExtensionHost::CloseContents(WebContents* contents) {
364 Close();
367 bool ExtensionHost::OnMessageReceived(const IPC::Message& message) {
368 bool handled = true;
369 IPC_BEGIN_MESSAGE_MAP(ExtensionHost, message)
370 IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request, OnRequest)
371 IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck, OnEventAck)
372 IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount,
373 OnIncrementLazyKeepaliveCount)
374 IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount,
375 OnDecrementLazyKeepaliveCount)
376 IPC_MESSAGE_UNHANDLED(handled = false)
377 IPC_END_MESSAGE_MAP()
378 return handled;
381 void ExtensionHost::OnRequest(const ExtensionHostMsg_Request_Params& params) {
382 extension_function_dispatcher_.Dispatch(params, render_view_host());
385 void ExtensionHost::OnEventAck(int message_id) {
386 EventRouter* router = EventRouter::Get(browser_context_);
387 if (router)
388 router->OnEventAck(browser_context_, extension_id());
390 // A compromised renderer could start sending out arbitrary message ids, which
391 // may affect other renderers by causing downstream methods to think that
392 // messages for other extensions have been acked. Make sure that the message
393 // id sent by the renderer is one that this ExtensionHost expects to receive.
394 // This way if a renderer _is_ compromised, it can really only affect itself.
395 if (unacked_messages_.erase(message_id) > 0) {
396 FOR_EACH_OBSERVER(ExtensionHostObserver, observer_list_,
397 OnExtensionMessageAcked(this, message_id));
398 } else {
399 // We have received an unexpected message id from the renderer. It might be
400 // compromised or it might have some other issue. Kill it just to be safe.
401 DCHECK(render_process_host());
402 render_process_host()->ReceivedBadMessage();
406 void ExtensionHost::OnIncrementLazyKeepaliveCount() {
407 ProcessManager::Get(browser_context_)
408 ->IncrementLazyKeepaliveCount(extension());
411 void ExtensionHost::OnDecrementLazyKeepaliveCount() {
412 ProcessManager::Get(browser_context_)
413 ->DecrementLazyKeepaliveCount(extension());
416 // content::WebContentsObserver
418 void ExtensionHost::RenderViewCreated(RenderViewHost* render_view_host) {
419 render_view_host_ = render_view_host;
422 void ExtensionHost::RenderViewDeleted(RenderViewHost* render_view_host) {
423 // If our RenderViewHost is deleted, fall back to the host_contents' current
424 // RVH. There is sometimes a small gap between the pending RVH being deleted
425 // and RenderViewCreated being called, so we update it here.
426 if (render_view_host == render_view_host_)
427 render_view_host_ = host_contents_->GetRenderViewHost();
430 content::JavaScriptDialogManager* ExtensionHost::GetJavaScriptDialogManager(
431 WebContents* source) {
432 return delegate_->GetJavaScriptDialogManager();
435 void ExtensionHost::AddNewContents(WebContents* source,
436 WebContents* new_contents,
437 WindowOpenDisposition disposition,
438 const gfx::Rect& initial_rect,
439 bool user_gesture,
440 bool* was_blocked) {
441 // First, if the creating extension view was associated with a tab contents,
442 // use that tab content's delegate. We must be careful here that the
443 // associated tab contents has the same profile as the new tab contents. In
444 // the case of extensions in 'spanning' incognito mode, they can mismatch.
445 // We don't want to end up putting a normal tab into an incognito window, or
446 // vice versa.
447 // Note that we don't do this for popup windows, because we need to associate
448 // those with their extension_app_id.
449 if (disposition != NEW_POPUP) {
450 WebContents* associated_contents = GetAssociatedWebContents();
451 if (associated_contents &&
452 associated_contents->GetBrowserContext() ==
453 new_contents->GetBrowserContext()) {
454 WebContentsDelegate* delegate = associated_contents->GetDelegate();
455 if (delegate) {
456 delegate->AddNewContents(
457 associated_contents, new_contents, disposition, initial_rect,
458 user_gesture, was_blocked);
459 return;
464 delegate_->CreateTab(
465 new_contents, extension_id_, disposition, initial_rect, user_gesture);
468 void ExtensionHost::RenderViewReady() {
469 content::NotificationService::current()->Notify(
470 extensions::NOTIFICATION_EXTENSION_HOST_CREATED,
471 content::Source<BrowserContext>(browser_context_),
472 content::Details<ExtensionHost>(this));
475 void ExtensionHost::RequestMediaAccessPermission(
476 content::WebContents* web_contents,
477 const content::MediaStreamRequest& request,
478 const content::MediaResponseCallback& callback) {
479 delegate_->ProcessMediaAccessRequest(
480 web_contents, request, callback, extension());
483 bool ExtensionHost::CheckMediaAccessPermission(
484 content::WebContents* web_contents,
485 const GURL& security_origin,
486 content::MediaStreamType type) {
487 return delegate_->CheckMediaAccessPermission(
488 web_contents, security_origin, type, extension());
491 bool ExtensionHost::IsNeverVisible(content::WebContents* web_contents) {
492 ViewType view_type = extensions::GetViewType(web_contents);
493 return view_type == extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE;
496 } // namespace extensions