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
5 #include "content/browser/frame_host/render_frame_proxy_host.h"
6
7 #include <unordered_map>
8 #include <utility>
9 #include <vector>
10
11 #include "base/callback.h"
12 #include "base/hash/hash.h"
13 #include "base/lazy_instance.h"
14 #include "content/browser/bad_message.h"
15 #include "content/browser/blob_storage/chrome_blob_storage_context.h"
16 #include "content/browser/child_process_security_policy_impl.h"
17 #include "content/browser/frame_host/cross_process_frame_connector.h"
18 #include "content/browser/frame_host/frame_tree.h"
19 #include "content/browser/frame_host/frame_tree_node.h"
20 #include "content/browser/frame_host/ipc_utils.h"
21 #include "content/browser/frame_host/navigator.h"
22 #include "content/browser/frame_host/render_frame_host_delegate.h"
23 #include "content/browser/renderer_host/render_view_host_impl.h"
24 #include "content/browser/renderer_host/render_widget_host_view_base.h"
25 #include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
26 #include "content/browser/scoped_active_url.h"
27 #include "content/browser/site_instance_impl.h"
28 #include "content/common/frame_messages.h"
29 #include "content/common/unfreezable_frame_messages.h"
30 #include "content/public/browser/browser_thread.h"
31 #include "content/public/common/content_client.h"
32 #include "content/public/common/content_features.h"
33 #include "ipc/ipc_message.h"
34 #include "mojo/public/cpp/bindings/pending_associated_receiver.h"
35 #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
36 #include "third_party/blink/public/mojom/frame/frame_owner_properties.mojom.h"
37 #include "third_party/blink/public/mojom/scroll/scroll_into_view_params.mojom.h"
38
39 namespace content {
40
41 namespace {
42
GetProxyHostCreatedCallback()43 RenderFrameProxyHost::CreatedCallback& GetProxyHostCreatedCallback() {
44 static base::NoDestructor<RenderFrameProxyHost::CreatedCallback> s_callback;
45 return *s_callback;
46 }
47
48 // The (process id, routing id) pair that identifies one RenderFrameProxy.
49 typedef std::pair<int32_t, int32_t> RenderFrameProxyHostID;
50 typedef std::unordered_map<RenderFrameProxyHostID,
51 RenderFrameProxyHost*,
52 base::IntPairHash<RenderFrameProxyHostID>>
53 RoutingIDFrameProxyMap;
54 base::LazyInstance<RoutingIDFrameProxyMap>::DestructorAtExit
55 g_routing_id_frame_proxy_map = LAZY_INSTANCE_INITIALIZER;
56
57 } // namespace
58
59 // static
SetCreatedCallbackForTesting(const CreatedCallback & created_callback)60 void RenderFrameProxyHost::SetCreatedCallbackForTesting(
61 const CreatedCallback& created_callback) {
62 GetProxyHostCreatedCallback() = created_callback;
63 }
64
65 // static
FromID(int process_id,int routing_id)66 RenderFrameProxyHost* RenderFrameProxyHost::FromID(int process_id,
67 int routing_id) {
68 DCHECK_CURRENTLY_ON(BrowserThread::UI);
69 RoutingIDFrameProxyMap* frames = g_routing_id_frame_proxy_map.Pointer();
70 auto it = frames->find(RenderFrameProxyHostID(process_id, routing_id));
71 return it == frames->end() ? NULL : it->second;
72 }
73
RenderFrameProxyHost(SiteInstance * site_instance,scoped_refptr<RenderViewHostImpl> render_view_host,FrameTreeNode * frame_tree_node)74 RenderFrameProxyHost::RenderFrameProxyHost(
75 SiteInstance* site_instance,
76 scoped_refptr<RenderViewHostImpl> render_view_host,
77 FrameTreeNode* frame_tree_node)
78 : routing_id_(site_instance->GetProcess()->GetNextRoutingID()),
79 site_instance_(site_instance),
80 process_(site_instance->GetProcess()),
81 frame_tree_node_(frame_tree_node),
82 render_frame_proxy_created_(false),
83 render_view_host_(std::move(render_view_host)) {
84 GetProcess()->AddRoute(routing_id_, this);
85 CHECK(
86 g_routing_id_frame_proxy_map.Get()
87 .insert(std::make_pair(
88 RenderFrameProxyHostID(GetProcess()->GetID(), routing_id_), this))
89 .second);
90 CHECK(render_view_host_ ||
91 frame_tree_node_->render_manager()->IsMainFrameForInnerDelegate());
92
93 bool is_proxy_to_parent = !frame_tree_node_->IsMainFrame() &&
94 frame_tree_node_->parent()
95 ->render_manager()
96 ->current_frame_host()
97 ->GetSiteInstance() == site_instance;
98 bool is_proxy_to_outer_delegate =
99 frame_tree_node_->render_manager()->IsMainFrameForInnerDelegate();
100
101 // If this is a proxy to parent frame or this proxy is for the inner
102 // WebContents's FrameTreeNode in outer WebContents's SiteInstance, then we
103 // need a CrossProcessFrameConnector.
104 if (is_proxy_to_parent || is_proxy_to_outer_delegate) {
105 // The RenderFrameHost navigating cross-process is destroyed and a proxy for
106 // it is created in the parent's process. CrossProcessFrameConnector
107 // initialization only needs to happen on an initial cross-process
108 // navigation, when the RenderFrameHost leaves the same process as its
109 // parent. The same CrossProcessFrameConnector is used for subsequent cross-
110 // process navigations, but it will be destroyed if the frame is
111 // navigated back to the same SiteInstance as its parent.
112 cross_process_frame_connector_.reset(new CrossProcessFrameConnector(this));
113 }
114
115 if (!GetProxyHostCreatedCallback().is_null())
116 GetProxyHostCreatedCallback().Run(this);
117 }
118
~RenderFrameProxyHost()119 RenderFrameProxyHost::~RenderFrameProxyHost() {
120 if (GetProcess()->IsInitializedAndNotDead()) {
121 // TODO(nasko): For now, don't send this IPC for top-level frames, as
122 // the top-level RenderFrame will delete the RenderFrameProxy.
123 // This can be removed once we don't have a swapped out state on
124 // RenderFrame. See https://crbug.com/357747
125 if (!frame_tree_node_->IsMainFrame())
126 Send(new UnfreezableFrameMsg_DeleteProxy(routing_id_));
127 }
128
129 // TODO(arthursonzogni): There are no known reason for removing the
130 // RenderViewHostImpl here instead of automatically at the end of the
131 // destructor. This line can be removed.
132 render_view_host_.reset();
133
134 GetProcess()->RemoveRoute(routing_id_);
135 g_routing_id_frame_proxy_map.Get().erase(
136 RenderFrameProxyHostID(GetProcess()->GetID(), routing_id_));
137 }
138
SetChildRWHView(RenderWidgetHostView * view,const gfx::Size * initial_frame_size)139 void RenderFrameProxyHost::SetChildRWHView(
140 RenderWidgetHostView* view,
141 const gfx::Size* initial_frame_size) {
142 cross_process_frame_connector_->SetView(
143 static_cast<RenderWidgetHostViewChildFrame*>(view));
144 if (initial_frame_size)
145 cross_process_frame_connector_->SetLocalFrameSize(*initial_frame_size);
146 }
147
GetRenderViewHost()148 RenderViewHostImpl* RenderFrameProxyHost::GetRenderViewHost() {
149 return frame_tree_node_->frame_tree()
150 ->GetRenderViewHost(site_instance_.get())
151 .get();
152 }
153
GetRenderWidgetHostView()154 RenderWidgetHostView* RenderFrameProxyHost::GetRenderWidgetHostView() {
155 return frame_tree_node_->parent()
156 ->render_manager()
157 ->GetRenderWidgetHostView();
158 }
159
Send(IPC::Message * msg)160 bool RenderFrameProxyHost::Send(IPC::Message* msg) {
161 return GetProcess()->Send(msg);
162 }
163
OnMessageReceived(const IPC::Message & msg)164 bool RenderFrameProxyHost::OnMessageReceived(const IPC::Message& msg) {
165 // Crash reports trigerred by IPC messages for this proxy should be associated
166 // with the URL of the current RenderFrameHost that is being proxied.
167 ScopedActiveURL scoped_active_url(this);
168
169 if (cross_process_frame_connector_.get() &&
170 cross_process_frame_connector_->OnMessageReceived(msg))
171 return true;
172
173 bool handled = true;
174 IPC_BEGIN_MESSAGE_MAP(RenderFrameProxyHost, msg)
175 IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
176 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
177 IPC_MESSAGE_HANDLER(FrameHostMsg_RouteMessageEvent, OnRouteMessageEvent)
178 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
179 IPC_MESSAGE_HANDLER(FrameHostMsg_AdvanceFocus, OnAdvanceFocus)
180 IPC_MESSAGE_HANDLER(FrameHostMsg_PrintCrossProcessSubframe,
181 OnPrintCrossProcessSubframe)
182 IPC_MESSAGE_UNHANDLED(handled = false)
183 IPC_END_MESSAGE_MAP()
184 return handled;
185 }
186
InitRenderFrameProxy()187 bool RenderFrameProxyHost::InitRenderFrameProxy() {
188 DCHECK(!render_frame_proxy_created_);
189
190 // If the current RenderFrameHost is pending deletion, no new proxies should
191 // be created for it, since this frame should no longer be visible from other
192 // processes. We can get here with postMessage while trying to recreate
193 // proxies for the sender.
194 if (!frame_tree_node_->current_frame_host()->is_active())
195 return false;
196
197 // It is possible to reach this when the process is dead (in particular, when
198 // creating proxies from CreateProxiesForChildFrame). In that case, don't
199 // create the proxy. The process shouldn't be resurrected just to create
200 // RenderFrameProxies; it should be restored only if it needs to host a
201 // RenderFrame. When that happens, the process will be reinitialized, and
202 // all necessary proxies, including any of the ones we skipped here, will be
203 // created by CreateProxiesForSiteInstance. See https://crbug.com/476846
204 if (!GetProcess()->IsInitializedAndNotDead())
205 return false;
206
207 int parent_routing_id = MSG_ROUTING_NONE;
208 if (frame_tree_node_->parent()) {
209 // It is safe to use GetRenderFrameProxyHost to get the parent proxy, since
210 // new child frames always start out as local frames, so a new proxy should
211 // never have a RenderFrameHost as a parent.
212 RenderFrameProxyHost* parent_proxy =
213 frame_tree_node_->parent()->render_manager()->GetRenderFrameProxyHost(
214 site_instance_.get());
215 CHECK(parent_proxy);
216
217 // Proxies that aren't live in the parent node should not be initialized
218 // here, since there is no valid parent RenderFrameProxy on the renderer
219 // side. This can happen when adding a new child frame after an opener
220 // process crashed and was reloaded. See https://crbug.com/501152.
221 if (!parent_proxy->is_render_frame_proxy_live())
222 return false;
223
224 parent_routing_id = parent_proxy->GetRoutingID();
225 CHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
226 }
227
228 int opener_routing_id = MSG_ROUTING_NONE;
229 if (frame_tree_node_->opener()) {
230 opener_routing_id = frame_tree_node_->render_manager()->GetOpenerRoutingID(
231 site_instance_.get());
232 }
233
234 int view_routing_id = frame_tree_node_->frame_tree()
235 ->GetRenderViewHost(site_instance_.get())
236 ->GetRoutingID();
237 GetProcess()->GetRendererInterface()->CreateFrameProxy(
238 routing_id_, view_routing_id, opener_routing_id, parent_routing_id,
239 frame_tree_node_->current_replication_state(),
240 frame_tree_node_->devtools_frame_token());
241
242 SetRenderFrameProxyCreated(true);
243
244 // If this proxy was created for a frame that hasn't yet finished loading,
245 // let the renderer know so it can also mark the proxy as loading. See
246 // https://crbug.com/916137.
247 if (frame_tree_node_->IsLoading())
248 GetAssociatedRemoteFrame()->DidStartLoading();
249
250 // For subframes, initialize the proxy's FrameOwnerProperties only if they
251 // differ from default values.
252 bool should_send_properties =
253 !frame_tree_node_->frame_owner_properties().Equals(
254 blink::mojom::FrameOwnerProperties());
255 if (frame_tree_node_->parent() && should_send_properties) {
256 auto frame_owner_properties =
257 frame_tree_node_->frame_owner_properties().Clone();
258 GetAssociatedRemoteFrame()->SetFrameOwnerProperties(
259 std::move(frame_owner_properties));
260 }
261
262 return true;
263 }
264
OnAssociatedInterfaceRequest(const std::string & interface_name,mojo::ScopedInterfaceEndpointHandle handle)265 void RenderFrameProxyHost::OnAssociatedInterfaceRequest(
266 const std::string& interface_name,
267 mojo::ScopedInterfaceEndpointHandle handle) {
268 if (interface_name == mojom::RenderFrameProxyHost::Name_) {
269 frame_proxy_host_associated_receiver_.Bind(
270 mojo::PendingAssociatedReceiver<mojom::RenderFrameProxyHost>(
271 std::move(handle)));
272 } else if (interface_name == blink::mojom::RemoteFrameHost::Name_) {
273 remote_frame_host_receiver_.Bind(
274 mojo::PendingAssociatedReceiver<blink::mojom::RemoteFrameHost>(
275 std::move(handle)));
276 }
277 }
278
279 blink::AssociatedInterfaceProvider*
GetRemoteAssociatedInterfaces()280 RenderFrameProxyHost::GetRemoteAssociatedInterfaces() {
281 if (!remote_associated_interfaces_) {
282 mojo::AssociatedRemote<blink::mojom::AssociatedInterfaceProvider>
283 remote_interfaces;
284 IPC::ChannelProxy* channel = GetProcess()->GetChannel();
285 if (channel) {
286 RenderProcessHostImpl* process =
287 static_cast<RenderProcessHostImpl*>(GetProcess());
288 process->GetRemoteRouteProvider()->GetRoute(
289 GetRoutingID(), remote_interfaces.BindNewEndpointAndPassReceiver());
290 } else {
291 // The channel may not be initialized in some tests environments. In this
292 // case we set up a dummy interface provider.
293 ignore_result(remote_interfaces
294 .BindNewEndpointAndPassDedicatedReceiverForTesting());
295 }
296 remote_associated_interfaces_ =
297 std::make_unique<blink::AssociatedInterfaceProvider>(
298 remote_interfaces.Unbind());
299 }
300 return remote_associated_interfaces_.get();
301 }
302
SetRenderFrameProxyCreated(bool created)303 void RenderFrameProxyHost::SetRenderFrameProxyCreated(bool created) {
304 if (!created) {
305 // If the renderer process has gone away, created can be false. In that
306 // case, invalidate the mojo connection.
307 frame_proxy_host_associated_receiver_.reset();
308 }
309 render_frame_proxy_created_ = created;
310 }
311
312 const mojo::AssociatedRemote<blink::mojom::RemoteFrame>&
GetAssociatedRemoteFrame()313 RenderFrameProxyHost::GetAssociatedRemoteFrame() {
314 if (!remote_frame_)
315 GetRemoteAssociatedInterfaces()->GetInterface(&remote_frame_);
316 return remote_frame_;
317 }
318
319 const mojo::AssociatedRemote<content::mojom::RenderFrameProxy>&
GetAssociatedRenderFrameProxy()320 RenderFrameProxyHost::GetAssociatedRenderFrameProxy() {
321 if (!render_frame_proxy_)
322 GetRemoteAssociatedInterfaces()->GetInterface(&render_frame_proxy_);
323 return render_frame_proxy_;
324 }
325
SetInheritedEffectiveTouchAction(cc::TouchAction touch_action)326 void RenderFrameProxyHost::SetInheritedEffectiveTouchAction(
327 cc::TouchAction touch_action) {
328 cross_process_frame_connector_->OnSetInheritedEffectiveTouchAction(
329 touch_action);
330 }
331
UpdateRenderThrottlingStatus(bool is_throttled,bool subtree_throttled)332 void RenderFrameProxyHost::UpdateRenderThrottlingStatus(
333 bool is_throttled,
334 bool subtree_throttled) {
335 cross_process_frame_connector_->UpdateRenderThrottlingStatus(
336 is_throttled, subtree_throttled);
337 }
338
VisibilityChanged(blink::mojom::FrameVisibility visibility)339 void RenderFrameProxyHost::VisibilityChanged(
340 blink::mojom::FrameVisibility visibility) {
341 cross_process_frame_connector_->OnVisibilityChanged(visibility);
342 }
343
UpdateOpener()344 void RenderFrameProxyHost::UpdateOpener() {
345 // Another frame in this proxy's SiteInstance may reach the new opener by
346 // first reaching this proxy and then referencing its window.opener. Ensure
347 // the new opener's proxy exists in this case.
348 if (frame_tree_node_->opener()) {
349 frame_tree_node_->opener()->render_manager()->CreateOpenerProxies(
350 GetSiteInstance(), frame_tree_node_);
351 }
352
353 int opener_routing_id =
354 frame_tree_node_->render_manager()->GetOpenerRoutingID(GetSiteInstance());
355 Send(new FrameMsg_UpdateOpener(GetRoutingID(), opener_routing_id));
356 }
357
SetFocusedFrame()358 void RenderFrameProxyHost::SetFocusedFrame() {
359 GetAssociatedRemoteFrame()->Focus();
360 }
361
ScrollRectToVisible(const gfx::Rect & rect_to_scroll,blink::mojom::ScrollIntoViewParamsPtr params)362 void RenderFrameProxyHost::ScrollRectToVisible(
363 const gfx::Rect& rect_to_scroll,
364 blink::mojom::ScrollIntoViewParamsPtr params) {
365 GetAssociatedRemoteFrame()->ScrollRectToVisible(rect_to_scroll,
366 std::move(params));
367 }
368
OnDetach()369 void RenderFrameProxyHost::OnDetach() {
370 if (frame_tree_node_->render_manager()->IsMainFrameForInnerDelegate()) {
371 frame_tree_node_->render_manager()->RemoveOuterDelegateFrame();
372 return;
373 }
374
375 // For a main frame with no outer delegate, no further work is needed. In this
376 // case, detach can only be triggered by closing the entire RenderViewHost.
377 // Instead, this cleanup relies on the destructors of RenderFrameHost and
378 // RenderFrameProxyHost decrementing the refcounts of their associated
379 // RenderViewHost. When the refcount hits 0, the corresponding renderer object
380 // is cleaned up. Since WebContents destruction will also destroy
381 // RenderFrameHost/RenderFrameProxyHost objects in FrameTree, this eventually
382 // results in all the associated RenderViewHosts being closed.
383 if (frame_tree_node_->IsMainFrame())
384 return;
385
386 // Otherwise, a remote child frame has been removed from the frame tree.
387 // Make sure that this action is mirrored to all the other renderers, so
388 // the frame tree remains consistent.
389 frame_tree_node_->current_frame_host()->DetachFromProxy();
390 }
391
OnOpenURL(const FrameHostMsg_OpenURL_Params & params)392 void RenderFrameProxyHost::OnOpenURL(
393 const FrameHostMsg_OpenURL_Params& params) {
394 // Verify and unpack IPC payload.
395 GURL validated_url;
396 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory;
397 if (!VerifyOpenURLParams(GetSiteInstance(), params, &validated_url,
398 &blob_url_loader_factory)) {
399 return;
400 }
401
402 RenderFrameHostImpl* current_rfh = frame_tree_node_->current_frame_host();
403
404 // The current_rfh may be pending deletion. In this case, ignore the
405 // navigation, because the frame is going to disappear soon anyway.
406 if (!current_rfh->is_active())
407 return;
408
409 // Verify that we are in the same BrowsingInstance as the current
410 // RenderFrameHost.
411 if (!site_instance_->IsRelatedSiteInstance(current_rfh->GetSiteInstance()))
412 return;
413
414 // Since this navigation targeted a specific RenderFrameProxy, it should stay
415 // in the current tab.
416 DCHECK_EQ(WindowOpenDisposition::CURRENT_TAB, params.disposition);
417
418 // Augment |download_policy| for situations that were not covered on the
419 // renderer side, e.g. status not available on remote frame, etc.
420 NavigationDownloadPolicy download_policy = params.download_policy;
421 GetContentClient()->browser()->AugmentNavigationDownloadPolicy(
422 frame_tree_node_->navigator()->GetController()->GetWebContents(),
423 current_rfh, params.user_gesture, &download_policy);
424
425 if ((frame_tree_node_->pending_frame_policy().sandbox_flags &
426 blink::mojom::WebSandboxFlags::kDownloads) !=
427 blink::mojom::WebSandboxFlags::kNone) {
428 if (download_policy.blocking_downloads_in_sandbox_enabled) {
429 download_policy.SetDisallowed(content::NavigationDownloadType::kSandbox);
430 } else {
431 download_policy.SetAllowed(content::NavigationDownloadType::kSandbox);
432 }
433 }
434
435 // TODO(lfg, lukasza): Remove |extra_headers| parameter from
436 // RequestTransferURL method once both RenderFrameProxyHost and
437 // RenderFrameHostImpl call RequestOpenURL from their OnOpenURL handlers.
438 // See also https://crbug.com/647772.
439 // TODO(clamy): The transition should probably be changed for POST navigations
440 // to PAGE_TRANSITION_FORM_SUBMIT. See https://crbug.com/829827.
441 frame_tree_node_->navigator()->NavigateFromFrameProxy(
442 current_rfh, validated_url, params.initiator_origin, site_instance_.get(),
443 params.referrer, ui::PAGE_TRANSITION_LINK,
444 params.should_replace_current_entry, download_policy,
445 params.post_body ? "POST" : "GET", params.post_body, params.extra_headers,
446 std::move(blob_url_loader_factory), params.user_gesture);
447 }
448
CheckCompleted()449 void RenderFrameProxyHost::CheckCompleted() {
450 RenderFrameHostImpl* target_rfh = frame_tree_node()->current_frame_host();
451 target_rfh->GetAssociatedLocalFrame()->CheckCompleted();
452 }
453
EnableAutoResize(const gfx::Size & min_size,const gfx::Size & max_size)454 void RenderFrameProxyHost::EnableAutoResize(const gfx::Size& min_size,
455 const gfx::Size& max_size) {
456 GetAssociatedRenderFrameProxy()->EnableAutoResize(min_size, max_size);
457 }
458
DisableAutoResize()459 void RenderFrameProxyHost::DisableAutoResize() {
460 GetAssociatedRenderFrameProxy()->DisableAutoResize();
461 }
462
DidUpdateVisualProperties(const cc::RenderFrameMetadata & metadata)463 void RenderFrameProxyHost::DidUpdateVisualProperties(
464 const cc::RenderFrameMetadata& metadata) {
465 GetAssociatedRenderFrameProxy()->DidUpdateVisualProperties(metadata);
466 }
467
ChildProcessGone()468 void RenderFrameProxyHost::ChildProcessGone() {
469 GetAssociatedRenderFrameProxy()->ChildProcessGone();
470 }
471
OnRouteMessageEvent(const FrameMsg_PostMessage_Params & params)472 void RenderFrameProxyHost::OnRouteMessageEvent(
473 const FrameMsg_PostMessage_Params& params) {
474 RenderFrameHostImpl* target_rfh = frame_tree_node()->current_frame_host();
475 if (!target_rfh->IsRenderFrameLive()) {
476 // Check if there is an inner delegate involved; if so target its main
477 // frame or otherwise return since there is no point in forwarding the
478 // message.
479 target_rfh = target_rfh->delegate()->GetMainFrameForInnerDelegate(
480 target_rfh->frame_tree_node());
481 if (!target_rfh || !target_rfh->IsRenderFrameLive())
482 return;
483 }
484
485 // |targetOrigin| argument of postMessage is already checked by
486 // blink::LocalDOMWindow::DispatchMessageEventWithOriginCheck (needed for
487 // messages sent within the same process - e.g. same-site, cross-origin),
488 // but this check needs to be duplicated below in case the recipient renderer
489 // process got compromised (i.e. in case the renderer-side check may be
490 // bypassed).
491 if (!params.target_origin.empty()) {
492 url::Origin target_origin =
493 url::Origin::Create(GURL(base::UTF16ToUTF8(params.target_origin)));
494
495 // Renderer should send either an empty string (this is how "*" is expressed
496 // in the IPC) or a valid, non-opaque origin. OTOH, there are no security
497 // implications here - the message payload needs to be protected from an
498 // unintended recipient, not from the sender.
499 DCHECK(!target_origin.opaque());
500
501 // While the postMessage was in flight, the target might have navigated away
502 // to another origin. In this case, the postMessage should be silently
503 // dropped.
504 if (target_origin != target_rfh->GetLastCommittedOrigin())
505 return;
506 }
507
508 // TODO(lukasza): Move opaque-ness check into ChildProcessSecurityPolicyImpl.
509 auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
510 if (params.source_origin != base::UTF8ToUTF16("null") &&
511 !policy->CanAccessDataForOrigin(GetProcess()->GetID(),
512 GURL(params.source_origin))) {
513 bad_message::ReceivedBadMessage(
514 GetProcess(), bad_message::RFPH_POST_MESSAGE_INVALID_SOURCE_ORIGIN);
515 return;
516 }
517
518 // Only deliver the message if the request came from a RenderFrameHost in the
519 // same BrowsingInstance or if this WebContents is dedicated to a browser
520 // plugin guest.
521 //
522 // TODO(alexmos, lazyboy): The check for browser plugin guest currently
523 // requires going through the delegate. It should be refactored and
524 // performed here once OOPIF support in <webview> is further along.
525 SiteInstance* target_site_instance = target_rfh->GetSiteInstance();
526 if (!target_site_instance->IsRelatedSiteInstance(GetSiteInstance()) &&
527 !target_rfh->delegate()->ShouldRouteMessageEvent(target_rfh,
528 GetSiteInstance()))
529 return;
530
531 int32_t source_routing_id = params.source_routing_id;
532 base::string16 source_origin = params.source_origin;
533 base::string16 target_origin = params.target_origin;
534 blink::TransferableMessage message = std::move(params.message->data);
535
536 // If there is a source_routing_id, translate it to the routing ID of the
537 // equivalent RenderFrameProxyHost in the target process.
538 if (source_routing_id != MSG_ROUTING_NONE) {
539 RenderFrameHostImpl* source_rfh =
540 RenderFrameHostImpl::FromID(GetProcess()->GetID(), source_routing_id);
541 if (!source_rfh) {
542 source_routing_id = MSG_ROUTING_NONE;
543 } else {
544 // https://crbug.com/822958: If the postMessage is going to a descendant
545 // frame, ensure that any pending visual properties such as size are sent
546 // to the target frame before the postMessage, as sites might implicitly
547 // be relying on this ordering.
548 bool target_is_descendant_of_source = false;
549 for (FrameTreeNode* node = target_rfh->frame_tree_node(); node;
550 node = node->parent()) {
551 if (node == source_rfh->frame_tree_node()) {
552 target_is_descendant_of_source = true;
553 break;
554 }
555 }
556 if (target_is_descendant_of_source) {
557 target_rfh->GetRenderWidgetHost()
558 ->SynchronizeVisualPropertiesIgnoringPendingAck();
559 }
560
561 // Ensure that we have a swapped-out RVH and proxy for the source frame
562 // in the target SiteInstance. If it doesn't exist, create it on demand
563 // and also create its opener chain, since that will also be accessible
564 // to the target page.
565 target_rfh->delegate()->EnsureOpenerProxiesExist(source_rfh);
566
567 // Transfer user activation state in the frame tree in the browser and
568 // the non-source and non-target renderer processes when
569 // |transfer_user_activation| is true. We are making an expriment with
570 // dynamic delegation of "autoplay" capability using this post message
571 // approach to transfer user activation.
572 // TODO(lanwei): we should transfer user activation state only when
573 // |source_rfh| and |target_rfh| are in the same frame tree.
574 bool should_transfer_user_activation =
575 base::FeatureList::IsEnabled(
576 features::kUserActivationPostMessageTransfer) &&
577 message.transfer_user_activation;
578 should_transfer_user_activation =
579 should_transfer_user_activation || message.allow_autoplay;
580 if (should_transfer_user_activation &&
581 source_rfh->frame_tree_node()->HasTransientUserActivation()) {
582 target_rfh->frame_tree_node()->TransferUserActivationFrom(source_rfh);
583 }
584
585 // If the message source is a cross-process subframe, its proxy will only
586 // be created in --site-per-process mode. If the proxy wasn't created,
587 // set the source routing ID to MSG_ROUTING_NONE (see
588 // https://crbug.com/485520 for discussion on why this is ok).
589 RenderFrameProxyHost* source_proxy_in_target_site_instance =
590 source_rfh->frame_tree_node()
591 ->render_manager()
592 ->GetRenderFrameProxyHost(target_site_instance);
593 if (source_proxy_in_target_site_instance) {
594 source_routing_id =
595 source_proxy_in_target_site_instance->GetRoutingID();
596 } else {
597 source_routing_id = MSG_ROUTING_NONE;
598 }
599 }
600 }
601
602 target_rfh->PostMessageEvent(source_routing_id, source_origin, target_origin,
603 std::move(message));
604 }
605
OnDidChangeOpener(int32_t opener_routing_id)606 void RenderFrameProxyHost::OnDidChangeOpener(int32_t opener_routing_id) {
607 frame_tree_node_->render_manager()->DidChangeOpener(opener_routing_id,
608 GetSiteInstance());
609 }
610
OnAdvanceFocus(blink::mojom::FocusType type,int32_t source_routing_id)611 void RenderFrameProxyHost::OnAdvanceFocus(blink::mojom::FocusType type,
612 int32_t source_routing_id) {
613 RenderFrameHostImpl* target_rfh =
614 frame_tree_node_->render_manager()->current_frame_host();
615 if (target_rfh->InsidePortal()) {
616 bad_message::ReceivedBadMessage(
617 GetProcess(), bad_message::RFPH_ADVANCE_FOCUS_INTO_PORTAL);
618 return;
619 }
620
621 // Translate the source RenderFrameHost in this process to its equivalent
622 // RenderFrameProxyHost in the target process. This is needed for continuing
623 // the focus traversal from correct place in a parent frame after one of its
624 // child frames finishes its traversal.
625 RenderFrameHostImpl* source_rfh =
626 RenderFrameHostImpl::FromID(GetProcess()->GetID(), source_routing_id);
627 RenderFrameProxyHost* source_proxy =
628 source_rfh ? source_rfh->frame_tree_node()
629 ->render_manager()
630 ->GetRenderFrameProxyHost(target_rfh->GetSiteInstance())
631 : nullptr;
632
633 target_rfh->AdvanceFocus(type, source_proxy);
634 frame_tree_node_->current_frame_host()->delegate()->OnAdvanceFocus(
635 source_rfh);
636 }
637
DidFocusFrame()638 void RenderFrameProxyHost::DidFocusFrame() {
639 RenderFrameHostImpl* render_frame_host =
640 frame_tree_node_->current_frame_host();
641
642 // We need to handle this case due to a race, see documentation in
643 // RenderFrameHostImpl::DidFocusFrame for more details.
644 if (render_frame_host->InsidePortal())
645 return;
646
647 render_frame_host->delegate()->SetFocusedFrame(frame_tree_node_,
648 GetSiteInstance());
649 }
650
CapturePaintPreviewOfCrossProcessSubframe(const gfx::Rect & clip_rect,const base::UnguessableToken & guid)651 void RenderFrameProxyHost::CapturePaintPreviewOfCrossProcessSubframe(
652 const gfx::Rect& clip_rect,
653 const base::UnguessableToken& guid) {
654 RenderFrameHostImpl* rfh = frame_tree_node_->current_frame_host();
655 if (!rfh->is_active())
656 return;
657 rfh->delegate()->CapturePaintPreviewOfCrossProcessSubframe(clip_rect, guid,
658 rfh);
659 }
660
SetIsInert(bool inert)661 void RenderFrameProxyHost::SetIsInert(bool inert) {
662 cross_process_frame_connector_->SetIsInert(inert);
663 }
664
IsInertForTesting()665 bool RenderFrameProxyHost::IsInertForTesting() {
666 return cross_process_frame_connector_->IsInert();
667 }
668
OnPrintCrossProcessSubframe(const gfx::Rect & rect,int document_cookie)669 void RenderFrameProxyHost::OnPrintCrossProcessSubframe(const gfx::Rect& rect,
670 int document_cookie) {
671 RenderFrameHostImpl* rfh = frame_tree_node_->current_frame_host();
672 rfh->delegate()->PrintCrossProcessSubframe(rect, document_cookie, rfh);
673 }
674
675 blink::AssociatedInterfaceProvider*
GetRemoteAssociatedInterfacesTesting()676 RenderFrameProxyHost::GetRemoteAssociatedInterfacesTesting() {
677 return GetRemoteAssociatedInterfaces();
678 }
679
680 } // namespace content
681