Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / content / browser / frame_host / render_frame_host_impl.cc
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.
4
5 #include "content/browser/frame_host/render_frame_host_impl.h"
6
7 #include "base/containers/hash_tables.h"
8 #include "base/lazy_instance.h"
9 #include "base/metrics/user_metrics_action.h"
10 #include "content/browser/child_process_security_policy_impl.h"
11 #include "content/browser/frame_host/cross_process_frame_connector.h"
12 #include "content/browser/frame_host/cross_site_transferring_request.h"
13 #include "content/browser/frame_host/frame_tree.h"
14 #include "content/browser/frame_host/frame_tree_node.h"
15 #include "content/browser/frame_host/navigator.h"
16 #include "content/browser/frame_host/render_frame_host_delegate.h"
17 #include "content/browser/renderer_host/input/input_router.h"
18 #include "content/browser/renderer_host/input/timeout_monitor.h"
19 #include "content/browser/renderer_host/render_view_host_impl.h"
20 #include "content/common/frame_messages.h"
21 #include "content/common/input_messages.h"
22 #include "content/common/inter_process_time_ticks_converter.h"
23 #include "content/common/swapped_out_messages.h"
24 #include "content/public/browser/browser_thread.h"
25 #include "content/public/browser/content_browser_client.h"
26 #include "content/public/browser/render_process_host.h"
27 #include "content/public/browser/render_widget_host_view.h"
28 #include "content/public/browser/user_metrics.h"
29 #include "content/public/common/url_constants.h"
30 #include "url/gurl.h"
31
32 using base::TimeDelta;
33
34 namespace content {
35
36 // The (process id, routing id) pair that identifies one RenderFrame.
37 typedef std::pair<int32, int32> RenderFrameHostID;
38 typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*>
39     RoutingIDFrameMap;
40 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
41     LAZY_INSTANCE_INITIALIZER;
42
43 RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
44                                          int render_frame_id) {
45   return RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
46 }
47
48 // static
49 RenderFrameHostImpl* RenderFrameHostImpl::FromID(
50     int process_id, int routing_id) {
51   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
52   RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer();
53   RoutingIDFrameMap::iterator it = frames->find(
54       RenderFrameHostID(process_id, routing_id));
55   return it == frames->end() ? NULL : it->second;
56 }
57
58 RenderFrameHostImpl::RenderFrameHostImpl(
59     RenderViewHostImpl* render_view_host,
60     RenderFrameHostDelegate* delegate,
61     FrameTree* frame_tree,
62     FrameTreeNode* frame_tree_node,
63     int routing_id,
64     bool is_swapped_out)
65     : render_view_host_(render_view_host),
66       delegate_(delegate),
67       cross_process_frame_connector_(NULL),
68       frame_tree_(frame_tree),
69       frame_tree_node_(frame_tree_node),
70       routing_id_(routing_id),
71       is_swapped_out_(is_swapped_out) {
72   frame_tree_->RegisterRenderFrameHost(this);
73   GetProcess()->AddRoute(routing_id_, this);
74   g_routing_id_frame_map.Get().insert(std::make_pair(
75       RenderFrameHostID(GetProcess()->GetID(), routing_id_),
76       this));
77 }
78
79 RenderFrameHostImpl::~RenderFrameHostImpl() {
80   GetProcess()->RemoveRoute(routing_id_);
81   g_routing_id_frame_map.Get().erase(
82       RenderFrameHostID(GetProcess()->GetID(), routing_id_));
83   if (delegate_)
84     delegate_->RenderFrameDeleted(this);
85
86   // Notify the FrameTree that this RFH is going away, allowing it to shut down
87   // the corresponding RenderViewHost if it is no longer needed.
88   frame_tree_->UnregisterRenderFrameHost(this);
89 }
90
91 int RenderFrameHostImpl::GetRoutingID() {
92   return routing_id_;
93 }
94
95 SiteInstance* RenderFrameHostImpl::GetSiteInstance() {
96   return render_view_host_->GetSiteInstance();
97 }
98
99 RenderProcessHost* RenderFrameHostImpl::GetProcess() {
100   // TODO(nasko): This should return its own process, once we have working
101   // cross-process navigation for subframes.
102   return render_view_host_->GetProcess();
103 }
104
105 RenderFrameHost* RenderFrameHostImpl::GetParent() {
106   FrameTreeNode* parent_node = frame_tree_node_->parent();
107   if (!parent_node)
108     return NULL;
109   return parent_node->current_frame_host();
110 }
111
112 const std::string& RenderFrameHostImpl::GetFrameName() {
113   return frame_tree_node_->frame_name();
114 }
115
116 bool RenderFrameHostImpl::IsCrossProcessSubframe() {
117   FrameTreeNode* parent_node = frame_tree_node_->parent();
118   if (!parent_node)
119     return false;
120   return GetSiteInstance() !=
121       parent_node->current_frame_host()->GetSiteInstance();
122 }
123
124 GURL RenderFrameHostImpl::GetLastCommittedURL() {
125   return frame_tree_node_->current_url();
126 }
127
128 gfx::NativeView RenderFrameHostImpl::GetNativeView() {
129   RenderWidgetHostView* view = render_view_host_->GetView();
130   if (!view)
131     return NULL;
132   return view->GetNativeView();
133 }
134
135 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
136   // TODO(creis): Support subframes.
137   DCHECK(!GetParent());
138
139   if (!render_view_host_->IsRenderViewLive()) {
140     // We don't have a live renderer, so just skip running beforeunload.
141     render_view_host_->is_waiting_for_beforeunload_ack_ = true;
142     render_view_host_->unload_ack_is_for_cross_site_transition_ =
143         for_cross_site_transition;
144     base::TimeTicks now = base::TimeTicks::Now();
145     OnBeforeUnloadACK(true, now, now);
146     return;
147   }
148
149   // This may be called more than once (if the user clicks the tab close button
150   // several times, or if she clicks the tab close button then the browser close
151   // button), and we only send the message once.
152   if (render_view_host_->is_waiting_for_beforeunload_ack_) {
153     // Some of our close messages could be for the tab, others for cross-site
154     // transitions. We always want to think it's for closing the tab if any
155     // of the messages were, since otherwise it might be impossible to close
156     // (if there was a cross-site "close" request pending when the user clicked
157     // the close button). We want to keep the "for cross site" flag only if
158     // both the old and the new ones are also for cross site.
159     render_view_host_->unload_ack_is_for_cross_site_transition_ =
160         render_view_host_->unload_ack_is_for_cross_site_transition_ &&
161         for_cross_site_transition;
162   } else {
163     // Start the hang monitor in case the renderer hangs in the beforeunload
164     // handler.
165     render_view_host_->is_waiting_for_beforeunload_ack_ = true;
166     render_view_host_->unload_ack_is_for_cross_site_transition_ =
167         for_cross_site_transition;
168     // Increment the in-flight event count, to ensure that input events won't
169     // cancel the timeout timer.
170     render_view_host_->increment_in_flight_event_count();
171     render_view_host_->StartHangMonitorTimeout(
172         TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
173     send_before_unload_start_time_ = base::TimeTicks::Now();
174     Send(new FrameMsg_BeforeUnload(routing_id_));
175   }
176 }
177
178 void RenderFrameHostImpl::NotifyContextMenuClosed(
179     const CustomContextMenuContext& context) {
180   Send(new FrameMsg_ContextMenuClosed(routing_id_, context));
181 }
182
183 void RenderFrameHostImpl::ExecuteCustomContextMenuCommand(
184     int action, const CustomContextMenuContext& context) {
185   Send(new FrameMsg_CustomContextMenuAction(routing_id_, context, action));
186 }
187
188 void RenderFrameHostImpl::Undo() {
189   Send(new InputMsg_Undo(routing_id_));
190   RecordAction(base::UserMetricsAction("Undo"));
191 }
192
193 void RenderFrameHostImpl::Redo() {
194   Send(new InputMsg_Redo(routing_id_));
195   RecordAction(base::UserMetricsAction("Redo"));
196 }
197
198 void RenderFrameHostImpl::Cut() {
199   Send(new InputMsg_Cut(routing_id_));
200   RecordAction(base::UserMetricsAction("Cut"));
201 }
202
203 void RenderFrameHostImpl::Copy() {
204   Send(new InputMsg_Copy(routing_id_));
205   RecordAction(base::UserMetricsAction("Copy"));
206 }
207
208 void RenderFrameHostImpl::CopyToFindPboard() {
209 #if defined(OS_MACOSX)
210   // Windows/Linux don't have the concept of a find pasteboard.
211   Send(new InputMsg_CopyToFindPboard(routing_id_));
212   RecordAction(base::UserMetricsAction("CopyToFindPboard"));
213 #endif
214 }
215
216 void RenderFrameHostImpl::Paste() {
217   Send(new InputMsg_Paste(routing_id_));
218   RecordAction(base::UserMetricsAction("Paste"));
219 }
220
221 void RenderFrameHostImpl::PasteAndMatchStyle() {
222   Send(new InputMsg_PasteAndMatchStyle(routing_id_));
223   RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
224 }
225
226 void RenderFrameHostImpl::Delete() {
227   Send(new InputMsg_Delete(routing_id_));
228   RecordAction(base::UserMetricsAction("DeleteSelection"));
229 }
230
231 void RenderFrameHostImpl::SelectAll() {
232   Send(new InputMsg_SelectAll(routing_id_));
233   RecordAction(base::UserMetricsAction("SelectAll"));
234 }
235
236 void RenderFrameHostImpl::Unselect() {
237   Send(new InputMsg_Unselect(routing_id_));
238   RecordAction(base::UserMetricsAction("Unselect"));
239 }
240
241 void RenderFrameHostImpl::InsertCSS(const std::string& css) {
242   Send(new FrameMsg_CSSInsertRequest(routing_id_, css));
243 }
244
245 void RenderFrameHostImpl::ExecuteJavaScript(
246     const base::string16& javascript) {
247   Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
248                                              javascript,
249                                              0, false));
250 }
251
252 void RenderFrameHostImpl::ExecuteJavaScript(
253      const base::string16& javascript,
254      const JavaScriptResultCallback& callback) {
255   static int next_id = 1;
256   int key = next_id++;
257   Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
258                                              javascript,
259                                              key, true));
260   javascript_callbacks_.insert(std::make_pair(key, callback));
261 }
262
263 RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
264   return render_view_host_;
265 }
266
267 bool RenderFrameHostImpl::Send(IPC::Message* message) {
268   if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) {
269     return render_view_host_->input_router()->SendInput(
270         make_scoped_ptr(message));
271   }
272
273   return GetProcess()->Send(message);
274 }
275
276 bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
277   // Filter out most IPC messages if this renderer is swapped out.
278   // We still want to handle certain ACKs to keep our state consistent.
279   // TODO(nasko): Only check RenderViewHost state, as this object's own state
280   // isn't yet properly updated. Transition this check once the swapped out
281   // state is correct in RenderFrameHost itself.
282   if (render_view_host_->IsSwappedOut()) {
283     if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
284       // If this is a synchronous message and we decided not to handle it,
285       // we must send an error reply, or else the renderer will be stuck
286       // and won't respond to future requests.
287       if (msg.is_sync()) {
288         IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
289         reply->set_reply_error();
290         Send(reply);
291       }
292       // Don't continue looking for someone to handle it.
293       return true;
294     }
295   }
296
297   if (delegate_->OnMessageReceived(this, msg))
298     return true;
299
300   if (cross_process_frame_connector_ &&
301       cross_process_frame_connector_->OnMessageReceived(msg))
302     return true;
303
304   bool handled = true;
305   bool msg_is_ok = true;
306   IPC_BEGIN_MESSAGE_MAP_EX(RenderFrameHostImpl, msg, msg_is_ok)
307     IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
308     IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
309     IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame,
310                         OnDidStartProvisionalLoadForFrame)
311     IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
312                         OnDidFailProvisionalLoadWithError)
313     IPC_MESSAGE_HANDLER(FrameHostMsg_DidRedirectProvisionalLoad,
314                         OnDidRedirectProvisionalLoad)
315     IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
316                         OnDidFailLoadWithError)
317     IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad,
318                                 OnNavigate(msg))
319     IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
320     IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
321     IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
322     IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
323     IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
324     IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
325     IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
326                         OnJavaScriptExecuteResponse)
327   IPC_END_MESSAGE_MAP_EX()
328
329   if (!msg_is_ok) {
330     // The message had a handler, but its de-serialization failed.
331     // Kill the renderer.
332     RecordAction(base::UserMetricsAction("BadMessageTerminate_RFH"));
333     GetProcess()->ReceivedBadMessage();
334   }
335
336   return handled;
337 }
338
339 void RenderFrameHostImpl::Init() {
340   GetProcess()->ResumeRequestsForView(routing_id_);
341 }
342
343 void RenderFrameHostImpl::OnCreateChildFrame(int new_routing_id,
344                                              const std::string& frame_name) {
345   RenderFrameHostImpl* new_frame = frame_tree_->AddFrame(
346       frame_tree_node_, new_routing_id, frame_name);
347   if (delegate_)
348     delegate_->RenderFrameCreated(new_frame);
349 }
350
351 void RenderFrameHostImpl::OnDetach() {
352   frame_tree_->RemoveFrame(frame_tree_node_);
353 }
354
355 void RenderFrameHostImpl::OnFrameFocused() {
356   frame_tree_->SetFocusedFrame(frame_tree_node_);
357 }
358
359 void RenderFrameHostImpl::OnOpenURL(
360     const FrameHostMsg_OpenURL_Params& params) {
361   GURL validated_url(params.url);
362   GetProcess()->FilterURL(false, &validated_url);
363
364   frame_tree_node_->navigator()->RequestOpenURL(
365       this, validated_url, params.referrer, params.disposition,
366       params.should_replace_current_entry, params.user_gesture);
367 }
368
369 void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame(
370     int parent_routing_id,
371     const GURL& url) {
372   frame_tree_node_->navigator()->DidStartProvisionalLoad(
373       this, parent_routing_id, url);
374 }
375
376 void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError(
377     const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
378   frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params);
379 }
380
381 void RenderFrameHostImpl::OnDidFailLoadWithError(
382     const GURL& url,
383     int error_code,
384     const base::string16& error_description) {
385   GURL validated_url(url);
386   GetProcess()->FilterURL(false, &validated_url);
387
388   frame_tree_node_->navigator()->DidFailLoadWithError(
389       this, validated_url, error_code, error_description);
390 }
391
392 void RenderFrameHostImpl::OnDidRedirectProvisionalLoad(
393     int32 page_id,
394     const GURL& source_url,
395     const GURL& target_url) {
396   frame_tree_node_->navigator()->DidRedirectProvisionalLoad(
397       this, page_id, source_url, target_url);
398 }
399
400 // Called when the renderer navigates.  For every frame loaded, we'll get this
401 // notification containing parameters identifying the navigation.
402 //
403 // Subframes are identified by the page transition type.  For subframes loaded
404 // as part of a wider page load, the page_id will be the same as for the top
405 // level frame.  If the user explicitly requests a subframe navigation, we will
406 // get a new page_id because we need to create a new navigation entry for that
407 // action.
408 void RenderFrameHostImpl::OnNavigate(const IPC::Message& msg) {
409   // Read the parameters out of the IPC message directly to avoid making another
410   // copy when we filter the URLs.
411   PickleIterator iter(msg);
412   FrameHostMsg_DidCommitProvisionalLoad_Params validated_params;
413   if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>::
414       Read(&msg, &iter, &validated_params))
415     return;
416
417   // If we're waiting for a cross-site beforeunload ack from this renderer and
418   // we receive a Navigate message from the main frame, then the renderer was
419   // navigating already and sent it before hearing the ViewMsg_Stop message.
420   // We do not want to cancel the pending navigation in this case, since the
421   // old page will soon be stopped.  Instead, treat this as a beforeunload ack
422   // to allow the pending navigation to continue.
423   if (render_view_host_->is_waiting_for_beforeunload_ack_ &&
424       render_view_host_->unload_ack_is_for_cross_site_transition_ &&
425       PageTransitionIsMainFrame(validated_params.transition)) {
426     OnBeforeUnloadACK(true, send_before_unload_start_time_,
427                       base::TimeTicks::Now());
428     return;
429   }
430
431   // If we're waiting for an unload ack from this renderer and we receive a
432   // Navigate message, then the renderer was navigating before it received the
433   // unload request.  It will either respond to the unload request soon or our
434   // timer will expire.  Either way, we should ignore this message, because we
435   // have already committed to closing this renderer.
436   if (render_view_host_->IsWaitingForUnloadACK())
437     return;
438
439   RenderProcessHost* process = GetProcess();
440
441   // Attempts to commit certain off-limits URL should be caught more strictly
442   // than our FilterURL checks below.  If a renderer violates this policy, it
443   // should be killed.
444   if (!CanCommitURL(validated_params.url)) {
445     VLOG(1) << "Blocked URL " << validated_params.url.spec();
446     validated_params.url = GURL(kAboutBlankURL);
447     RecordAction(base::UserMetricsAction("CanCommitURL_BlockedAndKilled"));
448     // Kills the process.
449     process->ReceivedBadMessage();
450   }
451
452   // Now that something has committed, we don't need to track whether the
453   // initial page has been accessed.
454   render_view_host_->has_accessed_initial_document_ = false;
455
456   // Without this check, an evil renderer can trick the browser into creating
457   // a navigation entry for a banned URL.  If the user clicks the back button
458   // followed by the forward button (or clicks reload, or round-trips through
459   // session restore, etc), we'll think that the browser commanded the
460   // renderer to load the URL and grant the renderer the privileges to request
461   // the URL.  To prevent this attack, we block the renderer from inserting
462   // banned URLs into the navigation controller in the first place.
463   process->FilterURL(false, &validated_params.url);
464   process->FilterURL(true, &validated_params.referrer.url);
465   for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
466       it != validated_params.redirects.end(); ++it) {
467     process->FilterURL(false, &(*it));
468   }
469   process->FilterURL(true, &validated_params.searchable_form_url);
470
471   // Without this check, the renderer can trick the browser into using
472   // filenames it can't access in a future session restore.
473   if (!render_view_host_->CanAccessFilesOfPageState(
474           validated_params.page_state)) {
475     GetProcess()->ReceivedBadMessage();
476     return;
477   }
478
479   frame_tree_node()->navigator()->DidNavigate(this, validated_params);
480 }
481
482 int RenderFrameHostImpl::GetEnabledBindings() {
483   return render_view_host_->GetEnabledBindings();
484 }
485
486 void RenderFrameHostImpl::OnCrossSiteResponse(
487     const GlobalRequestID& global_request_id,
488     scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
489     const std::vector<GURL>& transfer_url_chain,
490     const Referrer& referrer,
491     PageTransition page_transition,
492     bool should_replace_current_entry) {
493   frame_tree_node_->render_manager()->OnCrossSiteResponse(
494       this, global_request_id, cross_site_transferring_request.Pass(),
495       transfer_url_chain, referrer, page_transition,
496       should_replace_current_entry);
497 }
498
499 void RenderFrameHostImpl::SwapOut() {
500   // TODO(creis): Move swapped out state to RFH.  Until then, only update it
501   // when swapping out the main frame.
502   if (!GetParent()) {
503     // If this RenderViewHost is not in the default state, it must have already
504     // gone through this, therefore just return.
505     if (render_view_host_->rvh_state_ != RenderViewHostImpl::STATE_DEFAULT)
506       return;
507
508     render_view_host_->SetState(
509         RenderViewHostImpl::STATE_WAITING_FOR_UNLOAD_ACK);
510     render_view_host_->unload_event_monitor_timeout_->Start(
511         base::TimeDelta::FromMilliseconds(
512             RenderViewHostImpl::kUnloadTimeoutMS));
513   }
514
515   if (render_view_host_->IsRenderViewLive())
516     Send(new FrameMsg_SwapOut(routing_id_));
517
518   if (!GetParent())
519     delegate_->SwappedOut(this);
520
521   // Allow the navigation to proceed.
522   frame_tree_node_->render_manager()->SwappedOut(this);
523 }
524
525 void RenderFrameHostImpl::OnDidStartLoading(bool to_different_document) {
526   delegate_->DidStartLoading(this, to_different_document);
527 }
528
529 void RenderFrameHostImpl::OnDidStopLoading() {
530   delegate_->DidStopLoading(this);
531 }
532
533 void RenderFrameHostImpl::OnBeforeUnloadACK(
534     bool proceed,
535     const base::TimeTicks& renderer_before_unload_start_time,
536     const base::TimeTicks& renderer_before_unload_end_time) {
537   // TODO(creis): Support beforeunload on subframes.
538   if (GetParent()) {
539     NOTREACHED() << "Should only receive BeforeUnload_ACK from the main frame.";
540     return;
541   }
542
543   render_view_host_->decrement_in_flight_event_count();
544   render_view_host_->StopHangMonitorTimeout();
545   // If this renderer navigated while the beforeunload request was in flight, we
546   // may have cleared this state in OnNavigate, in which case we can ignore
547   // this message.
548   if (!render_view_host_->is_waiting_for_beforeunload_ack_ ||
549       render_view_host_->rvh_state_ != RenderViewHostImpl::STATE_DEFAULT) {
550     return;
551   }
552
553   render_view_host_->is_waiting_for_beforeunload_ack_ = false;
554
555   base::TimeTicks before_unload_end_time;
556   if (!send_before_unload_start_time_.is_null() &&
557       !renderer_before_unload_start_time.is_null() &&
558       !renderer_before_unload_end_time.is_null()) {
559     // When passing TimeTicks across process boundaries, we need to compensate
560     // for any skew between the processes. Here we are converting the
561     // renderer's notion of before_unload_end_time to TimeTicks in the browser
562     // process. See comments in inter_process_time_ticks_converter.h for more.
563     InterProcessTimeTicksConverter converter(
564         LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
565         LocalTimeTicks::FromTimeTicks(base::TimeTicks::Now()),
566         RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
567         RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
568     LocalTimeTicks browser_before_unload_end_time =
569         converter.ToLocalTimeTicks(
570             RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
571     before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
572   }
573   frame_tree_node_->render_manager()->OnBeforeUnloadACK(
574       render_view_host_->unload_ack_is_for_cross_site_transition_, proceed,
575       before_unload_end_time);
576
577   // If canceled, notify the delegate to cancel its pending navigation entry.
578   if (!proceed)
579     render_view_host_->GetDelegate()->DidCancelLoading();
580 }
581
582 void RenderFrameHostImpl::OnSwapOutACK() {
583   OnSwappedOut(false);
584 }
585
586 void RenderFrameHostImpl::OnSwappedOut(bool timed_out) {
587   // For now, we only need to update the RVH state machine for top-level swaps.
588   // Subframe swaps (in --site-per-process) can just continue via RFHM.
589   if (!GetParent())
590     render_view_host_->OnSwappedOut(timed_out);
591   else
592     frame_tree_node_->render_manager()->SwappedOut(this);
593 }
594
595 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
596   // Validate the URLs in |params|.  If the renderer can't request the URLs
597   // directly, don't show them in the context menu.
598   ContextMenuParams validated_params(params);
599   RenderProcessHost* process = GetProcess();
600
601   // We don't validate |unfiltered_link_url| so that this field can be used
602   // when users want to copy the original link URL.
603   process->FilterURL(true, &validated_params.link_url);
604   process->FilterURL(true, &validated_params.src_url);
605   process->FilterURL(false, &validated_params.page_url);
606   process->FilterURL(true, &validated_params.frame_url);
607
608   delegate_->ShowContextMenu(this, validated_params);
609 }
610
611 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
612     int id, const base::ListValue& result) {
613   const base::Value* result_value;
614   if (!result.Get(0, &result_value)) {
615     // Programming error or rogue renderer.
616     NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
617     return;
618   }
619
620   std::map<int, JavaScriptResultCallback>::iterator it =
621       javascript_callbacks_.find(id);
622   if (it != javascript_callbacks_.end()) {
623     it->second.Run(result_value);
624     javascript_callbacks_.erase(it);
625   } else {
626     NOTREACHED() << "Received script response for unknown request";
627   }
628 }
629
630 void RenderFrameHostImpl::SetPendingShutdown(const base::Closure& on_swap_out) {
631   render_view_host_->SetPendingShutdown(on_swap_out);
632 }
633
634 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
635   // TODO(creis): We should also check for WebUI pages here.  Also, when the
636   // out-of-process iframes implementation is ready, we should check for
637   // cross-site URLs that are not allowed to commit in this process.
638
639   // Give the client a chance to disallow URLs from committing.
640   return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
641 }
642
643 void RenderFrameHostImpl::Navigate(const FrameMsg_Navigate_Params& params) {
644   TRACE_EVENT0("frame_host", "RenderFrameHostImpl::Navigate");
645   // Browser plugin guests are not allowed to navigate outside web-safe schemes,
646   // so do not grant them the ability to request additional URLs.
647   if (!GetProcess()->IsGuest()) {
648     ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
649         GetProcess()->GetID(), params.url);
650     if (params.url.SchemeIs(kDataScheme) &&
651         params.base_url_for_data_url.SchemeIs(kFileScheme)) {
652       // If 'data:' is used, and we have a 'file:' base url, grant access to
653       // local files.
654       ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
655           GetProcess()->GetID(), params.base_url_for_data_url);
656     }
657   }
658
659   // Only send the message if we aren't suspended at the start of a cross-site
660   // request.
661   if (render_view_host_->navigations_suspended_) {
662     // Shouldn't be possible to have a second navigation while suspended, since
663     // navigations will only be suspended during a cross-site request.  If a
664     // second navigation occurs, RenderFrameHostManager will cancel this pending
665     // RFH and create a new pending RFH.
666     DCHECK(!render_view_host_->suspended_nav_params_.get());
667     render_view_host_->suspended_nav_params_.reset(
668         new FrameMsg_Navigate_Params(params));
669   } else {
670     // Get back to a clean state, in case we start a new navigation without
671     // completing a RVH swap or unload handler.
672     render_view_host_->SetState(RenderViewHostImpl::STATE_DEFAULT);
673
674     Send(new FrameMsg_Navigate(routing_id_, params));
675   }
676
677   // Force the throbber to start. We do this because Blink's "started
678   // loading" message will be received asynchronously from the UI of the
679   // browser. But we want to keep the throbber in sync with what's happening
680   // in the UI. For example, we want to start throbbing immediately when the
681   // user naivgates even if the renderer is delayed. There is also an issue
682   // with the throbber starting because the WebUI (which controls whether the
683   // favicon is displayed) happens synchronously. If the start loading
684   // messages was asynchronous, then the default favicon would flash in.
685   //
686   // Blink doesn't send throb notifications for JavaScript URLs, so we
687   // don't want to either.
688   if (!params.url.SchemeIs(kJavaScriptScheme))
689     delegate_->DidStartLoading(this, true);
690 }
691
692 void RenderFrameHostImpl::NavigateToURL(const GURL& url) {
693   FrameMsg_Navigate_Params params;
694   params.page_id = -1;
695   params.pending_history_list_offset = -1;
696   params.current_history_list_offset = -1;
697   params.current_history_list_length = 0;
698   params.url = url;
699   params.transition = PAGE_TRANSITION_LINK;
700   params.navigation_type = FrameMsg_Navigate_Type::NORMAL;
701   Navigate(params);
702 }
703
704 void RenderFrameHostImpl::SelectRange(const gfx::Point& start,
705                                       const gfx::Point& end) {
706   Send(new InputMsg_SelectRange(routing_id_, start, end));
707 }
708
709 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
710                                                    size_t after) {
711   Send(new FrameMsg_ExtendSelectionAndDelete(routing_id_, before, after));
712 }
713
714 }  // namespace content