1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/frame_host/navigator_impl.h"
7 #include "base/command_line.h"
8 #include "content/browser/frame_host/frame_tree.h"
9 #include "content/browser/frame_host/frame_tree_node.h"
10 #include "content/browser/frame_host/navigation_controller_impl.h"
11 #include "content/browser/frame_host/navigation_entry_impl.h"
12 #include "content/browser/frame_host/navigator_delegate.h"
13 #include "content/browser/frame_host/render_frame_host_impl.h"
14 #include "content/browser/renderer_host/render_view_host_impl.h"
15 #include "content/browser/site_instance_impl.h"
16 #include "content/browser/webui/web_ui_controller_factory_registry.h"
17 #include "content/common/frame_messages.h"
18 #include "content/common/view_messages.h"
19 #include "content/public/browser/browser_context.h"
20 #include "content/public/browser/content_browser_client.h"
21 #include "content/public/browser/invalidate_type.h"
22 #include "content/public/browser/navigation_controller.h"
23 #include "content/public/browser/navigation_details.h"
24 #include "content/public/browser/render_view_host.h"
25 #include "content/public/common/bindings_policy.h"
26 #include "content/public/common/content_client.h"
27 #include "content/public/common/content_switches.h"
28 #include "content/public/common/url_constants.h"
29 #include "content/public/common/url_utils.h"
35 FrameMsg_Navigate_Type::Value GetNavigationType(
36 BrowserContext* browser_context, const NavigationEntryImpl& entry,
37 NavigationController::ReloadType reload_type) {
38 switch (reload_type) {
39 case NavigationControllerImpl::RELOAD:
40 return FrameMsg_Navigate_Type::RELOAD;
41 case NavigationControllerImpl::RELOAD_IGNORING_CACHE:
42 return FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE;
43 case NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL:
44 return FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
45 case NavigationControllerImpl::NO_RELOAD:
46 break; // Fall through to rest of function.
49 // |RenderViewImpl::PopulateStateFromPendingNavigationParams| differentiates
50 // between |RESTORE_WITH_POST| and |RESTORE|.
51 if (entry.restore_type() ==
52 NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY) {
53 if (entry.GetHasPostData())
54 return FrameMsg_Navigate_Type::RESTORE_WITH_POST;
55 return FrameMsg_Navigate_Type::RESTORE;
58 return FrameMsg_Navigate_Type::NORMAL;
61 void MakeNavigateParams(const NavigationEntryImpl& entry,
62 const NavigationControllerImpl& controller,
63 NavigationController::ReloadType reload_type,
64 FrameMsg_Navigate_Params* params) {
65 params->page_id = entry.GetPageID();
66 params->should_clear_history_list = entry.should_clear_history_list();
67 params->should_replace_current_entry = entry.should_replace_entry();
68 if (entry.should_clear_history_list()) {
69 // Set the history list related parameters to the same values a
70 // NavigationController would return before its first navigation. This will
71 // fully clear the RenderView's view of the session history.
72 params->pending_history_list_offset = -1;
73 params->current_history_list_offset = -1;
74 params->current_history_list_length = 0;
76 params->pending_history_list_offset = controller.GetIndexOfEntry(&entry);
77 params->current_history_list_offset =
78 controller.GetLastCommittedEntryIndex();
79 params->current_history_list_length = controller.GetEntryCount();
81 params->url = entry.GetURL();
82 if (!entry.GetBaseURLForDataURL().is_empty()) {
83 params->base_url_for_data_url = entry.GetBaseURLForDataURL();
84 params->history_url_for_data_url = entry.GetVirtualURL();
86 params->referrer = entry.GetReferrer();
87 params->transition = entry.GetTransitionType();
88 params->page_state = entry.GetPageState();
89 params->navigation_type =
90 GetNavigationType(controller.GetBrowserContext(), entry, reload_type);
91 params->request_time = base::Time::Now();
92 params->extra_headers = entry.extra_headers();
93 params->transferred_request_child_id =
94 entry.transferred_global_request_id().child_id;
95 params->transferred_request_request_id =
96 entry.transferred_global_request_id().request_id;
97 params->is_overriding_user_agent = entry.GetIsOverridingUserAgent();
98 // Avoid downloading when in view-source mode.
99 params->allow_download = !entry.IsViewSourceMode();
100 params->is_post = entry.GetHasPostData();
101 if (entry.GetBrowserInitiatedPostData()) {
102 params->browser_initiated_post_data.assign(
103 entry.GetBrowserInitiatedPostData()->front(),
104 entry.GetBrowserInitiatedPostData()->front() +
105 entry.GetBrowserInitiatedPostData()->size());
108 params->redirects = entry.redirect_chain();
110 params->can_load_local_resources = entry.GetCanLoadLocalResources();
111 params->frame_to_navigate = entry.GetFrameToNavigate();
117 NavigatorImpl::NavigatorImpl(
118 NavigationControllerImpl* navigation_controller,
119 NavigatorDelegate* delegate)
120 : controller_(navigation_controller),
121 delegate_(delegate) {
124 void NavigatorImpl::DidStartProvisionalLoad(
125 RenderFrameHostImpl* render_frame_host,
127 int64 parent_frame_id,
130 bool is_error_page = (url.spec() == kUnreachableWebDataURL);
131 bool is_iframe_srcdoc = (url.spec() == kAboutSrcDocURL);
132 GURL validated_url(url);
133 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
134 render_process_host->FilterURL(false, &validated_url);
136 // TODO(creis): This is a hack for now, until we mirror the frame tree and do
137 // cross-process subframe navigations in actual subframes. As a result, we
138 // can currently only support a single cross-process subframe per RVH.
139 NavigationEntryImpl* pending_entry =
140 NavigationEntryImpl::FromNavigationEntry(controller_->GetPendingEntry());
142 pending_entry->frame_tree_node_id() != -1 &&
143 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess))
144 is_main_frame = false;
147 // If there is no browser-initiated pending entry for this navigation and it
148 // is not for the error URL, create a pending entry using the current
149 // SiteInstance, and ensure the address bar updates accordingly. We don't
150 // know the referrer or extra headers at this point, but the referrer will
151 // be set properly upon commit.
152 bool has_browser_initiated_pending_entry = pending_entry &&
153 !pending_entry->is_renderer_initiated();
154 if (!has_browser_initiated_pending_entry && !is_error_page) {
155 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
156 controller_->CreateNavigationEntry(validated_url,
158 content::PAGE_TRANSITION_LINK,
159 true /* is_renderer_initiated */,
161 controller_->GetBrowserContext()));
162 entry->set_site_instance(
163 static_cast<SiteInstanceImpl*>(
164 render_frame_host->render_view_host()->GetSiteInstance()));
165 // TODO(creis): If there's a pending entry already, find a safe way to
166 // update it instead of replacing it and copying over things like this.
168 entry->set_transferred_global_request_id(
169 pending_entry->transferred_global_request_id());
170 entry->set_should_replace_entry(pending_entry->should_replace_entry());
171 entry->set_redirect_chain(pending_entry->redirect_chain());
173 controller_->SetPendingEntry(entry);
175 delegate_->NotifyChangedNavigationState(content::INVALIDATE_TYPE_URL);
180 // Notify the observer about the start of the provisional load.
181 delegate_->DidStartProvisionalLoad(
182 render_frame_host, frame_id, parent_frame_id, is_main_frame,
183 validated_url, is_error_page, is_iframe_srcdoc);
188 void NavigatorImpl::DidFailProvisionalLoadWithError(
189 RenderFrameHostImpl* render_frame_host,
190 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
191 VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
192 << ", error_code: " << params.error_code
193 << ", error_description: " << params.error_description
194 << ", is_main_frame: " << params.is_main_frame
195 << ", showing_repost_interstitial: " <<
196 params.showing_repost_interstitial
197 << ", frame_id: " << params.frame_id;
198 GURL validated_url(params.url);
199 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
200 render_process_host->FilterURL(false, &validated_url);
202 if (net::ERR_ABORTED == params.error_code) {
203 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
204 // This means that the interstitial won't be torn down properly, which is
205 // bad. But if we have an interstitial, go back to another tab type, and
206 // then load the same interstitial again, we could end up getting the first
207 // interstitial's "failed" message (as a result of the cancel) when we're on
208 // the second one. We can't tell this apart, so we think we're tearing down
209 // the current page which will cause a crash later on.
211 // http://code.google.com/p/chromium/issues/detail?id=2855
212 // Because this will not tear down the interstitial properly, if "back" is
213 // back to another tab type, the interstitial will still be somewhat alive
214 // in the previous tab type. If you navigate somewhere that activates the
215 // tab with the interstitial again, you'll see a flash before the new load
216 // commits of the interstitial page.
217 FrameTreeNode* root =
218 render_frame_host->frame_tree_node()->frame_tree()->root();
219 if (root->render_manager()->interstitial_page() != NULL) {
220 LOG(WARNING) << "Discarding message during interstitial.";
224 // We used to cancel the pending renderer here for cross-site downloads.
225 // However, it's not safe to do that because the download logic repeatedly
226 // looks for this WebContents based on a render ID. Instead, we just
227 // leave the pending renderer around until the next navigation event
228 // (Navigate, DidNavigate, etc), which will clean it up properly.
230 // TODO(creis): Find a way to cancel any pending RFH here.
233 // Do not usually clear the pending entry if one exists, so that the user's
234 // typed URL is not lost when a navigation fails or is aborted. However, in
235 // cases that we don't show the pending entry (e.g., renderer-initiated
236 // navigations in an existing tab), we don't keep it around. That prevents
237 // spoofs on in-page navigations that don't go through
238 // DidStartProvisionalLoadForFrame.
239 // In general, we allow the view to clear the pending entry and typed URL if
240 // the user requests (e.g., hitting Escape with focus in the address bar).
241 // Note: don't touch the transient entry, since an interstitial may exist.
242 if (controller_->GetPendingEntry() != controller_->GetVisibleEntry())
243 controller_->DiscardPendingEntry();
245 delegate_->DidFailProvisionalLoadWithError(render_frame_host, params);
248 void NavigatorImpl::DidFailLoadWithError(
249 RenderFrameHostImpl* render_frame_host,
254 const base::string16& error_description) {
255 delegate_->DidFailLoadWithError(
256 render_frame_host, frame_id, url, is_main_frame, error_code,
260 void NavigatorImpl::DidRedirectProvisionalLoad(
261 RenderFrameHostImpl* render_frame_host,
263 const GURL& source_url,
264 const GURL& target_url) {
265 // TODO(creis): Remove this method and have the pre-rendering code listen to
266 // WebContentsObserver::DidGetRedirectForResourceRequest instead.
267 // See http://crbug.com/78512.
268 GURL validated_source_url(source_url);
269 GURL validated_target_url(target_url);
270 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
271 render_process_host->FilterURL(false, &validated_source_url);
272 render_process_host->FilterURL(false, &validated_target_url);
273 NavigationEntry* entry;
275 entry = controller_->GetPendingEntry();
277 entry = controller_->GetEntryWithPageID(
278 render_frame_host->GetSiteInstance(), page_id);
280 if (!entry || entry->GetURL() != validated_source_url)
283 delegate_->DidRedirectProvisionalLoad(
284 render_frame_host, validated_target_url);
287 bool NavigatorImpl::NavigateToEntry(
288 RenderFrameHostImpl* render_frame_host,
289 const NavigationEntryImpl& entry,
290 NavigationController::ReloadType reload_type) {
291 TRACE_EVENT0("browser", "NavigatorImpl::NavigateToEntry");
293 // The renderer will reject IPC messages with URLs longer than
294 // this limit, so don't attempt to navigate with a longer URL.
295 if (entry.GetURL().spec().size() > GetMaxURLChars()) {
296 LOG(WARNING) << "Refusing to load URL as it exceeds " << GetMaxURLChars()
301 // Use entry->frame_tree_node_id() to pick which RenderFrameHostManager to
302 // use when --site-per-process is used.
303 RenderFrameHostManager* manager =
304 render_frame_host->frame_tree_node()->render_manager();
305 if (entry.frame_tree_node_id() != -1 &&
306 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess)) {
307 int64 frame_tree_node_id = entry.frame_tree_node_id();
308 manager = render_frame_host->frame_tree_node()->frame_tree()->FindByID(
309 frame_tree_node_id)->render_manager();
312 RenderFrameHostImpl* dest_render_frame_host = manager->Navigate(entry);
313 if (!dest_render_frame_host)
314 return false; // Unable to create the desired RenderFrameHost.
316 // For security, we should never send non-Web-UI URLs to a Web UI renderer.
317 // Double check that here.
318 int enabled_bindings =
319 dest_render_frame_host->render_view_host()->GetEnabledBindings();
320 bool is_allowed_in_web_ui_renderer =
321 WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
322 controller_->GetBrowserContext(), entry.GetURL());
323 if ((enabled_bindings & BINDINGS_POLICY_WEB_UI) &&
324 !is_allowed_in_web_ui_renderer) {
325 // Log the URL to help us diagnose any future failures of this CHECK.
326 GetContentClient()->SetActiveURL(entry.GetURL());
330 // Notify observers that we will navigate in this RenderFrame.
332 delegate_->AboutToNavigateRenderFrame(dest_render_frame_host);
334 // Used for page load time metrics.
335 current_load_start_ = base::TimeTicks::Now();
337 // Navigate in the desired RenderFrameHost.
338 // TODO(creis): As a temporary hack, we currently do cross-process subframe
339 // navigations in a top-level frame of the new process. Thus, we don't yet
340 // need to store the correct frame ID in FrameMsg_Navigate_Params.
341 FrameMsg_Navigate_Params navigate_params;
342 MakeNavigateParams(entry, *controller_, reload_type, &navigate_params);
343 dest_render_frame_host->Navigate(navigate_params);
345 if (entry.GetPageID() == -1) {
346 // HACK!! This code suppresses javascript: URLs from being added to
347 // session history, which is what we want to do for javascript: URLs that
348 // do not generate content. What we really need is a message from the
349 // renderer telling us that a new page was not created. The same message
350 // could be used for mailto: URLs and the like.
351 if (entry.GetURL().SchemeIs(kJavaScriptScheme))
355 // Notify observers about navigation.
357 delegate_->DidStartNavigationToPendingEntry(render_frame_host,
365 bool NavigatorImpl::NavigateToPendingEntry(
366 RenderFrameHostImpl* render_frame_host,
367 NavigationController::ReloadType reload_type) {
368 return NavigateToEntry(
370 *NavigationEntryImpl::FromNavigationEntry(controller_->GetPendingEntry()),
374 base::TimeTicks NavigatorImpl::GetCurrentLoadStart() {
375 return current_load_start_;
378 void NavigatorImpl::DidNavigate(
379 RenderFrameHostImpl* render_frame_host,
380 const FrameHostMsg_DidCommitProvisionalLoad_Params& input_params) {
381 FrameHostMsg_DidCommitProvisionalLoad_Params params(input_params);
382 FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree();
383 RenderViewHostImpl* rvh = render_frame_host->render_view_host();
384 bool use_site_per_process =
385 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess);
386 if (frame_tree->IsFirstNavigationAfterSwap()) {
387 // First navigation should be a main frame navigation.
388 // TODO(creis): This DCHECK is currently disabled for --site-per-process
389 // because cross-process subframe navigations still have a main frame
391 if (!use_site_per_process)
392 DCHECK(PageTransitionIsMainFrame(params.transition));
393 frame_tree->OnFirstNavigationAfterSwap(params.frame_id);
396 // When using --site-per-process, look up the FrameTreeNode ID that the
397 // renderer-specific frame ID corresponds to.
398 int64 frame_tree_node_id = frame_tree->root()->frame_tree_node_id();
399 if (use_site_per_process) {
401 render_frame_host->frame_tree_node()->frame_tree_node_id();
403 // TODO(creis): In the short term, cross-process subframe navigations are
404 // happening in the pending RenderViewHost's top-level frame. (We need to
405 // both mirror the frame tree and get the navigation to occur in the correct
406 // subframe to fix this.) Until then, we should check whether we have a
407 // pending NavigationEntry with a frame ID and if so, treat the
408 // cross-process "main frame" navigation as a subframe navigation. This
409 // limits us to a single cross-process subframe per RVH, and it affects
410 // NavigateToEntry, NavigatorImpl::DidStartProvisionalLoad, and
412 NavigationEntryImpl* pending_entry =
413 NavigationEntryImpl::FromNavigationEntry(
414 controller_->GetPendingEntry());
415 int root_ftn_id = frame_tree->root()->frame_tree_node_id();
417 pending_entry->frame_tree_node_id() != -1 &&
418 pending_entry->frame_tree_node_id() != root_ftn_id) {
419 params.transition = PAGE_TRANSITION_AUTO_SUBFRAME;
420 frame_tree_node_id = pending_entry->frame_tree_node_id();
424 if (PageTransitionIsMainFrame(params.transition)) {
425 // When overscroll navigation gesture is enabled, a screenshot of the page
426 // in its current state is taken so that it can be used during the
427 // nav-gesture. It is necessary to take the screenshot here, before calling
428 // RenderFrameHostManager::DidNavigateMainFrame, because that can change
429 // WebContents::GetRenderViewHost to return the new host, instead of the one
430 // that may have just been swapped out.
431 if (delegate_ && delegate_->CanOverscrollContent())
432 controller_->TakeScreenshot();
434 if (!use_site_per_process)
435 frame_tree->root()->render_manager()->DidNavigateMainFrame(rvh);
438 // When using --site-per-process, we notify the RFHM for all navigations,
439 // not just main frame navigations.
440 if (use_site_per_process) {
441 FrameTreeNode* frame = frame_tree->FindByID(frame_tree_node_id);
442 // TODO(creis): Rename to DidNavigateFrame.
443 frame->render_manager()->DidNavigateMainFrame(rvh);
446 // Update the site of the SiteInstance if it doesn't have one yet, unless
447 // assigning a site is not necessary for this URL. In that case, the
448 // SiteInstance can still be considered unused until a navigation to a real
450 SiteInstanceImpl* site_instance =
451 static_cast<SiteInstanceImpl*>(render_frame_host->GetSiteInstance());
452 if (!site_instance->HasSite() &&
453 ShouldAssignSiteForURL(params.url)) {
454 site_instance->SetSite(params.url);
457 // Need to update MIME type here because it's referred to in
458 // UpdateNavigationCommands() called by RendererDidNavigate() to
459 // determine whether or not to enable the encoding menu.
460 // It's updated only for the main frame. For a subframe,
461 // RenderView::UpdateURL does not set params.contents_mime_type.
462 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
463 // TODO(jungshik): Add a test for the encoding menu to avoid
464 // regressing it again.
465 // TODO(nasko): Verify the correctness of the above comment, since some of the
466 // code doesn't exist anymore. Also, move this code in the
467 // PageTransitionIsMainFrame code block above.
468 if (PageTransitionIsMainFrame(params.transition) && delegate_)
469 delegate_->SetMainFrameMimeType(params.contents_mime_type);
471 LoadCommittedDetails details;
472 bool did_navigate = controller_->RendererDidNavigate(rvh, params, &details);
474 // For now, keep track of each frame's URL in its FrameTreeNode. This lets
475 // us estimate our process count for implementing OOP iframes.
476 // TODO(creis): Remove this when we track which pages commit in each frame.
477 frame_tree->SetFrameUrl(params.frame_id, params.url);
479 // Send notification about committed provisional loads. This notification is
480 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
481 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
482 if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) {
483 // For AUTO_SUBFRAME navigations, an event for the main frame is generated
484 // that is not recorded in the navigation history. For the purpose of
485 // tracking navigation events, we treat this event as a sub frame navigation
487 bool is_main_frame = did_navigate ? details.is_main_frame : false;
488 PageTransition transition_type = params.transition;
489 // Whether or not a page transition was triggered by going backward or
490 // forward in the history is only stored in the navigation controller's
493 (controller_->GetLastCommittedEntry()->GetTransitionType() &
494 PAGE_TRANSITION_FORWARD_BACK)) {
495 transition_type = PageTransitionFromInt(
496 params.transition | PAGE_TRANSITION_FORWARD_BACK);
499 delegate_->DidCommitProvisionalLoad(params.frame_id,
500 params.frame_unique_name,
508 return; // No navigation happened.
510 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
511 // for the appropriate notification (best) or you can add it to
512 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
513 // necessary, please).
515 // Run post-commit tasks.
517 if (details.is_main_frame)
518 delegate_->DidNavigateMainFramePostCommit(details, params);
520 delegate_->DidNavigateAnyFramePostCommit(
521 render_frame_host, details, params);
525 bool NavigatorImpl::ShouldAssignSiteForURL(const GURL& url) {
526 // about:blank should not "use up" a new SiteInstance. The SiteInstance can
527 // still be used for a normal web site.
528 if (url == GURL(kAboutBlankURL))
531 // The embedder will then have the opportunity to determine if the URL
532 // should "use up" the SiteInstance.
533 return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
536 } // namespace content