Home | History | Annotate | Download | only in frame_host
      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/bind.h"
      8 #include "base/containers/hash_tables.h"
      9 #include "base/lazy_instance.h"
     10 #include "base/metrics/user_metrics_action.h"
     11 #include "content/browser/child_process_security_policy_impl.h"
     12 #include "content/browser/frame_host/cross_process_frame_connector.h"
     13 #include "content/browser/frame_host/cross_site_transferring_request.h"
     14 #include "content/browser/frame_host/frame_tree.h"
     15 #include "content/browser/frame_host/frame_tree_node.h"
     16 #include "content/browser/frame_host/navigator.h"
     17 #include "content/browser/frame_host/render_frame_host_delegate.h"
     18 #include "content/browser/frame_host/render_frame_proxy_host.h"
     19 #include "content/browser/renderer_host/input/input_router.h"
     20 #include "content/browser/renderer_host/input/timeout_monitor.h"
     21 #include "content/browser/renderer_host/render_view_host_impl.h"
     22 #include "content/browser/renderer_host/render_widget_host_impl.h"
     23 #include "content/common/desktop_notification_messages.h"
     24 #include "content/common/frame_messages.h"
     25 #include "content/common/input_messages.h"
     26 #include "content/common/inter_process_time_ticks_converter.h"
     27 #include "content/common/swapped_out_messages.h"
     28 #include "content/public/browser/browser_thread.h"
     29 #include "content/public/browser/content_browser_client.h"
     30 #include "content/public/browser/desktop_notification_delegate.h"
     31 #include "content/public/browser/render_process_host.h"
     32 #include "content/public/browser/render_widget_host_view.h"
     33 #include "content/public/browser/user_metrics.h"
     34 #include "content/public/common/content_constants.h"
     35 #include "content/public/common/url_constants.h"
     36 #include "content/public/common/url_utils.h"
     37 #include "url/gurl.h"
     38 
     39 using base::TimeDelta;
     40 
     41 namespace content {
     42 
     43 namespace {
     44 
     45 // The (process id, routing id) pair that identifies one RenderFrame.
     46 typedef std::pair<int32, int32> RenderFrameHostID;
     47 typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*>
     48     RoutingIDFrameMap;
     49 base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
     50     LAZY_INSTANCE_INITIALIZER;
     51 
     52 class DesktopNotificationDelegateImpl : public DesktopNotificationDelegate {
     53  public:
     54   DesktopNotificationDelegateImpl(RenderFrameHost* render_frame_host,
     55                                   int notification_id)
     56       : render_process_id_(render_frame_host->GetProcess()->GetID()),
     57         render_frame_id_(render_frame_host->GetRoutingID()),
     58         notification_id_(notification_id) {}
     59 
     60   virtual ~DesktopNotificationDelegateImpl() {}
     61 
     62   virtual void NotificationDisplayed() OVERRIDE {
     63     RenderFrameHost* rfh =
     64         RenderFrameHost::FromID(render_process_id_, render_frame_id_);
     65     if (!rfh)
     66       return;
     67 
     68     rfh->Send(new DesktopNotificationMsg_PostDisplay(
     69         rfh->GetRoutingID(), notification_id_));
     70   }
     71 
     72   virtual void NotificationError() OVERRIDE {
     73     RenderFrameHost* rfh =
     74         RenderFrameHost::FromID(render_process_id_, render_frame_id_);
     75     if (!rfh)
     76       return;
     77 
     78     rfh->Send(new DesktopNotificationMsg_PostError(
     79         rfh->GetRoutingID(), notification_id_));
     80     delete this;
     81   }
     82 
     83   virtual void NotificationClosed(bool by_user) OVERRIDE {
     84     RenderFrameHost* rfh =
     85         RenderFrameHost::FromID(render_process_id_, render_frame_id_);
     86     if (!rfh)
     87       return;
     88 
     89     rfh->Send(new DesktopNotificationMsg_PostClose(
     90         rfh->GetRoutingID(), notification_id_, by_user));
     91     static_cast<RenderFrameHostImpl*>(rfh)->NotificationClosed(
     92         notification_id_);
     93     delete this;
     94   }
     95 
     96   virtual void NotificationClick() OVERRIDE {
     97     RenderFrameHost* rfh =
     98         RenderFrameHost::FromID(render_process_id_, render_frame_id_);
     99     if (!rfh)
    100       return;
    101 
    102     rfh->Send(new DesktopNotificationMsg_PostClick(
    103         rfh->GetRoutingID(), notification_id_));
    104   }
    105 
    106  private:
    107   int render_process_id_;
    108   int render_frame_id_;
    109   int notification_id_;
    110 };
    111 
    112 // Translate a WebKit text direction into a base::i18n one.
    113 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
    114     blink::WebTextDirection dir) {
    115   switch (dir) {
    116     case blink::WebTextDirectionLeftToRight:
    117       return base::i18n::LEFT_TO_RIGHT;
    118     case blink::WebTextDirectionRightToLeft:
    119       return base::i18n::RIGHT_TO_LEFT;
    120     default:
    121       NOTREACHED();
    122       return base::i18n::UNKNOWN_DIRECTION;
    123   }
    124 }
    125 
    126 }  // namespace
    127 
    128 RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
    129                                          int render_frame_id) {
    130   return RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
    131 }
    132 
    133 // static
    134 RenderFrameHostImpl* RenderFrameHostImpl::FromID(
    135     int process_id, int routing_id) {
    136   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    137   RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer();
    138   RoutingIDFrameMap::iterator it = frames->find(
    139       RenderFrameHostID(process_id, routing_id));
    140   return it == frames->end() ? NULL : it->second;
    141 }
    142 
    143 RenderFrameHostImpl::RenderFrameHostImpl(
    144     RenderViewHostImpl* render_view_host,
    145     RenderFrameHostDelegate* delegate,
    146     FrameTree* frame_tree,
    147     FrameTreeNode* frame_tree_node,
    148     int routing_id,
    149     bool is_swapped_out)
    150     : render_view_host_(render_view_host),
    151       delegate_(delegate),
    152       cross_process_frame_connector_(NULL),
    153       render_frame_proxy_host_(NULL),
    154       frame_tree_(frame_tree),
    155       frame_tree_node_(frame_tree_node),
    156       routing_id_(routing_id),
    157       is_swapped_out_(is_swapped_out),
    158       weak_ptr_factory_(this) {
    159   frame_tree_->RegisterRenderFrameHost(this);
    160   GetProcess()->AddRoute(routing_id_, this);
    161   g_routing_id_frame_map.Get().insert(std::make_pair(
    162       RenderFrameHostID(GetProcess()->GetID(), routing_id_),
    163       this));
    164 }
    165 
    166 RenderFrameHostImpl::~RenderFrameHostImpl() {
    167   GetProcess()->RemoveRoute(routing_id_);
    168   g_routing_id_frame_map.Get().erase(
    169       RenderFrameHostID(GetProcess()->GetID(), routing_id_));
    170   if (delegate_)
    171     delegate_->RenderFrameDeleted(this);
    172 
    173   // Notify the FrameTree that this RFH is going away, allowing it to shut down
    174   // the corresponding RenderViewHost if it is no longer needed.
    175   frame_tree_->UnregisterRenderFrameHost(this);
    176 }
    177 
    178 int RenderFrameHostImpl::GetRoutingID() {
    179   return routing_id_;
    180 }
    181 
    182 SiteInstance* RenderFrameHostImpl::GetSiteInstance() {
    183   return render_view_host_->GetSiteInstance();
    184 }
    185 
    186 RenderProcessHost* RenderFrameHostImpl::GetProcess() {
    187   // TODO(nasko): This should return its own process, once we have working
    188   // cross-process navigation for subframes.
    189   return render_view_host_->GetProcess();
    190 }
    191 
    192 RenderFrameHost* RenderFrameHostImpl::GetParent() {
    193   FrameTreeNode* parent_node = frame_tree_node_->parent();
    194   if (!parent_node)
    195     return NULL;
    196   return parent_node->current_frame_host();
    197 }
    198 
    199 const std::string& RenderFrameHostImpl::GetFrameName() {
    200   return frame_tree_node_->frame_name();
    201 }
    202 
    203 bool RenderFrameHostImpl::IsCrossProcessSubframe() {
    204   FrameTreeNode* parent_node = frame_tree_node_->parent();
    205   if (!parent_node)
    206     return false;
    207   return GetSiteInstance() !=
    208       parent_node->current_frame_host()->GetSiteInstance();
    209 }
    210 
    211 GURL RenderFrameHostImpl::GetLastCommittedURL() {
    212   return frame_tree_node_->current_url();
    213 }
    214 
    215 gfx::NativeView RenderFrameHostImpl::GetNativeView() {
    216   RenderWidgetHostView* view = render_view_host_->GetView();
    217   if (!view)
    218     return NULL;
    219   return view->GetNativeView();
    220 }
    221 
    222 void RenderFrameHostImpl::ExecuteJavaScript(
    223     const base::string16& javascript) {
    224   Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
    225                                              javascript,
    226                                              0, false));
    227 }
    228 
    229 void RenderFrameHostImpl::ExecuteJavaScript(
    230      const base::string16& javascript,
    231      const JavaScriptResultCallback& callback) {
    232   static int next_id = 1;
    233   int key = next_id++;
    234   Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
    235                                              javascript,
    236                                              key, true));
    237   javascript_callbacks_.insert(std::make_pair(key, callback));
    238 }
    239 
    240 RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
    241   return render_view_host_;
    242 }
    243 
    244 bool RenderFrameHostImpl::Send(IPC::Message* message) {
    245   if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) {
    246     return render_view_host_->input_router()->SendInput(
    247         make_scoped_ptr(message));
    248   }
    249 
    250   if (render_view_host_->IsSwappedOut()) {
    251     DCHECK(render_frame_proxy_host_);
    252     return render_frame_proxy_host_->Send(message);
    253   }
    254 
    255   return GetProcess()->Send(message);
    256 }
    257 
    258 bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
    259   // Filter out most IPC messages if this renderer is swapped out.
    260   // We still want to handle certain ACKs to keep our state consistent.
    261   // TODO(nasko): Only check RenderViewHost state, as this object's own state
    262   // isn't yet properly updated. Transition this check once the swapped out
    263   // state is correct in RenderFrameHost itself.
    264   if (render_view_host_->IsSwappedOut()) {
    265     if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
    266       // If this is a synchronous message and we decided not to handle it,
    267       // we must send an error reply, or else the renderer will be stuck
    268       // and won't respond to future requests.
    269       if (msg.is_sync()) {
    270         IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
    271         reply->set_reply_error();
    272         Send(reply);
    273       }
    274       // Don't continue looking for someone to handle it.
    275       return true;
    276     }
    277   }
    278 
    279   if (delegate_->OnMessageReceived(this, msg))
    280     return true;
    281 
    282   RenderFrameProxyHost* proxy =
    283       frame_tree_node_->render_manager()->GetProxyToParent();
    284   if (proxy && proxy->cross_process_frame_connector() &&
    285       proxy->cross_process_frame_connector()->OnMessageReceived(msg))
    286     return true;
    287 
    288   bool handled = true;
    289   IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
    290     IPC_MESSAGE_HANDLER(FrameHostMsg_AddMessageToConsole, OnAddMessageToConsole)
    291     IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
    292     IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
    293     IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame,
    294                         OnDidStartProvisionalLoadForFrame)
    295     IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
    296                         OnDidFailProvisionalLoadWithError)
    297     IPC_MESSAGE_HANDLER(FrameHostMsg_DidRedirectProvisionalLoad,
    298                         OnDidRedirectProvisionalLoad)
    299     IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
    300                         OnDidFailLoadWithError)
    301     IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad,
    302                                 OnNavigate(msg))
    303     IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
    304     IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
    305                         OnDocumentOnLoadCompleted)
    306     IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
    307     IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
    308     IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
    309     IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
    310                         OnJavaScriptExecuteResponse)
    311     IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptMessage,
    312                                     OnRunJavaScriptMessage)
    313     IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
    314                                     OnRunBeforeUnloadConfirm)
    315     IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
    316                         OnDidAccessInitialDocument)
    317     IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisownOpener, OnDidDisownOpener)
    318     IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
    319     IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateEncoding, OnUpdateEncoding)
    320     IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_RequestPermission,
    321                         OnRequestDesktopNotificationPermission)
    322     IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Show,
    323                         OnShowDesktopNotification)
    324     IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Cancel,
    325                         OnCancelDesktopNotification)
    326     IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
    327                         OnTextSurroundingSelectionResponse)
    328   IPC_END_MESSAGE_MAP()
    329 
    330   return handled;
    331 }
    332 
    333 void RenderFrameHostImpl::Init() {
    334   GetProcess()->ResumeRequestsForView(routing_id_);
    335 }
    336 
    337 void RenderFrameHostImpl::OnAddMessageToConsole(
    338     int32 level,
    339     const base::string16& message,
    340     int32 line_no,
    341     const base::string16& source_id) {
    342   if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
    343     return;
    344 
    345   // Pass through log level only on WebUI pages to limit console spew.
    346   int32 resolved_level =
    347       HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) ? level : 0;
    348 
    349   if (resolved_level >= ::logging::GetMinLogLevel()) {
    350     logging::LogMessage("CONSOLE", line_no, resolved_level).stream() << "\"" <<
    351         message << "\", source: " << source_id << " (" << line_no << ")";
    352   }
    353 }
    354 
    355 void RenderFrameHostImpl::OnCreateChildFrame(int new_routing_id,
    356                                              const std::string& frame_name) {
    357   RenderFrameHostImpl* new_frame = frame_tree_->AddFrame(
    358       frame_tree_node_, new_routing_id, frame_name);
    359   if (delegate_)
    360     delegate_->RenderFrameCreated(new_frame);
    361 }
    362 
    363 void RenderFrameHostImpl::OnDetach() {
    364   frame_tree_->RemoveFrame(frame_tree_node_);
    365 }
    366 
    367 void RenderFrameHostImpl::OnFrameFocused() {
    368   frame_tree_->SetFocusedFrame(frame_tree_node_);
    369 }
    370 
    371 void RenderFrameHostImpl::OnOpenURL(
    372     const FrameHostMsg_OpenURL_Params& params) {
    373   GURL validated_url(params.url);
    374   GetProcess()->FilterURL(false, &validated_url);
    375 
    376   frame_tree_node_->navigator()->RequestOpenURL(
    377       this, validated_url, params.referrer, params.disposition,
    378       params.should_replace_current_entry, params.user_gesture);
    379 }
    380 
    381 void RenderFrameHostImpl::OnDocumentOnLoadCompleted() {
    382   // This message is only sent for top-level frames. TODO(avi): when frame tree
    383   // mirroring works correctly, add a check here to enforce it.
    384   delegate_->DocumentOnLoadCompleted(this);
    385 }
    386 
    387 void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame(
    388     int parent_routing_id,
    389     const GURL& url) {
    390   frame_tree_node_->navigator()->DidStartProvisionalLoad(
    391       this, parent_routing_id, url);
    392 }
    393 
    394 void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError(
    395     const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
    396   frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params);
    397 }
    398 
    399 void RenderFrameHostImpl::OnDidFailLoadWithError(
    400     const GURL& url,
    401     int error_code,
    402     const base::string16& error_description) {
    403   GURL validated_url(url);
    404   GetProcess()->FilterURL(false, &validated_url);
    405 
    406   frame_tree_node_->navigator()->DidFailLoadWithError(
    407       this, validated_url, error_code, error_description);
    408 }
    409 
    410 void RenderFrameHostImpl::OnDidRedirectProvisionalLoad(
    411     int32 page_id,
    412     const GURL& source_url,
    413     const GURL& target_url) {
    414   frame_tree_node_->navigator()->DidRedirectProvisionalLoad(
    415       this, page_id, source_url, target_url);
    416 }
    417 
    418 // Called when the renderer navigates.  For every frame loaded, we'll get this
    419 // notification containing parameters identifying the navigation.
    420 //
    421 // Subframes are identified by the page transition type.  For subframes loaded
    422 // as part of a wider page load, the page_id will be the same as for the top
    423 // level frame.  If the user explicitly requests a subframe navigation, we will
    424 // get a new page_id because we need to create a new navigation entry for that
    425 // action.
    426 void RenderFrameHostImpl::OnNavigate(const IPC::Message& msg) {
    427   // Read the parameters out of the IPC message directly to avoid making another
    428   // copy when we filter the URLs.
    429   PickleIterator iter(msg);
    430   FrameHostMsg_DidCommitProvisionalLoad_Params validated_params;
    431   if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>::
    432       Read(&msg, &iter, &validated_params))
    433     return;
    434 
    435   // If we're waiting for a cross-site beforeunload ack from this renderer and
    436   // we receive a Navigate message from the main frame, then the renderer was
    437   // navigating already and sent it before hearing the ViewMsg_Stop message.
    438   // We do not want to cancel the pending navigation in this case, since the
    439   // old page will soon be stopped.  Instead, treat this as a beforeunload ack
    440   // to allow the pending navigation to continue.
    441   if (render_view_host_->is_waiting_for_beforeunload_ack_ &&
    442       render_view_host_->unload_ack_is_for_cross_site_transition_ &&
    443       PageTransitionIsMainFrame(validated_params.transition)) {
    444     OnBeforeUnloadACK(true, send_before_unload_start_time_,
    445                       base::TimeTicks::Now());
    446     return;
    447   }
    448 
    449   // If we're waiting for an unload ack from this renderer and we receive a
    450   // Navigate message, then the renderer was navigating before it received the
    451   // unload request.  It will either respond to the unload request soon or our
    452   // timer will expire.  Either way, we should ignore this message, because we
    453   // have already committed to closing this renderer.
    454   if (render_view_host_->IsWaitingForUnloadACK())
    455     return;
    456 
    457   RenderProcessHost* process = GetProcess();
    458 
    459   // Attempts to commit certain off-limits URL should be caught more strictly
    460   // than our FilterURL checks below.  If a renderer violates this policy, it
    461   // should be killed.
    462   if (!CanCommitURL(validated_params.url)) {
    463     VLOG(1) << "Blocked URL " << validated_params.url.spec();
    464     validated_params.url = GURL(url::kAboutBlankURL);
    465     RecordAction(base::UserMetricsAction("CanCommitURL_BlockedAndKilled"));
    466     // Kills the process.
    467     process->ReceivedBadMessage();
    468   }
    469 
    470   // Without this check, an evil renderer can trick the browser into creating
    471   // a navigation entry for a banned URL.  If the user clicks the back button
    472   // followed by the forward button (or clicks reload, or round-trips through
    473   // session restore, etc), we'll think that the browser commanded the
    474   // renderer to load the URL and grant the renderer the privileges to request
    475   // the URL.  To prevent this attack, we block the renderer from inserting
    476   // banned URLs into the navigation controller in the first place.
    477   process->FilterURL(false, &validated_params.url);
    478   process->FilterURL(true, &validated_params.referrer.url);
    479   for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
    480       it != validated_params.redirects.end(); ++it) {
    481     process->FilterURL(false, &(*it));
    482   }
    483   process->FilterURL(true, &validated_params.searchable_form_url);
    484 
    485   // Without this check, the renderer can trick the browser into using
    486   // filenames it can't access in a future session restore.
    487   if (!render_view_host_->CanAccessFilesOfPageState(
    488           validated_params.page_state)) {
    489     GetProcess()->ReceivedBadMessage();
    490     return;
    491   }
    492 
    493   frame_tree_node()->navigator()->DidNavigate(this, validated_params);
    494 }
    495 
    496 RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
    497   return static_cast<RenderWidgetHostImpl*>(render_view_host_);
    498 }
    499 
    500 int RenderFrameHostImpl::GetEnabledBindings() {
    501   return render_view_host_->GetEnabledBindings();
    502 }
    503 
    504 void RenderFrameHostImpl::OnCrossSiteResponse(
    505     const GlobalRequestID& global_request_id,
    506     scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
    507     const std::vector<GURL>& transfer_url_chain,
    508     const Referrer& referrer,
    509     PageTransition page_transition,
    510     bool should_replace_current_entry) {
    511   frame_tree_node_->render_manager()->OnCrossSiteResponse(
    512       this, global_request_id, cross_site_transferring_request.Pass(),
    513       transfer_url_chain, referrer, page_transition,
    514       should_replace_current_entry);
    515 }
    516 
    517 void RenderFrameHostImpl::SwapOut(RenderFrameProxyHost* proxy) {
    518   // TODO(creis): Move swapped out state to RFH.  Until then, only update it
    519   // when swapping out the main frame.
    520   if (!GetParent()) {
    521     // If this RenderViewHost is not in the default state, it must have already
    522     // gone through this, therefore just return.
    523     if (render_view_host_->rvh_state_ != RenderViewHostImpl::STATE_DEFAULT)
    524       return;
    525 
    526     render_view_host_->SetState(
    527         RenderViewHostImpl::STATE_WAITING_FOR_UNLOAD_ACK);
    528     render_view_host_->unload_event_monitor_timeout_->Start(
    529         base::TimeDelta::FromMilliseconds(
    530             RenderViewHostImpl::kUnloadTimeoutMS));
    531   }
    532 
    533   set_render_frame_proxy_host(proxy);
    534 
    535   if (render_view_host_->IsRenderViewLive())
    536     Send(new FrameMsg_SwapOut(routing_id_, proxy->GetRoutingID()));
    537 
    538   if (!GetParent())
    539     delegate_->SwappedOut(this);
    540 
    541   // Allow the navigation to proceed.
    542   frame_tree_node_->render_manager()->SwappedOut(this);
    543 }
    544 
    545 void RenderFrameHostImpl::OnBeforeUnloadACK(
    546     bool proceed,
    547     const base::TimeTicks& renderer_before_unload_start_time,
    548     const base::TimeTicks& renderer_before_unload_end_time) {
    549   // TODO(creis): Support properly beforeunload on subframes. For now just
    550   // pretend that the handler ran and allowed the navigation to proceed.
    551   if (GetParent()) {
    552     render_view_host_->is_waiting_for_beforeunload_ack_ = false;
    553     frame_tree_node_->render_manager()->OnBeforeUnloadACK(
    554         render_view_host_->unload_ack_is_for_cross_site_transition_, proceed,
    555         renderer_before_unload_end_time);
    556     return;
    557   }
    558 
    559   render_view_host_->decrement_in_flight_event_count();
    560   render_view_host_->StopHangMonitorTimeout();
    561   // If this renderer navigated while the beforeunload request was in flight, we
    562   // may have cleared this state in OnNavigate, in which case we can ignore
    563   // this message.
    564   // However renderer might also be swapped out but we still want to proceed
    565   // with navigation, otherwise it would block future navigations. This can
    566   // happen when pending cross-site navigation is canceled by a second one just
    567   // before OnNavigate while current RVH is waiting for commit but second
    568   // navigation is started from the beginning.
    569   if (!render_view_host_->is_waiting_for_beforeunload_ack_) {
    570     return;
    571   }
    572 
    573   render_view_host_->is_waiting_for_beforeunload_ack_ = false;
    574 
    575   base::TimeTicks before_unload_end_time;
    576   if (!send_before_unload_start_time_.is_null() &&
    577       !renderer_before_unload_start_time.is_null() &&
    578       !renderer_before_unload_end_time.is_null()) {
    579     // When passing TimeTicks across process boundaries, we need to compensate
    580     // for any skew between the processes. Here we are converting the
    581     // renderer's notion of before_unload_end_time to TimeTicks in the browser
    582     // process. See comments in inter_process_time_ticks_converter.h for more.
    583     InterProcessTimeTicksConverter converter(
    584         LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
    585         LocalTimeTicks::FromTimeTicks(base::TimeTicks::Now()),
    586         RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
    587         RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
    588     LocalTimeTicks browser_before_unload_end_time =
    589         converter.ToLocalTimeTicks(
    590             RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
    591     before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
    592   }
    593   frame_tree_node_->render_manager()->OnBeforeUnloadACK(
    594       render_view_host_->unload_ack_is_for_cross_site_transition_, proceed,
    595       before_unload_end_time);
    596 
    597   // If canceled, notify the delegate to cancel its pending navigation entry.
    598   if (!proceed)
    599     render_view_host_->GetDelegate()->DidCancelLoading();
    600 }
    601 
    602 void RenderFrameHostImpl::OnSwapOutACK() {
    603   OnSwappedOut(false);
    604 }
    605 
    606 void RenderFrameHostImpl::OnSwappedOut(bool timed_out) {
    607   // For now, we only need to update the RVH state machine for top-level swaps.
    608   // Subframe swaps (in --site-per-process) can just continue via RFHM.
    609   if (!GetParent())
    610     render_view_host_->OnSwappedOut(timed_out);
    611   else
    612     frame_tree_node_->render_manager()->SwappedOut(this);
    613 }
    614 
    615 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
    616   // Validate the URLs in |params|.  If the renderer can't request the URLs
    617   // directly, don't show them in the context menu.
    618   ContextMenuParams validated_params(params);
    619   RenderProcessHost* process = GetProcess();
    620 
    621   // We don't validate |unfiltered_link_url| so that this field can be used
    622   // when users want to copy the original link URL.
    623   process->FilterURL(true, &validated_params.link_url);
    624   process->FilterURL(true, &validated_params.src_url);
    625   process->FilterURL(false, &validated_params.page_url);
    626   process->FilterURL(true, &validated_params.frame_url);
    627 
    628   delegate_->ShowContextMenu(this, validated_params);
    629 }
    630 
    631 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
    632     int id, const base::ListValue& result) {
    633   const base::Value* result_value;
    634   if (!result.Get(0, &result_value)) {
    635     // Programming error or rogue renderer.
    636     NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
    637     return;
    638   }
    639 
    640   std::map<int, JavaScriptResultCallback>::iterator it =
    641       javascript_callbacks_.find(id);
    642   if (it != javascript_callbacks_.end()) {
    643     it->second.Run(result_value);
    644     javascript_callbacks_.erase(it);
    645   } else {
    646     NOTREACHED() << "Received script response for unknown request";
    647   }
    648 }
    649 
    650 void RenderFrameHostImpl::OnRunJavaScriptMessage(
    651     const base::string16& message,
    652     const base::string16& default_prompt,
    653     const GURL& frame_url,
    654     JavaScriptMessageType type,
    655     IPC::Message* reply_msg) {
    656   // While a JS message dialog is showing, tabs in the same process shouldn't
    657   // process input events.
    658   GetProcess()->SetIgnoreInputEvents(true);
    659   render_view_host_->StopHangMonitorTimeout();
    660   delegate_->RunJavaScriptMessage(this, message, default_prompt,
    661                                   frame_url, type, reply_msg);
    662 }
    663 
    664 void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
    665     const GURL& frame_url,
    666     const base::string16& message,
    667     bool is_reload,
    668     IPC::Message* reply_msg) {
    669   // While a JS before unload dialog is showing, tabs in the same process
    670   // shouldn't process input events.
    671   GetProcess()->SetIgnoreInputEvents(true);
    672   render_view_host_->StopHangMonitorTimeout();
    673   delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
    674 }
    675 
    676 void RenderFrameHostImpl::OnRequestDesktopNotificationPermission(
    677     const GURL& source_origin, int callback_context) {
    678   base::Closure done_callback = base::Bind(
    679       &RenderFrameHostImpl::DesktopNotificationPermissionRequestDone,
    680       weak_ptr_factory_.GetWeakPtr(), callback_context);
    681   GetContentClient()->browser()->RequestDesktopNotificationPermission(
    682       source_origin, this, done_callback);
    683 }
    684 
    685 void RenderFrameHostImpl::OnShowDesktopNotification(
    686     int notification_id,
    687     const ShowDesktopNotificationHostMsgParams& params) {
    688   base::Closure cancel_callback;
    689   GetContentClient()->browser()->ShowDesktopNotification(
    690       params, this,
    691       new DesktopNotificationDelegateImpl(this, notification_id),
    692       &cancel_callback);
    693   cancel_notification_callbacks_[notification_id] = cancel_callback;
    694 }
    695 
    696 void RenderFrameHostImpl::OnCancelDesktopNotification(int notification_id) {
    697   if (!cancel_notification_callbacks_.count(notification_id)) {
    698     NOTREACHED();
    699     return;
    700   }
    701   cancel_notification_callbacks_[notification_id].Run();
    702   cancel_notification_callbacks_.erase(notification_id);
    703 }
    704 
    705 void RenderFrameHostImpl::OnTextSurroundingSelectionResponse(
    706     const base::string16& content,
    707     size_t start_offset,
    708     size_t end_offset) {
    709   render_view_host_->OnTextSurroundingSelectionResponse(
    710       content, start_offset, end_offset);
    711 }
    712 
    713 void RenderFrameHostImpl::OnDidAccessInitialDocument() {
    714   delegate_->DidAccessInitialDocument();
    715 }
    716 
    717 void RenderFrameHostImpl::OnDidDisownOpener() {
    718   // This message is only sent for top-level frames. TODO(avi): when frame tree
    719   // mirroring works correctly, add a check here to enforce it.
    720   delegate_->DidDisownOpener(this);
    721 }
    722 
    723 void RenderFrameHostImpl::OnUpdateTitle(
    724     int32 page_id,
    725     const base::string16& title,
    726     blink::WebTextDirection title_direction) {
    727   // This message is only sent for top-level frames. TODO(avi): when frame tree
    728   // mirroring works correctly, add a check here to enforce it.
    729   if (title.length() > kMaxTitleChars) {
    730     NOTREACHED() << "Renderer sent too many characters in title.";
    731     return;
    732   }
    733 
    734   delegate_->UpdateTitle(this, page_id, title,
    735                          WebTextDirectionToChromeTextDirection(
    736                              title_direction));
    737 }
    738 
    739 void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
    740   // This message is only sent for top-level frames. TODO(avi): when frame tree
    741   // mirroring works correctly, add a check here to enforce it.
    742   delegate_->UpdateEncoding(this, encoding_name);
    743 }
    744 
    745 void RenderFrameHostImpl::SetPendingShutdown(const base::Closure& on_swap_out) {
    746   render_view_host_->SetPendingShutdown(on_swap_out);
    747 }
    748 
    749 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
    750   // TODO(creis): We should also check for WebUI pages here.  Also, when the
    751   // out-of-process iframes implementation is ready, we should check for
    752   // cross-site URLs that are not allowed to commit in this process.
    753 
    754   // Give the client a chance to disallow URLs from committing.
    755   return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
    756 }
    757 
    758 void RenderFrameHostImpl::Navigate(const FrameMsg_Navigate_Params& params) {
    759   TRACE_EVENT0("frame_host", "RenderFrameHostImpl::Navigate");
    760   // Browser plugin guests are not allowed to navigate outside web-safe schemes,
    761   // so do not grant them the ability to request additional URLs.
    762   if (!GetProcess()->IsIsolatedGuest()) {
    763     ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
    764         GetProcess()->GetID(), params.url);
    765     if (params.url.SchemeIs(url::kDataScheme) &&
    766         params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
    767       // If 'data:' is used, and we have a 'file:' base url, grant access to
    768       // local files.
    769       ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
    770           GetProcess()->GetID(), params.base_url_for_data_url);
    771     }
    772   }
    773 
    774   // Only send the message if we aren't suspended at the start of a cross-site
    775   // request.
    776   if (render_view_host_->navigations_suspended_) {
    777     // Shouldn't be possible to have a second navigation while suspended, since
    778     // navigations will only be suspended during a cross-site request.  If a
    779     // second navigation occurs, RenderFrameHostManager will cancel this pending
    780     // RFH and create a new pending RFH.
    781     DCHECK(!render_view_host_->suspended_nav_params_.get());
    782     render_view_host_->suspended_nav_params_.reset(
    783         new FrameMsg_Navigate_Params(params));
    784   } else {
    785     // Get back to a clean state, in case we start a new navigation without
    786     // completing a RVH swap or unload handler.
    787     render_view_host_->SetState(RenderViewHostImpl::STATE_DEFAULT);
    788 
    789     Send(new FrameMsg_Navigate(routing_id_, params));
    790   }
    791 
    792   // Force the throbber to start. We do this because Blink's "started
    793   // loading" message will be received asynchronously from the UI of the
    794   // browser. But we want to keep the throbber in sync with what's happening
    795   // in the UI. For example, we want to start throbbing immediately when the
    796   // user naivgates even if the renderer is delayed. There is also an issue
    797   // with the throbber starting because the WebUI (which controls whether the
    798   // favicon is displayed) happens synchronously. If the start loading
    799   // messages was asynchronous, then the default favicon would flash in.
    800   //
    801   // Blink doesn't send throb notifications for JavaScript URLs, so we
    802   // don't want to either.
    803   if (!params.url.SchemeIs(url::kJavaScriptScheme))
    804     delegate_->DidStartLoading(this, true);
    805 }
    806 
    807 void RenderFrameHostImpl::NavigateToURL(const GURL& url) {
    808   FrameMsg_Navigate_Params params;
    809   params.page_id = -1;
    810   params.pending_history_list_offset = -1;
    811   params.current_history_list_offset = -1;
    812   params.current_history_list_length = 0;
    813   params.url = url;
    814   params.transition = PAGE_TRANSITION_LINK;
    815   params.navigation_type = FrameMsg_Navigate_Type::NORMAL;
    816   Navigate(params);
    817 }
    818 
    819 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
    820   // TODO(creis): Support subframes.
    821   if (!render_view_host_->IsRenderViewLive() || GetParent()) {
    822     // We don't have a live renderer, so just skip running beforeunload.
    823     render_view_host_->is_waiting_for_beforeunload_ack_ = true;
    824     render_view_host_->unload_ack_is_for_cross_site_transition_ =
    825         for_cross_site_transition;
    826     base::TimeTicks now = base::TimeTicks::Now();
    827     OnBeforeUnloadACK(true, now, now);
    828     return;
    829   }
    830 
    831   // This may be called more than once (if the user clicks the tab close button
    832   // several times, or if she clicks the tab close button then the browser close
    833   // button), and we only send the message once.
    834   if (render_view_host_->is_waiting_for_beforeunload_ack_) {
    835     // Some of our close messages could be for the tab, others for cross-site
    836     // transitions. We always want to think it's for closing the tab if any
    837     // of the messages were, since otherwise it might be impossible to close
    838     // (if there was a cross-site "close" request pending when the user clicked
    839     // the close button). We want to keep the "for cross site" flag only if
    840     // both the old and the new ones are also for cross site.
    841     render_view_host_->unload_ack_is_for_cross_site_transition_ =
    842         render_view_host_->unload_ack_is_for_cross_site_transition_ &&
    843         for_cross_site_transition;
    844   } else {
    845     // Start the hang monitor in case the renderer hangs in the beforeunload
    846     // handler.
    847     render_view_host_->is_waiting_for_beforeunload_ack_ = true;
    848     render_view_host_->unload_ack_is_for_cross_site_transition_ =
    849         for_cross_site_transition;
    850     // Increment the in-flight event count, to ensure that input events won't
    851     // cancel the timeout timer.
    852     render_view_host_->increment_in_flight_event_count();
    853     render_view_host_->StartHangMonitorTimeout(
    854         TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
    855     send_before_unload_start_time_ = base::TimeTicks::Now();
    856     Send(new FrameMsg_BeforeUnload(routing_id_));
    857   }
    858 }
    859 
    860 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
    861                                                    size_t after) {
    862   Send(new FrameMsg_ExtendSelectionAndDelete(routing_id_, before, after));
    863 }
    864 
    865 void RenderFrameHostImpl::JavaScriptDialogClosed(
    866     IPC::Message* reply_msg,
    867     bool success,
    868     const base::string16& user_input,
    869     bool dialog_was_suppressed) {
    870   GetProcess()->SetIgnoreInputEvents(false);
    871   bool is_waiting = render_view_host_->is_waiting_for_beforeunload_ack() ||
    872                     render_view_host_->IsWaitingForUnloadACK();
    873 
    874   // If we are executing as part of (before)unload event handling, we don't
    875   // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
    876   // leave the current page. In this case, use the regular timeout value used
    877   // during the (before)unload handling.
    878   if (is_waiting) {
    879     render_view_host_->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
    880         success ? RenderViewHostImpl::kUnloadTimeoutMS
    881                 : render_view_host_->hung_renderer_delay_ms_));
    882   }
    883 
    884   FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
    885                                                       success, user_input);
    886   Send(reply_msg);
    887 
    888   // If we are waiting for an unload or beforeunload ack and the user has
    889   // suppressed messages, kill the tab immediately; a page that's spamming
    890   // alerts in onbeforeunload is presumably malicious, so there's no point in
    891   // continuing to run its script and dragging out the process.
    892   // This must be done after sending the reply since RenderView can't close
    893   // correctly while waiting for a response.
    894   if (is_waiting && dialog_was_suppressed)
    895     render_view_host_->delegate_->RendererUnresponsive(
    896         render_view_host_,
    897         render_view_host_->is_waiting_for_beforeunload_ack(),
    898         render_view_host_->IsWaitingForUnloadACK());
    899 }
    900 
    901 void RenderFrameHostImpl::NotificationClosed(int notification_id) {
    902   cancel_notification_callbacks_.erase(notification_id);
    903 }
    904 
    905 void RenderFrameHostImpl::DesktopNotificationPermissionRequestDone(
    906     int callback_context) {
    907   Send(new DesktopNotificationMsg_PermissionRequestDone(
    908       routing_id_, callback_context));
    909 }
    910 
    911 }  // namespace content
    912