Implement basic mojo Permission service and use it for Geolocation.
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_impl.cc
blob4d497d73d551894b75775c0f5d13af71855521b7
1 // Copyright 2013 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 "content/browser/frame_host/render_frame_host_impl.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/containers/hash_tables.h"
10 #include "base/lazy_instance.h"
11 #include "base/metrics/histogram.h"
12 #include "base/metrics/user_metrics_action.h"
13 #include "base/time/time.h"
14 #include "content/browser/accessibility/accessibility_mode_helper.h"
15 #include "content/browser/accessibility/browser_accessibility_manager.h"
16 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
17 #include "content/browser/child_process_security_policy_impl.h"
18 #include "content/browser/frame_host/cross_process_frame_connector.h"
19 #include "content/browser/frame_host/cross_site_transferring_request.h"
20 #include "content/browser/frame_host/frame_accessibility.h"
21 #include "content/browser/frame_host/frame_tree.h"
22 #include "content/browser/frame_host/frame_tree_node.h"
23 #include "content/browser/frame_host/navigator.h"
24 #include "content/browser/frame_host/render_frame_host_delegate.h"
25 #include "content/browser/frame_host/render_frame_proxy_host.h"
26 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
27 #include "content/browser/geolocation/geolocation_service_context.h"
28 #include "content/browser/permissions/permission_service_context.h"
29 #include "content/browser/permissions/permission_service_impl.h"
30 #include "content/browser/renderer_host/input/input_router.h"
31 #include "content/browser/renderer_host/input/timeout_monitor.h"
32 #include "content/browser/renderer_host/render_process_host_impl.h"
33 #include "content/browser/renderer_host/render_view_host_delegate.h"
34 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
35 #include "content/browser/renderer_host/render_view_host_impl.h"
36 #include "content/browser/renderer_host/render_widget_host_impl.h"
37 #include "content/browser/renderer_host/render_widget_host_view_base.h"
38 #include "content/browser/transition_request_manager.h"
39 #include "content/common/accessibility_messages.h"
40 #include "content/common/desktop_notification_messages.h"
41 #include "content/common/frame_messages.h"
42 #include "content/common/input_messages.h"
43 #include "content/common/inter_process_time_ticks_converter.h"
44 #include "content/common/navigation_params.h"
45 #include "content/common/platform_notification_messages.h"
46 #include "content/common/render_frame_setup.mojom.h"
47 #include "content/common/swapped_out_messages.h"
48 #include "content/public/browser/ax_event_notification_details.h"
49 #include "content/public/browser/browser_accessibility_state.h"
50 #include "content/public/browser/browser_context.h"
51 #include "content/public/browser/browser_plugin_guest_manager.h"
52 #include "content/public/browser/browser_thread.h"
53 #include "content/public/browser/content_browser_client.h"
54 #include "content/public/browser/desktop_notification_delegate.h"
55 #include "content/public/browser/render_process_host.h"
56 #include "content/public/browser/render_widget_host_view.h"
57 #include "content/public/browser/stream_handle.h"
58 #include "content/public/browser/user_metrics.h"
59 #include "content/public/common/content_constants.h"
60 #include "content/public/common/content_switches.h"
61 #include "content/public/common/url_constants.h"
62 #include "content/public/common/url_utils.h"
63 #include "ui/accessibility/ax_tree.h"
64 #include "url/gurl.h"
66 #if defined(OS_MACOSX)
67 #include "content/browser/frame_host/popup_menu_helper_mac.h"
68 #endif
70 using base::TimeDelta;
72 namespace content {
74 namespace {
76 // The next value to use for the accessibility reset token.
77 int g_next_accessibility_reset_token = 1;
79 // The (process id, routing id) pair that identifies one RenderFrame.
80 typedef std::pair<int32, int32> RenderFrameHostID;
81 typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*>
82 RoutingIDFrameMap;
83 base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
84 LAZY_INSTANCE_INITIALIZER;
86 class DesktopNotificationDelegateImpl : public DesktopNotificationDelegate {
87 public:
88 DesktopNotificationDelegateImpl(RenderFrameHost* render_frame_host,
89 int notification_id)
90 : render_process_id_(render_frame_host->GetProcess()->GetID()),
91 render_frame_id_(render_frame_host->GetRoutingID()),
92 notification_id_(notification_id) {}
94 ~DesktopNotificationDelegateImpl() override {}
96 void NotificationDisplayed() override {
97 RenderFrameHost* rfh =
98 RenderFrameHost::FromID(render_process_id_, render_frame_id_);
99 if (!rfh)
100 return;
102 rfh->Send(new DesktopNotificationMsg_PostDisplay(
103 rfh->GetRoutingID(), notification_id_));
106 void NotificationClosed(bool by_user) override {
107 RenderFrameHost* rfh =
108 RenderFrameHost::FromID(render_process_id_, render_frame_id_);
109 if (!rfh)
110 return;
112 rfh->Send(new DesktopNotificationMsg_PostClose(
113 rfh->GetRoutingID(), notification_id_, by_user));
114 static_cast<RenderFrameHostImpl*>(rfh)->NotificationClosed(
115 notification_id_);
118 void NotificationClick() override {
119 RenderFrameHost* rfh =
120 RenderFrameHost::FromID(render_process_id_, render_frame_id_);
121 if (!rfh)
122 return;
124 rfh->Send(new DesktopNotificationMsg_PostClick(
125 rfh->GetRoutingID(), notification_id_));
128 private:
129 int render_process_id_;
130 int render_frame_id_;
131 int notification_id_;
134 // Translate a WebKit text direction into a base::i18n one.
135 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
136 blink::WebTextDirection dir) {
137 switch (dir) {
138 case blink::WebTextDirectionLeftToRight:
139 return base::i18n::LEFT_TO_RIGHT;
140 case blink::WebTextDirectionRightToLeft:
141 return base::i18n::RIGHT_TO_LEFT;
142 default:
143 NOTREACHED();
144 return base::i18n::UNKNOWN_DIRECTION;
148 } // namespace
150 // static
151 bool RenderFrameHostImpl::IsRFHStateActive(RenderFrameHostImplState rfh_state) {
152 return rfh_state == STATE_DEFAULT;
155 // static
156 RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
157 int render_frame_id) {
158 return RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
161 // static
162 RenderFrameHostImpl* RenderFrameHostImpl::FromID(int process_id,
163 int routing_id) {
164 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
165 RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer();
166 RoutingIDFrameMap::iterator it = frames->find(
167 RenderFrameHostID(process_id, routing_id));
168 return it == frames->end() ? NULL : it->second;
171 RenderFrameHostImpl::RenderFrameHostImpl(RenderViewHostImpl* render_view_host,
172 RenderFrameHostDelegate* delegate,
173 FrameTree* frame_tree,
174 FrameTreeNode* frame_tree_node,
175 int routing_id,
176 bool is_swapped_out)
177 : render_view_host_(render_view_host),
178 delegate_(delegate),
179 cross_process_frame_connector_(NULL),
180 render_frame_proxy_host_(NULL),
181 frame_tree_(frame_tree),
182 frame_tree_node_(frame_tree_node),
183 routing_id_(routing_id),
184 render_frame_created_(false),
185 navigations_suspended_(false),
186 is_waiting_for_beforeunload_ack_(false),
187 unload_ack_is_for_cross_site_transition_(false),
188 accessibility_reset_token_(0),
189 accessibility_reset_count_(0),
190 no_create_browser_accessibility_manager_for_testing_(false),
191 weak_ptr_factory_(this) {
192 frame_tree_->RegisterRenderFrameHost(this);
193 GetProcess()->AddRoute(routing_id_, this);
194 g_routing_id_frame_map.Get().insert(std::make_pair(
195 RenderFrameHostID(GetProcess()->GetID(), routing_id_),
196 this));
198 if (is_swapped_out) {
199 rfh_state_ = STATE_SWAPPED_OUT;
200 } else {
201 rfh_state_ = STATE_DEFAULT;
202 GetSiteInstance()->increment_active_frame_count();
205 SetUpMojoIfNeeded();
206 swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
207 &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr())));
210 RenderFrameHostImpl::~RenderFrameHostImpl() {
211 GetProcess()->RemoveRoute(routing_id_);
212 g_routing_id_frame_map.Get().erase(
213 RenderFrameHostID(GetProcess()->GetID(), routing_id_));
215 if (delegate_)
216 delegate_->RenderFrameDeleted(this);
218 FrameAccessibility::GetInstance()->OnRenderFrameHostDestroyed(this);
220 // If this was swapped out, it already decremented the active frame count of
221 // the SiteInstance it belongs to.
222 if (IsRFHStateActive(rfh_state_))
223 GetSiteInstance()->decrement_active_frame_count();
225 // Notify the FrameTree that this RFH is going away, allowing it to shut down
226 // the corresponding RenderViewHost if it is no longer needed.
227 frame_tree_->UnregisterRenderFrameHost(this);
230 int RenderFrameHostImpl::GetRoutingID() {
231 return routing_id_;
234 SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() {
235 return render_view_host_->GetSiteInstance();
238 RenderProcessHost* RenderFrameHostImpl::GetProcess() {
239 // TODO(nasko): This should return its own process, once we have working
240 // cross-process navigation for subframes.
241 return render_view_host_->GetProcess();
244 RenderFrameHost* RenderFrameHostImpl::GetParent() {
245 FrameTreeNode* parent_node = frame_tree_node_->parent();
246 if (!parent_node)
247 return NULL;
248 return parent_node->current_frame_host();
251 const std::string& RenderFrameHostImpl::GetFrameName() {
252 return frame_tree_node_->frame_name();
255 bool RenderFrameHostImpl::IsCrossProcessSubframe() {
256 FrameTreeNode* parent_node = frame_tree_node_->parent();
257 if (!parent_node)
258 return false;
259 return GetSiteInstance() !=
260 parent_node->current_frame_host()->GetSiteInstance();
263 GURL RenderFrameHostImpl::GetLastCommittedURL() {
264 return frame_tree_node_->current_url();
267 gfx::NativeView RenderFrameHostImpl::GetNativeView() {
268 RenderWidgetHostView* view = render_view_host_->GetView();
269 if (!view)
270 return NULL;
271 return view->GetNativeView();
274 void RenderFrameHostImpl::ExecuteJavaScript(
275 const base::string16& javascript) {
276 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
277 javascript,
278 0, false));
281 void RenderFrameHostImpl::ExecuteJavaScript(
282 const base::string16& javascript,
283 const JavaScriptResultCallback& callback) {
284 static int next_id = 1;
285 int key = next_id++;
286 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
287 javascript,
288 key, true));
289 javascript_callbacks_.insert(std::make_pair(key, callback));
292 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
293 const base::string16& javascript) {
294 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
295 javascript,
296 0, false));
299 RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
300 return render_view_host_;
303 ServiceRegistry* RenderFrameHostImpl::GetServiceRegistry() {
304 return service_registry_.get();
307 bool RenderFrameHostImpl::Send(IPC::Message* message) {
308 if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) {
309 return render_view_host_->input_router()->SendInput(
310 make_scoped_ptr(message));
313 // Route IPCs through the RenderFrameProxyHost when in swapped out state.
314 // Note: For subframes in --site-per-process mode, we don't use swapped out
315 // RenderFrameHosts.
316 if (frame_tree_node_->IsMainFrame() && is_swapped_out()) {
317 DCHECK(render_frame_proxy_host_);
318 return render_frame_proxy_host_->Send(message);
321 return GetProcess()->Send(message);
324 bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
325 // Filter out most IPC messages if this frame is swapped out.
326 // We still want to handle certain ACKs to keep our state consistent.
327 if (is_swapped_out()) {
328 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
329 // If this is a synchronous message and we decided not to handle it,
330 // we must send an error reply, or else the renderer will be stuck
331 // and won't respond to future requests.
332 if (msg.is_sync()) {
333 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
334 reply->set_reply_error();
335 Send(reply);
337 // Don't continue looking for someone to handle it.
338 return true;
342 if (delegate_->OnMessageReceived(this, msg))
343 return true;
345 RenderFrameProxyHost* proxy =
346 frame_tree_node_->render_manager()->GetProxyToParent();
347 if (proxy && proxy->cross_process_frame_connector() &&
348 proxy->cross_process_frame_connector()->OnMessageReceived(msg))
349 return true;
351 bool handled = true;
352 IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
353 IPC_MESSAGE_HANDLER(FrameHostMsg_AddMessageToConsole, OnAddMessageToConsole)
354 IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
355 IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
356 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame,
357 OnDidStartProvisionalLoadForFrame)
358 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
359 OnDidFailProvisionalLoadWithError)
360 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
361 OnDidFailLoadWithError)
362 IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad,
363 OnDidCommitProvisionalLoad(msg))
364 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
365 IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
366 OnDocumentOnLoadCompleted)
367 IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
368 IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
369 IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
370 IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
371 OnJavaScriptExecuteResponse)
372 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptMessage,
373 OnRunJavaScriptMessage)
374 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
375 OnRunBeforeUnloadConfirm)
376 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
377 OnDidAccessInitialDocument)
378 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisownOpener, OnDidDisownOpener)
379 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAssignPageId, OnDidAssignPageId)
380 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
381 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateEncoding, OnUpdateEncoding)
382 IPC_MESSAGE_HANDLER(FrameHostMsg_BeginNavigation,
383 OnBeginNavigation)
384 IPC_MESSAGE_HANDLER(PlatformNotificationHostMsg_RequestPermission,
385 OnRequestPlatformNotificationPermission)
386 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Show,
387 OnShowDesktopNotification)
388 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Cancel,
389 OnCancelDesktopNotification)
390 IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
391 OnTextSurroundingSelectionResponse)
392 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
393 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
394 OnAccessibilityLocationChanges)
395 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
396 OnAccessibilityFindInPageResult)
397 #if defined(OS_MACOSX) || defined(OS_ANDROID)
398 IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
399 IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
400 #endif
401 IPC_END_MESSAGE_MAP()
403 // No further actions here, since we may have been deleted.
404 return handled;
407 void RenderFrameHostImpl::AccessibilitySetFocus(int object_id) {
408 Send(new AccessibilityMsg_SetFocus(routing_id_, object_id));
411 void RenderFrameHostImpl::AccessibilityDoDefaultAction(int object_id) {
412 Send(new AccessibilityMsg_DoDefaultAction(routing_id_, object_id));
415 void RenderFrameHostImpl::AccessibilityShowMenu(
416 const gfx::Point& global_point) {
417 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
418 render_view_host_->GetView());
419 if (view)
420 view->AccessibilityShowMenu(global_point);
423 void RenderFrameHostImpl::AccessibilityScrollToMakeVisible(
424 int acc_obj_id, const gfx::Rect& subfocus) {
425 Send(new AccessibilityMsg_ScrollToMakeVisible(
426 routing_id_, acc_obj_id, subfocus));
429 void RenderFrameHostImpl::AccessibilityScrollToPoint(
430 int acc_obj_id, const gfx::Point& point) {
431 Send(new AccessibilityMsg_ScrollToPoint(
432 routing_id_, acc_obj_id, point));
435 void RenderFrameHostImpl::AccessibilitySetTextSelection(
436 int object_id, int start_offset, int end_offset) {
437 Send(new AccessibilityMsg_SetTextSelection(
438 routing_id_, object_id, start_offset, end_offset));
441 void RenderFrameHostImpl::AccessibilitySetValue(
442 int object_id, const base::string16& value) {
443 Send(new AccessibilityMsg_SetValue(routing_id_, object_id, value));
446 bool RenderFrameHostImpl::AccessibilityViewHasFocus() const {
447 RenderWidgetHostView* view = render_view_host_->GetView();
448 if (view)
449 return view->HasFocus();
450 return false;
453 gfx::Rect RenderFrameHostImpl::AccessibilityGetViewBounds() const {
454 RenderWidgetHostView* view = render_view_host_->GetView();
455 if (view)
456 return view->GetViewBounds();
457 return gfx::Rect();
460 gfx::Point RenderFrameHostImpl::AccessibilityOriginInScreen(
461 const gfx::Rect& bounds) const {
462 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
463 render_view_host_->GetView());
464 if (view)
465 return view->AccessibilityOriginInScreen(bounds);
466 return gfx::Point();
469 void RenderFrameHostImpl::AccessibilityHitTest(const gfx::Point& point) {
470 Send(new AccessibilityMsg_HitTest(routing_id_, point));
473 void RenderFrameHostImpl::AccessibilityFatalError() {
474 browser_accessibility_manager_.reset(NULL);
475 if (accessibility_reset_token_)
476 return;
478 accessibility_reset_count_++;
479 if (accessibility_reset_count_ >= kMaxAccessibilityResets) {
480 Send(new AccessibilityMsg_FatalError(routing_id_));
481 } else {
482 accessibility_reset_token_ = g_next_accessibility_reset_token++;
483 UMA_HISTOGRAM_COUNTS("Accessibility.FrameResetCount", 1);
484 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
488 gfx::AcceleratedWidget
489 RenderFrameHostImpl::AccessibilityGetAcceleratedWidget() {
490 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
491 render_view_host_->GetView());
492 if (view)
493 return view->AccessibilityGetAcceleratedWidget();
494 return gfx::kNullAcceleratedWidget;
497 gfx::NativeViewAccessible
498 RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() {
499 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
500 render_view_host_->GetView());
501 if (view)
502 return view->AccessibilityGetNativeViewAccessible();
503 return NULL;
506 BrowserAccessibilityManager* RenderFrameHostImpl::AccessibilityGetChildFrame(
507 int accessibility_node_id) {
508 RenderFrameHostImpl* child_frame =
509 FrameAccessibility::GetInstance()->GetChild(this, accessibility_node_id);
510 if (!child_frame)
511 return NULL;
513 // Return NULL if this isn't an out-of-process iframe. Same-process iframes
514 // are already part of the accessibility tree.
515 if (child_frame->GetProcess()->GetID() == GetProcess()->GetID())
516 return NULL;
518 // As a sanity check, make sure the frame we're going to return belongs
519 // to the same BrowserContext.
520 if (GetSiteInstance()->GetBrowserContext() !=
521 child_frame->GetSiteInstance()->GetBrowserContext()) {
522 NOTREACHED();
523 return NULL;
526 return child_frame->GetOrCreateBrowserAccessibilityManager();
529 BrowserAccessibility* RenderFrameHostImpl::AccessibilityGetParentFrame() {
530 RenderFrameHostImpl* parent_frame = NULL;
531 int parent_node_id = 0;
532 if (!FrameAccessibility::GetInstance()->GetParent(
533 this, &parent_frame, &parent_node_id)) {
534 return NULL;
537 // As a sanity check, make sure the frame we're going to return belongs
538 // to the same BrowserContext.
539 if (GetSiteInstance()->GetBrowserContext() !=
540 parent_frame->GetSiteInstance()->GetBrowserContext()) {
541 NOTREACHED();
542 return NULL;
545 BrowserAccessibilityManager* manager =
546 parent_frame->browser_accessibility_manager();
547 if (!manager)
548 return NULL;
550 return manager->GetFromID(parent_node_id);
553 bool RenderFrameHostImpl::CreateRenderFrame(int parent_routing_id,
554 int proxy_routing_id) {
555 TRACE_EVENT0("navigation", "RenderFrameHostImpl::CreateRenderFrame");
556 DCHECK(!IsRenderFrameLive()) << "Creating frame twice";
558 // The process may (if we're sharing a process with another host that already
559 // initialized it) or may not (we have our own process or the old process
560 // crashed) have been initialized. Calling Init multiple times will be
561 // ignored, so this is safe.
562 if (!GetProcess()->Init())
563 return false;
565 DCHECK(GetProcess()->HasConnection());
567 Send(new FrameMsg_NewFrame(routing_id_, parent_routing_id, proxy_routing_id));
569 // The renderer now has a RenderFrame for this RenderFrameHost. Note that
570 // this path is only used for out-of-process iframes. Main frame RenderFrames
571 // are created with their RenderView, and same-site iframes are created at the
572 // time of OnCreateChildFrame.
573 set_render_frame_created(true);
575 return true;
578 bool RenderFrameHostImpl::IsRenderFrameLive() {
579 // RenderFrames are created for main frames at the same time as RenderViews,
580 // so we rely on IsRenderViewLive. For subframes, we keep track of each
581 // RenderFrame individually with render_frame_created_.
582 bool is_live = !GetParent() ?
583 render_view_host_->IsRenderViewLive() :
584 GetProcess()->HasConnection() && render_frame_created_;
586 // Sanity check: the RenderView should always be live if the RenderFrame is.
587 DCHECK(!is_live || render_view_host_->IsRenderViewLive());
589 return is_live;
592 void RenderFrameHostImpl::Init() {
593 GetProcess()->ResumeRequestsForView(routing_id_);
596 void RenderFrameHostImpl::OnAddMessageToConsole(
597 int32 level,
598 const base::string16& message,
599 int32 line_no,
600 const base::string16& source_id) {
601 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
602 return;
604 // Pass through log level only on WebUI pages to limit console spew.
605 int32 resolved_level =
606 HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) ? level : 0;
608 if (resolved_level >= ::logging::GetMinLogLevel()) {
609 logging::LogMessage("CONSOLE", line_no, resolved_level).stream() << "\"" <<
610 message << "\", source: " << source_id << " (" << line_no << ")";
614 void RenderFrameHostImpl::OnCreateChildFrame(int new_routing_id,
615 const std::string& frame_name) {
616 // It is possible that while a new RenderFrameHost was committed, the
617 // RenderFrame corresponding to this host sent an IPC message to create a
618 // frame and it is delivered after this host is swapped out.
619 // Ignore such messages, as we know this RenderFrameHost is going away.
620 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT)
621 return;
623 RenderFrameHostImpl* new_frame = frame_tree_->AddFrame(
624 frame_tree_node_, GetProcess()->GetID(), new_routing_id, frame_name);
625 if (!new_frame)
626 return;
628 // We know that the RenderFrame has been created in this case, immediately
629 // after the CreateChildFrame IPC was sent.
630 new_frame->set_render_frame_created(true);
632 if (delegate_)
633 delegate_->RenderFrameCreated(new_frame);
636 void RenderFrameHostImpl::OnDetach() {
637 frame_tree_->RemoveFrame(frame_tree_node_);
640 void RenderFrameHostImpl::OnFrameFocused() {
641 frame_tree_->SetFocusedFrame(frame_tree_node_);
644 void RenderFrameHostImpl::OnOpenURL(
645 const FrameHostMsg_OpenURL_Params& params) {
646 GURL validated_url(params.url);
647 GetProcess()->FilterURL(false, &validated_url);
649 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnOpenURL",
650 "url", validated_url.possibly_invalid_spec());
651 frame_tree_node_->navigator()->RequestOpenURL(
652 this, validated_url, params.referrer, params.disposition,
653 params.should_replace_current_entry, params.user_gesture);
656 void RenderFrameHostImpl::OnDocumentOnLoadCompleted() {
657 // This message is only sent for top-level frames. TODO(avi): when frame tree
658 // mirroring works correctly, add a check here to enforce it.
659 delegate_->DocumentOnLoadCompleted(this);
662 void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame(
663 const GURL& url,
664 bool is_transition_navigation) {
665 frame_tree_node_->navigator()->DidStartProvisionalLoad(
666 this, url, is_transition_navigation);
669 void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError(
670 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
671 frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params);
674 void RenderFrameHostImpl::OnDidFailLoadWithError(
675 const GURL& url,
676 int error_code,
677 const base::string16& error_description) {
678 GURL validated_url(url);
679 GetProcess()->FilterURL(false, &validated_url);
681 frame_tree_node_->navigator()->DidFailLoadWithError(
682 this, validated_url, error_code, error_description);
685 // Called when the renderer navigates. For every frame loaded, we'll get this
686 // notification containing parameters identifying the navigation.
688 // Subframes are identified by the page transition type. For subframes loaded
689 // as part of a wider page load, the page_id will be the same as for the top
690 // level frame. If the user explicitly requests a subframe navigation, we will
691 // get a new page_id because we need to create a new navigation entry for that
692 // action.
693 void RenderFrameHostImpl::OnDidCommitProvisionalLoad(const IPC::Message& msg) {
694 // Read the parameters out of the IPC message directly to avoid making another
695 // copy when we filter the URLs.
696 PickleIterator iter(msg);
697 FrameHostMsg_DidCommitProvisionalLoad_Params validated_params;
698 if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>::
699 Read(&msg, &iter, &validated_params))
700 return;
701 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnDidCommitProvisionalLoad",
702 "url", validated_params.url.possibly_invalid_spec());
704 // If we're waiting for a cross-site beforeunload ack from this renderer and
705 // we receive a Navigate message from the main frame, then the renderer was
706 // navigating already and sent it before hearing the FrameMsg_Stop message.
707 // We do not want to cancel the pending navigation in this case, since the
708 // old page will soon be stopped. Instead, treat this as a beforeunload ack
709 // to allow the pending navigation to continue.
710 if (is_waiting_for_beforeunload_ack_ &&
711 unload_ack_is_for_cross_site_transition_ &&
712 ui::PageTransitionIsMainFrame(validated_params.transition)) {
713 base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_;
714 OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now());
715 return;
718 // If we're waiting for an unload ack from this renderer and we receive a
719 // Navigate message, then the renderer was navigating before it received the
720 // unload request. It will either respond to the unload request soon or our
721 // timer will expire. Either way, we should ignore this message, because we
722 // have already committed to closing this renderer.
723 if (IsWaitingForUnloadACK())
724 return;
726 RenderProcessHost* process = GetProcess();
728 // Attempts to commit certain off-limits URL should be caught more strictly
729 // than our FilterURL checks below. If a renderer violates this policy, it
730 // should be killed.
731 if (!CanCommitURL(validated_params.url)) {
732 VLOG(1) << "Blocked URL " << validated_params.url.spec();
733 validated_params.url = GURL(url::kAboutBlankURL);
734 RecordAction(base::UserMetricsAction("CanCommitURL_BlockedAndKilled"));
735 // Kills the process.
736 process->ReceivedBadMessage();
739 // Without this check, an evil renderer can trick the browser into creating
740 // a navigation entry for a banned URL. If the user clicks the back button
741 // followed by the forward button (or clicks reload, or round-trips through
742 // session restore, etc), we'll think that the browser commanded the
743 // renderer to load the URL and grant the renderer the privileges to request
744 // the URL. To prevent this attack, we block the renderer from inserting
745 // banned URLs into the navigation controller in the first place.
746 process->FilterURL(false, &validated_params.url);
747 process->FilterURL(true, &validated_params.referrer.url);
748 for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
749 it != validated_params.redirects.end(); ++it) {
750 process->FilterURL(false, &(*it));
752 process->FilterURL(true, &validated_params.searchable_form_url);
754 // Without this check, the renderer can trick the browser into using
755 // filenames it can't access in a future session restore.
756 if (!render_view_host_->CanAccessFilesOfPageState(
757 validated_params.page_state)) {
758 GetProcess()->ReceivedBadMessage();
759 return;
762 accessibility_reset_count_ = 0;
763 frame_tree_node()->navigator()->DidNavigate(this, validated_params);
766 RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
767 return static_cast<RenderWidgetHostImpl*>(render_view_host_);
770 int RenderFrameHostImpl::GetEnabledBindings() {
771 return render_view_host_->GetEnabledBindings();
774 void RenderFrameHostImpl::OnCrossSiteResponse(
775 const GlobalRequestID& global_request_id,
776 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
777 const std::vector<GURL>& transfer_url_chain,
778 const Referrer& referrer,
779 ui::PageTransition page_transition,
780 bool should_replace_current_entry) {
781 frame_tree_node_->render_manager()->OnCrossSiteResponse(
782 this, global_request_id, cross_site_transferring_request.Pass(),
783 transfer_url_chain, referrer, page_transition,
784 should_replace_current_entry);
787 void RenderFrameHostImpl::OnDeferredAfterResponseStarted(
788 const GlobalRequestID& global_request_id,
789 const TransitionLayerData& transition_data) {
790 frame_tree_node_->render_manager()->OnDeferredAfterResponseStarted(
791 global_request_id, this);
793 if (GetParent() || !delegate_->WillHandleDeferAfterResponseStarted())
794 frame_tree_node_->render_manager()->ResumeResponseDeferredAtStart();
795 else
796 delegate_->DidDeferAfterResponseStarted(transition_data);
799 void RenderFrameHostImpl::SwapOut(RenderFrameProxyHost* proxy) {
800 // The end of this event is in OnSwapOutACK when the RenderFrame has completed
801 // the operation and sends back an IPC message.
802 // The trace event may not end properly if the ACK times out. We expect this
803 // to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost.
804 TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl::SwapOut", this);
806 // If this RenderFrameHost is not in the default state, it must have already
807 // gone through this, therefore just return.
808 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) {
809 NOTREACHED() << "RFH should be in default state when calling SwapOut.";
810 return;
813 SetState(RenderFrameHostImpl::STATE_PENDING_SWAP_OUT);
814 swapout_event_monitor_timeout_->Start(
815 base::TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
817 // There may be no proxy if there are no active views in the process.
818 int proxy_routing_id = MSG_ROUTING_NONE;
819 if (proxy) {
820 set_render_frame_proxy_host(proxy);
821 proxy_routing_id = proxy->GetRoutingID();
824 if (IsRenderFrameLive())
825 Send(new FrameMsg_SwapOut(routing_id_, proxy_routing_id));
827 if (!GetParent())
828 delegate_->SwappedOut(this);
831 void RenderFrameHostImpl::OnBeforeUnloadACK(
832 bool proceed,
833 const base::TimeTicks& renderer_before_unload_start_time,
834 const base::TimeTicks& renderer_before_unload_end_time) {
835 TRACE_EVENT_ASYNC_END0(
836 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
837 DCHECK(!GetParent());
838 render_view_host_->decrement_in_flight_event_count();
839 render_view_host_->StopHangMonitorTimeout();
840 // If this renderer navigated while the beforeunload request was in flight, we
841 // may have cleared this state in OnDidCommitProvisionalLoad, in which case we
842 // can ignore this message.
843 // However renderer might also be swapped out but we still want to proceed
844 // with navigation, otherwise it would block future navigations. This can
845 // happen when pending cross-site navigation is canceled by a second one just
846 // before OnDidCommitProvisionalLoad while current RVH is waiting for commit
847 // but second navigation is started from the beginning.
848 if (!is_waiting_for_beforeunload_ack_) {
849 return;
851 DCHECK(!send_before_unload_start_time_.is_null());
853 // Sets a default value for before_unload_end_time so that the browser
854 // survives a hacked renderer.
855 base::TimeTicks before_unload_end_time = renderer_before_unload_end_time;
856 if (!renderer_before_unload_start_time.is_null() &&
857 !renderer_before_unload_end_time.is_null()) {
858 // When passing TimeTicks across process boundaries, we need to compensate
859 // for any skew between the processes. Here we are converting the
860 // renderer's notion of before_unload_end_time to TimeTicks in the browser
861 // process. See comments in inter_process_time_ticks_converter.h for more.
862 base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now();
863 InterProcessTimeTicksConverter converter(
864 LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
865 LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time),
866 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
867 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
868 LocalTimeTicks browser_before_unload_end_time =
869 converter.ToLocalTimeTicks(
870 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
871 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
873 // Collect UMA on the inter-process skew.
874 bool is_skew_additive = false;
875 if (converter.IsSkewAdditiveForMetrics()) {
876 is_skew_additive = true;
877 base::TimeDelta skew = converter.GetSkewForMetrics();
878 if (skew >= base::TimeDelta()) {
879 UMA_HISTOGRAM_TIMES(
880 "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew);
881 } else {
882 UMA_HISTOGRAM_TIMES(
883 "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew);
886 UMA_HISTOGRAM_BOOLEAN(
887 "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser",
888 is_skew_additive);
890 base::TimeDelta on_before_unload_overhead_time =
891 (receive_before_unload_ack_time - send_before_unload_start_time_) -
892 (renderer_before_unload_end_time - renderer_before_unload_start_time);
893 UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime",
894 on_before_unload_overhead_time);
896 frame_tree_node_->navigator()->LogBeforeUnloadTime(
897 renderer_before_unload_start_time, renderer_before_unload_end_time);
899 // Resets beforeunload waiting state.
900 is_waiting_for_beforeunload_ack_ = false;
901 send_before_unload_start_time_ = base::TimeTicks();
903 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
904 unload_ack_is_for_cross_site_transition_, proceed,
905 before_unload_end_time);
907 // If canceled, notify the delegate to cancel its pending navigation entry.
908 if (!proceed)
909 render_view_host_->GetDelegate()->DidCancelLoading();
912 bool RenderFrameHostImpl::IsWaitingForUnloadACK() const {
913 return render_view_host_->is_waiting_for_close_ack_ ||
914 rfh_state_ == STATE_PENDING_SWAP_OUT;
917 void RenderFrameHostImpl::OnSwapOutACK() {
918 OnSwappedOut();
921 void RenderFrameHostImpl::OnSwappedOut() {
922 // Ignore spurious swap out ack.
923 if (rfh_state_ != STATE_PENDING_SWAP_OUT)
924 return;
926 TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
927 swapout_event_monitor_timeout_->Stop();
929 if (frame_tree_node_->render_manager()->DeleteFromPendingList(this)) {
930 // We are now deleted.
931 return;
934 // If this RFH wasn't pending deletion, then it is now swapped out.
935 SetState(RenderFrameHostImpl::STATE_SWAPPED_OUT);
938 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
939 // Validate the URLs in |params|. If the renderer can't request the URLs
940 // directly, don't show them in the context menu.
941 ContextMenuParams validated_params(params);
942 RenderProcessHost* process = GetProcess();
944 // We don't validate |unfiltered_link_url| so that this field can be used
945 // when users want to copy the original link URL.
946 process->FilterURL(true, &validated_params.link_url);
947 process->FilterURL(true, &validated_params.src_url);
948 process->FilterURL(false, &validated_params.page_url);
949 process->FilterURL(true, &validated_params.frame_url);
951 delegate_->ShowContextMenu(this, validated_params);
954 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
955 int id, const base::ListValue& result) {
956 const base::Value* result_value;
957 if (!result.Get(0, &result_value)) {
958 // Programming error or rogue renderer.
959 NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
960 return;
963 std::map<int, JavaScriptResultCallback>::iterator it =
964 javascript_callbacks_.find(id);
965 if (it != javascript_callbacks_.end()) {
966 it->second.Run(result_value);
967 javascript_callbacks_.erase(it);
968 } else {
969 NOTREACHED() << "Received script response for unknown request";
973 void RenderFrameHostImpl::OnRunJavaScriptMessage(
974 const base::string16& message,
975 const base::string16& default_prompt,
976 const GURL& frame_url,
977 JavaScriptMessageType type,
978 IPC::Message* reply_msg) {
979 // While a JS message dialog is showing, tabs in the same process shouldn't
980 // process input events.
981 GetProcess()->SetIgnoreInputEvents(true);
982 render_view_host_->StopHangMonitorTimeout();
983 delegate_->RunJavaScriptMessage(this, message, default_prompt,
984 frame_url, type, reply_msg);
987 void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
988 const GURL& frame_url,
989 const base::string16& message,
990 bool is_reload,
991 IPC::Message* reply_msg) {
992 // While a JS beforeunload dialog is showing, tabs in the same process
993 // shouldn't process input events.
994 GetProcess()->SetIgnoreInputEvents(true);
995 render_view_host_->StopHangMonitorTimeout();
996 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
999 void RenderFrameHostImpl::OnRequestPlatformNotificationPermission(
1000 const GURL& origin, int request_id) {
1001 base::Callback<void(bool)> done_callback = base::Bind(
1002 &RenderFrameHostImpl::PlatformNotificationPermissionRequestDone,
1003 weak_ptr_factory_.GetWeakPtr(),
1004 request_id);
1006 if (!delegate()->GetAsWebContents())
1007 return;
1009 // TODO(peter): plumb user_gesture and bridge_id.
1010 GetContentClient()->browser()->RequestPermission(
1011 content::PERMISSION_NOTIFICATIONS,
1012 delegate()->GetAsWebContents(),
1013 routing_id_,
1014 origin,
1015 true, // user_gesture,
1016 done_callback);
1019 void RenderFrameHostImpl::OnShowDesktopNotification(
1020 int notification_id,
1021 const ShowDesktopNotificationHostMsgParams& params) {
1022 scoped_ptr<DesktopNotificationDelegateImpl> delegate(
1023 new DesktopNotificationDelegateImpl(this, notification_id));
1025 base::Closure cancel_callback;
1026 GetContentClient()->browser()->ShowDesktopNotification(
1027 params,
1028 GetSiteInstance()->GetBrowserContext(),
1029 GetProcess()->GetID(),
1030 delegate.Pass(),
1031 &cancel_callback);
1033 cancel_notification_callbacks_[notification_id] = cancel_callback;
1036 void RenderFrameHostImpl::OnCancelDesktopNotification(int notification_id) {
1037 if (!cancel_notification_callbacks_.count(notification_id))
1038 return;
1040 cancel_notification_callbacks_[notification_id].Run();
1041 cancel_notification_callbacks_.erase(notification_id);
1044 void RenderFrameHostImpl::OnTextSurroundingSelectionResponse(
1045 const base::string16& content,
1046 size_t start_offset,
1047 size_t end_offset) {
1048 render_view_host_->OnTextSurroundingSelectionResponse(
1049 content, start_offset, end_offset);
1052 void RenderFrameHostImpl::OnDidAccessInitialDocument() {
1053 delegate_->DidAccessInitialDocument();
1056 void RenderFrameHostImpl::OnDidDisownOpener() {
1057 // This message is only sent for top-level frames. TODO(avi): when frame tree
1058 // mirroring works correctly, add a check here to enforce it.
1059 delegate_->DidDisownOpener(this);
1062 void RenderFrameHostImpl::OnDidAssignPageId(int32 page_id) {
1063 // Update the RVH's current page ID so that future IPCs from the renderer
1064 // correspond to the new page.
1065 render_view_host_->page_id_ = page_id;
1068 void RenderFrameHostImpl::OnUpdateTitle(
1069 const base::string16& title,
1070 blink::WebTextDirection title_direction) {
1071 // This message is only sent for top-level frames. TODO(avi): when frame tree
1072 // mirroring works correctly, add a check here to enforce it.
1073 if (title.length() > kMaxTitleChars) {
1074 NOTREACHED() << "Renderer sent too many characters in title.";
1075 return;
1078 delegate_->UpdateTitle(this, render_view_host_->page_id_, title,
1079 WebTextDirectionToChromeTextDirection(
1080 title_direction));
1083 void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
1084 // This message is only sent for top-level frames. TODO(avi): when frame tree
1085 // mirroring works correctly, add a check here to enforce it.
1086 delegate_->UpdateEncoding(this, encoding_name);
1089 void RenderFrameHostImpl::OnBeginNavigation(
1090 const FrameHostMsg_BeginNavigation_Params& params,
1091 const CommonNavigationParams& common_params) {
1092 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
1093 switches::kEnableBrowserSideNavigation));
1094 frame_tree_node()->navigator()->OnBeginNavigation(
1095 frame_tree_node(), params, common_params);
1098 void RenderFrameHostImpl::OnAccessibilityEvents(
1099 const std::vector<AccessibilityHostMsg_EventParams>& params,
1100 int reset_token) {
1101 // Don't process this IPC if either we're waiting on a reset and this
1102 // IPC doesn't have the matching token ID, or if we're not waiting on a
1103 // reset but this message includes a reset token.
1104 if (accessibility_reset_token_ != reset_token) {
1105 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1106 return;
1108 accessibility_reset_token_ = 0;
1110 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1111 render_view_host_->GetView());
1113 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1114 if ((accessibility_mode != AccessibilityModeOff) && view &&
1115 RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1116 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1117 GetOrCreateBrowserAccessibilityManager();
1118 if (browser_accessibility_manager_)
1119 browser_accessibility_manager_->OnAccessibilityEvents(params);
1122 if (browser_accessibility_manager_) {
1123 // Get the frame routing ids from out-of-process iframes and
1124 // browser plugin instance ids from guests and update the mappings in
1125 // FrameAccessibility.
1126 for (size_t i = 0; i < params.size(); ++i) {
1127 const AccessibilityHostMsg_EventParams& param = params[i];
1128 UpdateCrossProcessIframeAccessibility(
1129 param.node_to_frame_routing_id_map);
1130 UpdateGuestFrameAccessibility(
1131 param.node_to_browser_plugin_instance_id_map);
1135 // Send the updates to the automation extension API.
1136 std::vector<AXEventNotificationDetails> details;
1137 details.reserve(params.size());
1138 for (size_t i = 0; i < params.size(); ++i) {
1139 const AccessibilityHostMsg_EventParams& param = params[i];
1140 AXEventNotificationDetails detail(param.update.node_id_to_clear,
1141 param.update.nodes,
1142 param.event_type,
1143 param.id,
1144 GetProcess()->GetID(),
1145 routing_id_);
1146 details.push_back(detail);
1149 delegate_->AccessibilityEventReceived(details);
1152 // Always send an ACK or the renderer can be in a bad state.
1153 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1155 // The rest of this code is just for testing; bail out if we're not
1156 // in that mode.
1157 if (accessibility_testing_callback_.is_null())
1158 return;
1160 for (size_t i = 0; i < params.size(); i++) {
1161 const AccessibilityHostMsg_EventParams& param = params[i];
1162 if (static_cast<int>(param.event_type) < 0)
1163 continue;
1165 if (!ax_tree_for_testing_) {
1166 if (browser_accessibility_manager_) {
1167 ax_tree_for_testing_.reset(new ui::AXTree(
1168 browser_accessibility_manager_->SnapshotAXTreeForTesting()));
1169 } else {
1170 ax_tree_for_testing_.reset(new ui::AXTree());
1171 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1172 << ax_tree_for_testing_->error();
1174 } else {
1175 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1176 << ax_tree_for_testing_->error();
1178 accessibility_testing_callback_.Run(param.event_type, param.id);
1182 void RenderFrameHostImpl::OnAccessibilityLocationChanges(
1183 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1184 if (accessibility_reset_token_)
1185 return;
1187 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1188 render_view_host_->GetView());
1189 if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1190 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1191 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1192 BrowserAccessibilityManager* manager =
1193 GetOrCreateBrowserAccessibilityManager();
1194 if (manager)
1195 manager->OnLocationChanges(params);
1197 // TODO(aboxhall): send location change events to web contents observers too
1201 void RenderFrameHostImpl::OnAccessibilityFindInPageResult(
1202 const AccessibilityHostMsg_FindInPageResultParams& params) {
1203 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1204 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1205 BrowserAccessibilityManager* manager =
1206 GetOrCreateBrowserAccessibilityManager();
1207 if (manager) {
1208 manager->OnFindInPageResult(
1209 params.request_id, params.match_index, params.start_id,
1210 params.start_offset, params.end_id, params.end_offset);
1215 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1216 void RenderFrameHostImpl::OnShowPopup(
1217 const FrameHostMsg_ShowPopup_Params& params) {
1218 RenderViewHostDelegateView* view =
1219 render_view_host_->delegate_->GetDelegateView();
1220 if (view) {
1221 view->ShowPopupMenu(this,
1222 params.bounds,
1223 params.item_height,
1224 params.item_font_size,
1225 params.selected_item,
1226 params.popup_items,
1227 params.right_aligned,
1228 params.allow_multiple_selection);
1232 void RenderFrameHostImpl::OnHidePopup() {
1233 RenderViewHostDelegateView* view =
1234 render_view_host_->delegate_->GetDelegateView();
1235 if (view)
1236 view->HidePopupMenu();
1238 #endif
1240 void RenderFrameHostImpl::RegisterMojoServices() {
1241 GeolocationServiceContext* geolocation_service_context =
1242 delegate_ ? delegate_->GetGeolocationServiceContext() : NULL;
1243 if (geolocation_service_context) {
1244 // TODO(creis): Bind process ID here so that GeolocationServiceImpl
1245 // can perform permissions checks once site isolation is complete.
1246 // crbug.com/426384
1247 GetServiceRegistry()->AddService<GeolocationService>(
1248 base::Bind(&GeolocationServiceContext::CreateService,
1249 base::Unretained(geolocation_service_context),
1250 base::Bind(&RenderFrameHostImpl::DidUseGeolocationPermission,
1251 base::Unretained(this))));
1254 if (!permission_service_context_)
1255 permission_service_context_.reset(new PermissionServiceContext(this));
1257 GetServiceRegistry()->AddService<PermissionService>(
1258 base::Bind(&PermissionServiceContext::CreateService,
1259 base::Unretained(permission_service_context_.get())));
1262 void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) {
1263 // Only main frames should be swapped out and retained inside a proxy host.
1264 if (rfh_state == STATE_SWAPPED_OUT)
1265 CHECK(!GetParent());
1267 // We update the number of RenderFrameHosts in a SiteInstance when the swapped
1268 // out status of a RenderFrameHost gets flipped to/from active.
1269 if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state))
1270 GetSiteInstance()->increment_active_frame_count();
1271 else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state))
1272 GetSiteInstance()->decrement_active_frame_count();
1274 // The active and swapped out state of the RVH is determined by its main
1275 // frame, since subframes should have their own widgets.
1276 if (frame_tree_node_->IsMainFrame()) {
1277 render_view_host_->set_is_active(IsRFHStateActive(rfh_state));
1278 render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT);
1281 // Whenever we change the RFH state to and from active or swapped out state,
1282 // we should not be waiting for beforeunload or close acks. We clear them
1283 // here to be safe, since they can cause navigations to be ignored in
1284 // OnDidCommitProvisionalLoad.
1285 // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine.
1286 if (rfh_state == STATE_DEFAULT ||
1287 rfh_state == STATE_SWAPPED_OUT ||
1288 rfh_state_ == STATE_DEFAULT ||
1289 rfh_state_ == STATE_SWAPPED_OUT) {
1290 is_waiting_for_beforeunload_ack_ = false;
1291 send_before_unload_start_time_ = base::TimeTicks();
1292 render_view_host_->is_waiting_for_close_ack_ = false;
1294 rfh_state_ = rfh_state;
1297 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
1298 // TODO(creis): We should also check for WebUI pages here. Also, when the
1299 // out-of-process iframes implementation is ready, we should check for
1300 // cross-site URLs that are not allowed to commit in this process.
1302 // Give the client a chance to disallow URLs from committing.
1303 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1306 void RenderFrameHostImpl::Navigate(const FrameMsg_Navigate_Params& params) {
1307 TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate");
1308 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
1309 // so do not grant them the ability to request additional URLs.
1310 if (!GetProcess()->IsIsolatedGuest()) {
1311 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
1312 GetProcess()->GetID(), params.common_params.url);
1313 if (params.common_params.url.SchemeIs(url::kDataScheme) &&
1314 params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
1315 // If 'data:' is used, and we have a 'file:' base url, grant access to
1316 // local files.
1317 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
1318 GetProcess()->GetID(), params.base_url_for_data_url);
1322 // Only send the message if we aren't suspended at the start of a cross-site
1323 // request.
1324 if (navigations_suspended_) {
1325 // Shouldn't be possible to have a second navigation while suspended, since
1326 // navigations will only be suspended during a cross-site request. If a
1327 // second navigation occurs, RenderFrameHostManager will cancel this pending
1328 // RFH and create a new pending RFH.
1329 DCHECK(!suspended_nav_params_.get());
1330 suspended_nav_params_.reset(new FrameMsg_Navigate_Params(params));
1331 } else {
1332 // Get back to a clean state, in case we start a new navigation without
1333 // completing a RFH swap or unload handler.
1334 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1336 Send(new FrameMsg_Navigate(routing_id_, params));
1339 // Force the throbber to start. We do this because Blink's "started
1340 // loading" message will be received asynchronously from the UI of the
1341 // browser. But we want to keep the throbber in sync with what's happening
1342 // in the UI. For example, we want to start throbbing immediately when the
1343 // user naivgates even if the renderer is delayed. There is also an issue
1344 // with the throbber starting because the WebUI (which controls whether the
1345 // favicon is displayed) happens synchronously. If the start loading
1346 // messages was asynchronous, then the default favicon would flash in.
1348 // Blink doesn't send throb notifications for JavaScript URLs, so we
1349 // don't want to either.
1350 if (!params.common_params.url.SchemeIs(url::kJavaScriptScheme))
1351 delegate_->DidStartLoading(this, true);
1354 void RenderFrameHostImpl::NavigateToURL(const GURL& url) {
1355 FrameMsg_Navigate_Params params;
1356 params.common_params.url = url;
1357 params.common_params.transition = ui::PAGE_TRANSITION_LINK;
1358 params.common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL;
1359 params.commit_params.browser_navigation_start = base::TimeTicks::Now();
1360 params.page_id = -1;
1361 params.pending_history_list_offset = -1;
1362 params.current_history_list_offset = -1;
1363 params.current_history_list_length = 0;
1364 Navigate(params);
1367 void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params) {
1368 OnOpenURL(params);
1371 void RenderFrameHostImpl::Stop() {
1372 Send(new FrameMsg_Stop(routing_id_));
1375 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
1376 // TODO(creis): Support beforeunload on subframes. For now just pretend that
1377 // the handler ran and allowed the navigation to proceed.
1378 if (GetParent() || !IsRenderFrameLive()) {
1379 // We don't have a live renderer, so just skip running beforeunload.
1380 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1381 for_cross_site_transition, true, base::TimeTicks::Now());
1382 return;
1384 TRACE_EVENT_ASYNC_BEGIN0(
1385 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1387 // This may be called more than once (if the user clicks the tab close button
1388 // several times, or if she clicks the tab close button then the browser close
1389 // button), and we only send the message once.
1390 if (is_waiting_for_beforeunload_ack_) {
1391 // Some of our close messages could be for the tab, others for cross-site
1392 // transitions. We always want to think it's for closing the tab if any
1393 // of the messages were, since otherwise it might be impossible to close
1394 // (if there was a cross-site "close" request pending when the user clicked
1395 // the close button). We want to keep the "for cross site" flag only if
1396 // both the old and the new ones are also for cross site.
1397 unload_ack_is_for_cross_site_transition_ =
1398 unload_ack_is_for_cross_site_transition_ && for_cross_site_transition;
1399 } else {
1400 // Start the hang monitor in case the renderer hangs in the beforeunload
1401 // handler.
1402 is_waiting_for_beforeunload_ack_ = true;
1403 unload_ack_is_for_cross_site_transition_ = for_cross_site_transition;
1404 // Increment the in-flight event count, to ensure that input events won't
1405 // cancel the timeout timer.
1406 render_view_host_->increment_in_flight_event_count();
1407 render_view_host_->StartHangMonitorTimeout(
1408 TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1409 send_before_unload_start_time_ = base::TimeTicks::Now();
1410 Send(new FrameMsg_BeforeUnload(routing_id_));
1414 void RenderFrameHostImpl::DisownOpener() {
1415 Send(new FrameMsg_DisownOpener(GetRoutingID()));
1418 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
1419 size_t after) {
1420 Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after));
1423 void RenderFrameHostImpl::JavaScriptDialogClosed(
1424 IPC::Message* reply_msg,
1425 bool success,
1426 const base::string16& user_input,
1427 bool dialog_was_suppressed) {
1428 GetProcess()->SetIgnoreInputEvents(false);
1429 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
1431 // If we are executing as part of (before)unload event handling, we don't
1432 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
1433 // leave the current page. In this case, use the regular timeout value used
1434 // during the (before)unload handling.
1435 if (is_waiting) {
1436 render_view_host_->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
1437 success ? RenderViewHostImpl::kUnloadTimeoutMS
1438 : render_view_host_->hung_renderer_delay_ms_));
1441 FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
1442 success, user_input);
1443 Send(reply_msg);
1445 // If we are waiting for an unload or beforeunload ack and the user has
1446 // suppressed messages, kill the tab immediately; a page that's spamming
1447 // alerts in onbeforeunload is presumably malicious, so there's no point in
1448 // continuing to run its script and dragging out the process.
1449 // This must be done after sending the reply since RenderView can't close
1450 // correctly while waiting for a response.
1451 if (is_waiting && dialog_was_suppressed)
1452 render_view_host_->delegate_->RendererUnresponsive(render_view_host_);
1455 void RenderFrameHostImpl::NotificationClosed(int notification_id) {
1456 cancel_notification_callbacks_.erase(notification_id);
1459 // PlzNavigate
1460 void RenderFrameHostImpl::CommitNavigation(
1461 ResourceResponse* response,
1462 scoped_ptr<StreamHandle> body,
1463 const CommonNavigationParams& common_params,
1464 const CommitNavigationParams& commit_params) {
1465 // TODO(clamy): Check if we have to add security checks for the browser plugin
1466 // guests.
1468 Send(new FrameMsg_CommitNavigation(
1469 routing_id_, response->head, body->GetURL(),
1470 common_params, commit_params));
1471 // TODO(clamy): Check if we should start the throbber for non javascript urls
1472 // here.
1474 // TODO(clamy): Release the stream handle once the renderer has finished
1475 // reading it.
1476 stream_handle_ = body.Pass();
1479 void RenderFrameHostImpl::SetUpMojoIfNeeded() {
1480 if (service_registry_.get())
1481 return;
1483 service_registry_.reset(new ServiceRegistryImpl());
1484 if (!GetProcess()->GetServiceRegistry())
1485 return;
1487 RegisterMojoServices();
1488 RenderFrameSetupPtr setup;
1489 GetProcess()->GetServiceRegistry()->ConnectToRemoteService(&setup);
1490 mojo::ServiceProviderPtr service_provider;
1491 setup->GetServiceProviderForFrame(routing_id_,
1492 mojo::GetProxy(&service_provider));
1493 service_registry_->BindRemoteServiceProvider(
1494 service_provider.PassMessagePipe());
1496 #if defined(OS_ANDROID)
1497 service_registry_android_.reset(
1498 new ServiceRegistryAndroid(service_registry_.get()));
1499 #endif
1502 void RenderFrameHostImpl::InvalidateMojoConnection() {
1503 #if defined(OS_ANDROID)
1504 // The Android-specific service registry has a reference to
1505 // |service_registry_| and thus must be torn down first.
1506 service_registry_android_.reset();
1507 #endif
1509 service_registry_.reset();
1512 void RenderFrameHostImpl::PlatformNotificationPermissionRequestDone(
1513 int request_id,
1514 bool granted) {
1515 blink::WebNotificationPermission permission =
1516 granted ? blink::WebNotificationPermissionAllowed
1517 : blink::WebNotificationPermissionDenied;
1519 Send(new PlatformNotificationMsg_PermissionRequestComplete(
1520 routing_id_, request_id, permission));
1523 void RenderFrameHostImpl::UpdateCrossProcessIframeAccessibility(
1524 const std::map<int32, int>& node_to_frame_routing_id_map) {
1525 for (const auto& iter : node_to_frame_routing_id_map) {
1526 // This is the id of the accessibility node that has a child frame.
1527 int32 node_id = iter.first;
1528 // The routing id from either a RenderFrame or a RenderFrameProxy.
1529 int frame_routing_id = iter.second;
1531 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1532 FrameTreeNode* child_frame_tree_node = frame_tree->FindByRoutingID(
1533 GetProcess()->GetID(), frame_routing_id);
1534 if (child_frame_tree_node) {
1535 FrameAccessibility::GetInstance()->AddChildFrame(
1536 this, node_id, child_frame_tree_node->frame_tree_node_id());
1541 void RenderFrameHostImpl::UpdateGuestFrameAccessibility(
1542 const std::map<int32, int>& node_to_browser_plugin_instance_id_map) {
1543 for (const auto& iter : node_to_browser_plugin_instance_id_map) {
1544 // This is the id of the accessibility node that hosts a plugin.
1545 int32 node_id = iter.first;
1546 // The id of the browser plugin.
1547 int browser_plugin_instance_id = iter.second;
1548 FrameAccessibility::GetInstance()->AddGuestWebContents(
1549 this, node_id, browser_plugin_instance_id);
1553 void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
1554 Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode));
1557 void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
1558 const base::Callback<void(ui::AXEvent, int)>& callback) {
1559 accessibility_testing_callback_ = callback;
1562 const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() {
1563 return ax_tree_for_testing_.get();
1566 BrowserAccessibilityManager*
1567 RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
1568 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1569 render_view_host_->GetView());
1570 if (view &&
1571 !browser_accessibility_manager_ &&
1572 !no_create_browser_accessibility_manager_for_testing_) {
1573 browser_accessibility_manager_.reset(
1574 view->CreateBrowserAccessibilityManager(this));
1575 if (browser_accessibility_manager_)
1576 UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1);
1577 else
1578 UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1);
1580 return browser_accessibility_manager_.get();
1583 void RenderFrameHostImpl::ActivateFindInPageResultForAccessibility(
1584 int request_id) {
1585 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1586 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1587 BrowserAccessibilityManager* manager =
1588 GetOrCreateBrowserAccessibilityManager();
1589 if (manager)
1590 manager->ActivateFindInPageResult(request_id);
1594 #if defined(OS_WIN)
1596 void RenderFrameHostImpl::SetParentNativeViewAccessible(
1597 gfx::NativeViewAccessible accessible_parent) {
1598 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1599 render_view_host_->GetView());
1600 if (view)
1601 view->SetParentNativeViewAccessible(accessible_parent);
1604 gfx::NativeViewAccessible
1605 RenderFrameHostImpl::GetParentNativeViewAccessible() const {
1606 return delegate_->GetParentNativeViewAccessible();
1609 #elif defined(OS_MACOSX)
1611 void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) {
1612 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index));
1615 void RenderFrameHostImpl::DidCancelPopupMenu() {
1616 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1));
1619 #elif defined(OS_ANDROID)
1621 void RenderFrameHostImpl::DidSelectPopupMenuItems(
1622 const std::vector<int>& selected_indices) {
1623 Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices));
1626 void RenderFrameHostImpl::DidCancelPopupMenu() {
1627 Send(new FrameMsg_SelectPopupMenuItems(
1628 routing_id_, true, std::vector<int>()));
1631 #endif
1633 void RenderFrameHostImpl::ClearPendingTransitionRequestData() {
1634 BrowserThread::PostTask(
1635 BrowserThread::IO,
1636 FROM_HERE,
1637 base::Bind(
1638 &TransitionRequestManager::ClearPendingTransitionRequestData,
1639 base::Unretained(TransitionRequestManager::GetInstance()),
1640 GetProcess()->GetID(),
1641 routing_id_));
1644 void RenderFrameHostImpl::SetNavigationsSuspended(
1645 bool suspend,
1646 const base::TimeTicks& proceed_time) {
1647 // This should only be called to toggle the state.
1648 DCHECK(navigations_suspended_ != suspend);
1650 navigations_suspended_ = suspend;
1651 if (navigations_suspended_) {
1652 TRACE_EVENT_ASYNC_BEGIN0("navigation",
1653 "RenderFrameHostImpl navigation suspended", this);
1654 } else {
1655 TRACE_EVENT_ASYNC_END0("navigation",
1656 "RenderFrameHostImpl navigation suspended", this);
1659 if (!suspend && suspended_nav_params_) {
1660 // There's navigation message params waiting to be sent. Now that we're not
1661 // suspended anymore, resume navigation by sending them. If we were swapped
1662 // out, we should also stop filtering out the IPC messages now.
1663 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1665 DCHECK(!proceed_time.is_null());
1666 suspended_nav_params_->commit_params.browser_navigation_start =
1667 proceed_time;
1668 Send(new FrameMsg_Navigate(routing_id_, *suspended_nav_params_));
1669 suspended_nav_params_.reset();
1673 void RenderFrameHostImpl::CancelSuspendedNavigations() {
1674 // Clear any state if a pending navigation is canceled or preempted.
1675 if (suspended_nav_params_)
1676 suspended_nav_params_.reset();
1678 TRACE_EVENT_ASYNC_END0("navigation",
1679 "RenderFrameHostImpl navigation suspended", this);
1680 navigations_suspended_ = false;
1683 void RenderFrameHostImpl::DidUseGeolocationPermission() {
1684 RenderFrameHost* top_frame = frame_tree_node()->frame_tree()->GetMainFrame();
1685 GetContentClient()->browser()->RegisterPermissionUsage(
1686 PERMISSION_GEOLOCATION,
1687 delegate_->GetAsWebContents(),
1688 GetLastCommittedURL().GetOrigin(),
1689 top_frame->GetLastCommittedURL().GetOrigin());
1692 } // namespace content