extension_host.cc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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.
  4. #include "extensions/browser/extension_host.h"
  5. #include <memory>
  6. #include "base/logging.h"
  7. #include "base/metrics/histogram_macros.h"
  8. #include "base/observer_list.h"
  9. #include "base/strings/string_util.h"
  10. #include "base/strings/utf_string_conversions.h"
  11. #include "content/public/browser/browser_context.h"
  12. #include "content/public/browser/content_browser_client.h"
  13. #include "content/public/browser/native_web_keyboard_event.h"
  14. #include "content/public/browser/render_frame_host.h"
  15. #include "content/public/browser/render_process_host.h"
  16. #include "content/public/browser/render_widget_host_view.h"
  17. #include "content/public/browser/site_instance.h"
  18. #include "content/public/browser/web_contents.h"
  19. #include "extensions/browser/bad_message.h"
  20. #include "extensions/browser/event_router.h"
  21. #include "extensions/browser/extension_error.h"
  22. #include "extensions/browser/extension_host_delegate.h"
  23. #include "extensions/browser/extension_host_observer.h"
  24. #include "extensions/browser/extension_host_queue.h"
  25. #include "extensions/browser/extension_host_registry.h"
  26. #include "extensions/browser/extension_registry.h"
  27. #include "extensions/browser/extension_web_contents_observer.h"
  28. #include "extensions/browser/extensions_browser_client.h"
  29. #include "extensions/browser/process_manager.h"
  30. #include "extensions/browser/view_type_utils.h"
  31. #include "extensions/common/extension.h"
  32. #include "extensions/common/extension_messages.h"
  33. #include "extensions/common/extension_urls.h"
  34. #include "extensions/common/feature_switch.h"
  35. #include "extensions/common/manifest_handlers/background_info.h"
  36. #include "ui/base/l10n/l10n_util.h"
  37. #include "ui/base/window_open_disposition.h"
  38. using content::RenderProcessHost;
  39. using content::SiteInstance;
  40. using content::WebContents;
  41. namespace extensions {
  42. ExtensionHost::ExtensionHost(const Extension* extension,
  43. SiteInstance* site_instance,
  44. const GURL& url,
  45. mojom::ViewType host_type)
  46. : delegate_(ExtensionsBrowserClient::Get()->CreateExtensionHostDelegate()),
  47. extension_(extension),
  48. extension_id_(extension->id()),
  49. browser_context_(site_instance->GetBrowserContext()),
  50. initial_url_(url),
  51. extension_host_type_(host_type) {
  52. DCHECK(host_type == mojom::ViewType::kExtensionBackgroundPage ||
  53. host_type == mojom::ViewType::kOffscreenDocument ||
  54. host_type == mojom::ViewType::kExtensionDialog ||
  55. host_type == mojom::ViewType::kExtensionPopup);
  56. host_contents_ = WebContents::Create(
  57. WebContents::CreateParams(browser_context_, site_instance)),
  58. content::WebContentsObserver::Observe(host_contents_.get());
  59. host_contents_->SetDelegate(this);
  60. SetViewType(host_contents_.get(), host_type);
  61. main_frame_host_ = host_contents_->GetPrimaryMainFrame();
  62. // Listen for when an extension is unloaded from the same profile, as it may
  63. // be the same extension that this points to.
  64. ExtensionRegistry::Get(browser_context_)->AddObserver(this);
  65. // Set up web contents observers and pref observers.
  66. delegate_->OnExtensionHostCreated(host_contents());
  67. ExtensionWebContentsObserver::GetForWebContents(host_contents())->
  68. dispatcher()->set_delegate(this);
  69. ExtensionHostRegistry::Get(browser_context_)->ExtensionHostCreated(this);
  70. }
  71. ExtensionHost::~ExtensionHost() {
  72. ExtensionRegistry::Get(browser_context_)->RemoveObserver(this);
  73. if (extension_host_type_ == mojom::ViewType::kExtensionBackgroundPage &&
  74. extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_) &&
  75. load_start_.get()) {
  76. UMA_HISTOGRAM_LONG_TIMES("Extensions.EventPageActiveTime2",
  77. load_start_->Elapsed());
  78. }
  79. for (auto& observer : observer_list_)
  80. observer.OnExtensionHostDestroyed(this);
  81. ExtensionHostRegistry::Get(browser_context_)->ExtensionHostDestroyed(this);
  82. // Remove ourselves from the queue as late as possible (before effectively
  83. // destroying self, but after everything else) so that queues that are
  84. // monitoring lifetime get a chance to see stop-loading events.
  85. ExtensionHostQueue::GetInstance().Remove(this);
  86. // Deliberately stop observing |host_contents_| because its destruction
  87. // events (like DidStopLoading, it turns out) can call back into
  88. // ExtensionHost re-entrantly, when anything declared after |host_contents_|
  89. // has already been destroyed.
  90. content::WebContentsObserver::Observe(nullptr);
  91. }
  92. content::RenderProcessHost* ExtensionHost::render_process_host() const {
  93. return main_frame_host_->GetProcess();
  94. }
  95. bool ExtensionHost::IsRendererLive() const {
  96. return main_frame_host_->IsRenderFrameLive();
  97. }
  98. void ExtensionHost::CreateRendererSoon() {
  99. if (render_process_host() &&
  100. render_process_host()->IsInitializedAndNotDead()) {
  101. // If the process is already started, go ahead and initialize the renderer
  102. // frame synchronously. The process creation is the real meaty part that we
  103. // want to defer.
  104. CreateRendererNow();
  105. } else {
  106. ExtensionHostQueue::GetInstance().Add(this);
  107. }
  108. }
  109. void ExtensionHost::CreateRendererNow() {
  110. if (!ExtensionRegistry::Get(browser_context_)
  111. ->ready_extensions()
  112. .Contains(extension_->id())) {
  113. is_renderer_creation_pending_ = true;
  114. return;
  115. }
  116. is_renderer_creation_pending_ = false;
  117. LoadInitialURL();
  118. if (IsBackgroundPage()) {
  119. DCHECK(IsRendererLive());
  120. // Connect orphaned dev-tools instances.
  121. delegate_->OnMainFrameCreatedForBackgroundPage(this);
  122. }
  123. }
  124. void ExtensionHost::Close() {
  125. // Some ways of closing the host may be asynchronous, which would allow the
  126. // contents to call Close() multiple times. If we've already called the
  127. // handler once, ignore subsequent calls. If we haven't called the handler
  128. // once, the handler should be present.
  129. DCHECK(close_handler_ || called_close_handler_);
  130. if (called_close_handler_)
  131. return;
  132. called_close_handler_ = true;
  133. std::move(close_handler_).Run(this);
  134. // NOTE: `this` may be deleted at this point!
  135. }
  136. void ExtensionHost::AddObserver(ExtensionHostObserver* observer) {
  137. observer_list_.AddObserver(observer);
  138. }
  139. void ExtensionHost::RemoveObserver(ExtensionHostObserver* observer) {
  140. observer_list_.RemoveObserver(observer);
  141. }
  142. void ExtensionHost::OnBackgroundEventDispatched(const std::string& event_name,
  143. int event_id) {
  144. CHECK(IsBackgroundPage());
  145. unacked_messages_[event_id] = event_name;
  146. for (auto& observer : observer_list_)
  147. observer.OnBackgroundEventDispatched(this, event_name, event_id);
  148. }
  149. void ExtensionHost::OnNetworkRequestStarted(uint64_t request_id) {
  150. for (auto& observer : observer_list_)
  151. observer.OnNetworkRequestStarted(this, request_id);
  152. }
  153. void ExtensionHost::OnNetworkRequestDone(uint64_t request_id) {
  154. for (auto& observer : observer_list_)
  155. observer.OnNetworkRequestDone(this, request_id);
  156. }
  157. void ExtensionHost::SetCloseHandler(CloseHandler close_handler) {
  158. DCHECK(!close_handler_);
  159. DCHECK(!called_close_handler_);
  160. close_handler_ = std::move(close_handler);
  161. }
  162. bool ExtensionHost::ShouldAllowNavigations() const {
  163. // Don't allow background pages or offscreen documents to navigate.
  164. return extension_host_type_ != mojom::ViewType::kExtensionBackgroundPage &&
  165. extension_host_type_ != mojom::ViewType::kOffscreenDocument;
  166. }
  167. const GURL& ExtensionHost::GetLastCommittedURL() const {
  168. return host_contents()->GetLastCommittedURL();
  169. }
  170. void ExtensionHost::LoadInitialURL() {
  171. load_start_ = std::make_unique<base::ElapsedTimer>();
  172. host_contents_->GetController().LoadURL(
  173. initial_url_, content::Referrer(), ui::PAGE_TRANSITION_LINK,
  174. std::string());
  175. }
  176. bool ExtensionHost::IsBackgroundPage() const {
  177. DCHECK_EQ(extension_host_type_, mojom::ViewType::kExtensionBackgroundPage);
  178. return true;
  179. }
  180. void ExtensionHost::OnExtensionReady(content::BrowserContext* browser_context,
  181. const Extension* extension) {
  182. if (is_renderer_creation_pending_)
  183. CreateRendererNow();
  184. }
  185. void ExtensionHost::OnExtensionUnloaded(
  186. content::BrowserContext* browser_context,
  187. const Extension* extension,
  188. UnloadedExtensionReason reason) {
  189. // The extension object will be deleted after this notification has been sent.
  190. // Null it out so that dirty pointer issues don't arise in cases when multiple
  191. // ExtensionHost objects pointing to the same Extension are present.
  192. if (extension_ == extension) {
  193. extension_ = nullptr;
  194. }
  195. }
  196. void ExtensionHost::PrimaryMainFrameRenderProcessGone(
  197. base::TerminationStatus status) {
  198. // During browser shutdown, we may use sudden termination on an extension
  199. // process, so it is expected to lose our connection to the render view.
  200. // Do nothing.
  201. RenderProcessHost* process_host =
  202. host_contents_->GetPrimaryMainFrame()->GetProcess();
  203. if (process_host && process_host->FastShutdownStarted())
  204. return;
  205. // In certain cases, multiple ExtensionHost objects may have pointed to
  206. // the same Extension at some point (one with a background page and a
  207. // popup, for example). When the first ExtensionHost goes away, the extension
  208. // is unloaded, and any other host that pointed to that extension will have
  209. // its pointer to it null'd out so that any attempt to unload a dirty pointer
  210. // will be averted.
  211. if (!extension_)
  212. return;
  213. // TODO(aa): This is suspicious. There can be multiple views in an extension,
  214. // and they aren't all going to use ExtensionHost. This should be in someplace
  215. // more central, like EPM maybe.
  216. ExtensionHostRegistry::Get(browser_context_)
  217. ->ExtensionHostRenderProcessGone(this);
  218. ProcessManager::Get(browser_context_)
  219. ->NotifyExtensionProcessTerminated(extension_);
  220. }
  221. void ExtensionHost::DidStopLoading() {
  222. // Only record UMA for the first load. Subsequent loads will likely behave
  223. // quite different, and it's first load we're most interested in.
  224. bool first_load = !has_loaded_once_;
  225. has_loaded_once_ = true;
  226. if (first_load) {
  227. RecordStopLoadingUMA();
  228. OnDidStopFirstLoad();
  229. ExtensionHostRegistry::Get(browser_context_)
  230. ->ExtensionHostCompletedFirstLoad(this);
  231. for (auto& observer : observer_list_)
  232. observer.OnExtensionHostDidStopFirstLoad(this);
  233. }
  234. }
  235. void ExtensionHost::OnDidStopFirstLoad() {
  236. DCHECK_EQ(extension_host_type_, mojom::ViewType::kExtensionBackgroundPage);
  237. // Nothing to do for background pages.
  238. }
  239. void ExtensionHost::PrimaryMainDocumentElementAvailable() {
  240. // If the document has already been marked as available for this host, then
  241. // bail. No need for the redundant setup. http://crbug.com/31170
  242. if (document_element_available_)
  243. return;
  244. document_element_available_ = true;
  245. ExtensionHostRegistry::Get(browser_context_)
  246. ->ExtensionHostDocumentElementAvailable(this);
  247. }
  248. void ExtensionHost::CloseContents(WebContents* contents) {
  249. Close();
  250. }
  251. bool ExtensionHost::OnMessageReceived(const IPC::Message& message,
  252. content::RenderFrameHost* host) {
  253. bool handled = true;
  254. IPC_BEGIN_MESSAGE_MAP(ExtensionHost, message)
  255. IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck, OnEventAck)
  256. IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount,
  257. OnIncrementLazyKeepaliveCount)
  258. IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount,
  259. OnDecrementLazyKeepaliveCount)
  260. IPC_MESSAGE_UNHANDLED(handled = false)
  261. IPC_END_MESSAGE_MAP()
  262. return handled;
  263. }
  264. void ExtensionHost::OnEventAck(int event_id) {
  265. // This should always be true since event acks are only sent by extensions
  266. // with lazy background pages but it doesn't hurt to be extra careful.
  267. const bool is_background_page = IsBackgroundPage();
  268. // A compromised renderer could start sending out arbitrary event ids, which
  269. // may affect other renderers by causing downstream methods to think that
  270. // events for other extensions have been acked. Make sure that the event id
  271. // sent by the renderer is one that this ExtensionHost expects to receive.
  272. // This way if a renderer _is_ compromised, it can really only affect itself.
  273. if (!is_background_page) {
  274. // Kill this renderer.
  275. DCHECK(render_process_host());
  276. LOG(ERROR) << "Killing renderer for extension " << extension_id()
  277. << " for sending an EventAck without a lazy background page.";
  278. bad_message::ReceivedBadMessage(render_process_host(),
  279. bad_message::EH_BAD_EVENT_ID);
  280. return;
  281. }
  282. const auto it = unacked_messages_.find(event_id);
  283. if (it == unacked_messages_.end()) {
  284. // Ideally, we'd be able to kill the renderer in the case of it sending an
  285. // ack for an event that we haven't seen. However, https://crbug.com/939279
  286. // demonstrates that there are cases in which this can happen in other
  287. // situations. We should track those down and fix them, but for now
  288. // log and gracefully exit.
  289. // bad_message::ReceivedBadMessage(render_process_host(),
  290. // bad_message::EH_BAD_EVENT_ID);
  291. LOG(ERROR) << "Received EventAck for extension " << extension_id()
  292. << " for an unknown event.";
  293. return;
  294. }
  295. EventRouter* router = EventRouter::Get(browser_context_);
  296. if (router)
  297. router->OnEventAck(browser_context_, extension_id(), it->second);
  298. for (auto& observer : observer_list_)
  299. observer.OnBackgroundEventAcked(this, event_id);
  300. // Remove it.
  301. unacked_messages_.erase(it);
  302. }
  303. void ExtensionHost::OnIncrementLazyKeepaliveCount() {
  304. ProcessManager::Get(browser_context_)
  305. ->IncrementLazyKeepaliveCount(extension(), Activity::LIFECYCLE_MANAGEMENT,
  306. Activity::kIPC);
  307. }
  308. void ExtensionHost::OnDecrementLazyKeepaliveCount() {
  309. ProcessManager::Get(browser_context_)
  310. ->DecrementLazyKeepaliveCount(extension(), Activity::LIFECYCLE_MANAGEMENT,
  311. Activity::kIPC);
  312. }
  313. // content::WebContentsObserver
  314. content::JavaScriptDialogManager* ExtensionHost::GetJavaScriptDialogManager(
  315. WebContents* source) {
  316. return delegate_->GetJavaScriptDialogManager();
  317. }
  318. void ExtensionHost::AddNewContents(WebContents* source,
  319. std::unique_ptr<WebContents> new_contents,
  320. const GURL& target_url,
  321. WindowOpenDisposition disposition,
  322. const gfx::Rect& initial_rect,
  323. bool user_gesture,
  324. bool* was_blocked) {
  325. // First, if the creating extension view was associated with a tab contents,
  326. // use that tab content's delegate. We must be careful here that the
  327. // associated tab contents has the same profile as the new tab contents. In
  328. // the case of extensions in 'spanning' incognito mode, they can mismatch.
  329. // We don't want to end up putting a normal tab into an incognito window, or
  330. // vice versa.
  331. // Note that we don't do this for popup windows, because we need to associate
  332. // those with their extension_app_id.
  333. if (disposition != WindowOpenDisposition::NEW_POPUP) {
  334. WebContents* associated_contents = GetAssociatedWebContents();
  335. if (associated_contents &&
  336. associated_contents->GetBrowserContext() ==
  337. new_contents->GetBrowserContext()) {
  338. WebContentsDelegate* delegate = associated_contents->GetDelegate();
  339. if (delegate) {
  340. delegate->AddNewContents(associated_contents, std::move(new_contents),
  341. target_url, disposition, initial_rect,
  342. user_gesture, was_blocked);
  343. return;
  344. }
  345. }
  346. }
  347. delegate_->CreateTab(std::move(new_contents), extension_id_, disposition,
  348. initial_rect, user_gesture);
  349. }
  350. void ExtensionHost::RenderFrameCreated(content::RenderFrameHost* frame_host) {
  351. // Only consider the main frame. Ignore all other frames, including
  352. // speculative main frames (which might replace the main frame, but that
  353. // scenario is handled in `RenderFrameHostChanged`).
  354. if (frame_host != main_frame_host_)
  355. return;
  356. MaybeNotifyRenderProcessReady();
  357. }
  358. void ExtensionHost::RenderFrameHostChanged(content::RenderFrameHost* old_host,
  359. content::RenderFrameHost* new_host) {
  360. // Only the primary main frame is tracked, so ignore any other frames.
  361. if (old_host != main_frame_host_)
  362. return;
  363. main_frame_host_ = new_host;
  364. // The RenderFrame already exists when this callback is fired. Try to notify
  365. // again in case we missed the `RenderFrameCreated` callback (e.g. when the
  366. // ExtensionHost is attached after the main frame started a navigation).
  367. MaybeNotifyRenderProcessReady();
  368. }
  369. void ExtensionHost::MaybeNotifyRenderProcessReady() {
  370. if (!has_creation_notification_already_fired_) {
  371. has_creation_notification_already_fired_ = true;
  372. // When the first renderer comes alive, we wait for the process to complete
  373. // its initialization then notify observers.
  374. render_process_host()->PostTaskWhenProcessIsReady(
  375. base::BindOnce(&ExtensionHost::NotifyRenderProcessReady,
  376. weak_ptr_factory_.GetWeakPtr()));
  377. }
  378. }
  379. void ExtensionHost::NotifyRenderProcessReady() {
  380. ExtensionHostRegistry::Get(browser_context_)
  381. ->ExtensionHostRenderProcessReady(this);
  382. }
  383. void ExtensionHost::RequestMediaAccessPermission(
  384. content::WebContents* web_contents,
  385. const content::MediaStreamRequest& request,
  386. content::MediaResponseCallback callback) {
  387. delegate_->ProcessMediaAccessRequest(web_contents, request,
  388. std::move(callback), extension());
  389. }
  390. bool ExtensionHost::CheckMediaAccessPermission(
  391. content::RenderFrameHost* render_frame_host,
  392. const GURL& security_origin,
  393. blink::mojom::MediaStreamType type) {
  394. return delegate_->CheckMediaAccessPermission(
  395. render_frame_host, security_origin, type, extension());
  396. }
  397. bool ExtensionHost::IsNeverComposited(content::WebContents* web_contents) {
  398. mojom::ViewType view_type = extensions::GetViewType(web_contents);
  399. return view_type == mojom::ViewType::kExtensionBackgroundPage ||
  400. view_type == mojom::ViewType::kOffscreenDocument;
  401. }
  402. content::PictureInPictureResult ExtensionHost::EnterPictureInPicture(
  403. content::WebContents* web_contents) {
  404. return delegate_->EnterPictureInPicture(web_contents);
  405. }
  406. void ExtensionHost::ExitPictureInPicture() {
  407. delegate_->ExitPictureInPicture();
  408. }
  409. std::string ExtensionHost::GetTitleForMediaControls(
  410. content::WebContents* web_contents) {
  411. return extension() ? extension()->name() : std::string();
  412. }
  413. void ExtensionHost::RecordStopLoadingUMA() {
  414. CHECK(load_start_.get());
  415. if (extension_host_type_ == mojom::ViewType::kExtensionBackgroundPage) {
  416. if (extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_)) {
  417. UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.EventPageLoadTime2",
  418. load_start_->Elapsed());
  419. } else {
  420. UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.BackgroundPageLoadTime2",
  421. load_start_->Elapsed());
  422. }
  423. } else if (extension_host_type_ == mojom::ViewType::kExtensionPopup) {
  424. UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupLoadTime2",
  425. load_start_->Elapsed());
  426. UMA_HISTOGRAM_MEDIUM_TIMES("Extensions.PopupCreateTime",
  427. create_start_.Elapsed());
  428. }
  429. }
  430. } // namespace extensions