Implement SSLKEYLOGFILE for OpenSSL.
[chromium-blink-merge.git] / content / browser / frame_host / navigation_controller_impl.cc
blobc4f05fdc199d2560d08acd5ded513397d745ec17
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/navigation_controller_impl.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/debug/trace_event.h"
10 #include "base/logging.h"
11 #include "base/metrics/histogram.h"
12 #include "base/strings/string_number_conversions.h" // Temporary
13 #include "base/strings/string_util.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/time/time.h"
16 #include "cc/base/switches.h"
17 #include "content/browser/browser_url_handler_impl.h"
18 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
19 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
20 #include "content/browser/frame_host/debug_urls.h"
21 #include "content/browser/frame_host/interstitial_page_impl.h"
22 #include "content/browser/frame_host/navigation_entry_impl.h"
23 #include "content/browser/frame_host/navigation_entry_screenshot_manager.h"
24 #include "content/browser/renderer_host/render_view_host_impl.h" // Temporary
25 #include "content/browser/site_instance_impl.h"
26 #include "content/common/frame_messages.h"
27 #include "content/common/view_messages.h"
28 #include "content/public/browser/browser_context.h"
29 #include "content/public/browser/content_browser_client.h"
30 #include "content/public/browser/invalidate_type.h"
31 #include "content/public/browser/navigation_details.h"
32 #include "content/public/browser/notification_service.h"
33 #include "content/public/browser/notification_types.h"
34 #include "content/public/browser/render_widget_host.h"
35 #include "content/public/browser/render_widget_host_view.h"
36 #include "content/public/browser/storage_partition.h"
37 #include "content/public/browser/user_metrics.h"
38 #include "content/public/common/content_client.h"
39 #include "content/public/common/content_constants.h"
40 #include "net/base/escape.h"
41 #include "net/base/mime_util.h"
42 #include "net/base/net_util.h"
43 #include "skia/ext/platform_canvas.h"
44 #include "url/url_constants.h"
46 namespace content {
47 namespace {
49 // Invoked when entries have been pruned, or removed. For example, if the
50 // current entries are [google, digg, yahoo], with the current entry google,
51 // and the user types in cnet, then digg and yahoo are pruned.
52 void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
53 bool from_front,
54 int count) {
55 PrunedDetails details;
56 details.from_front = from_front;
57 details.count = count;
58 NotificationService::current()->Notify(
59 NOTIFICATION_NAV_LIST_PRUNED,
60 Source<NavigationController>(nav_controller),
61 Details<PrunedDetails>(&details));
64 // Ensure the given NavigationEntry has a valid state, so that WebKit does not
65 // get confused if we navigate back to it.
67 // An empty state is treated as a new navigation by WebKit, which would mean
68 // losing the navigation entries and generating a new navigation entry after
69 // this one. We don't want that. To avoid this we create a valid state which
70 // WebKit will not treat as a new navigation.
71 void SetPageStateIfEmpty(NavigationEntryImpl* entry) {
72 if (!entry->GetPageState().IsValid())
73 entry->SetPageState(PageState::CreateFromURL(entry->GetURL()));
76 NavigationEntryImpl::RestoreType ControllerRestoreTypeToEntryType(
77 NavigationController::RestoreType type) {
78 switch (type) {
79 case NavigationController::RESTORE_CURRENT_SESSION:
80 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
81 case NavigationController::RESTORE_LAST_SESSION_EXITED_CLEANLY:
82 return NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY;
83 case NavigationController::RESTORE_LAST_SESSION_CRASHED:
84 return NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED;
86 NOTREACHED();
87 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
90 // Configure all the NavigationEntries in entries for restore. This resets
91 // the transition type to reload and makes sure the content state isn't empty.
92 void ConfigureEntriesForRestore(
93 std::vector<linked_ptr<NavigationEntryImpl> >* entries,
94 NavigationController::RestoreType type) {
95 for (size_t i = 0; i < entries->size(); ++i) {
96 // Use a transition type of reload so that we don't incorrectly increase
97 // the typed count.
98 (*entries)[i]->SetTransitionType(PAGE_TRANSITION_RELOAD);
99 (*entries)[i]->set_restore_type(ControllerRestoreTypeToEntryType(type));
100 // NOTE(darin): This code is only needed for backwards compat.
101 SetPageStateIfEmpty((*entries)[i].get());
105 // There are two general cases where a navigation is in page:
106 // 1. A fragment navigation, in which the url is kept the same except for the
107 // reference fragment.
108 // 2. A history API navigation (pushState and replaceState). This case is
109 // always in-page, but the urls are not guaranteed to match excluding the
110 // fragment. The relevant spec allows pushState/replaceState to any URL on
111 // the same origin.
112 // However, due to reloads, even identical urls are *not* guaranteed to be
113 // in-page navigations, we have to trust the renderer almost entirely.
114 // The one thing we do know is that cross-origin navigations will *never* be
115 // in-page. Therefore, trust the renderer if the URLs are on the same origin,
116 // and assume the renderer is malicious if a cross-origin navigation claims to
117 // be in-page.
118 bool AreURLsInPageNavigation(const GURL& existing_url,
119 const GURL& new_url,
120 bool renderer_says_in_page,
121 RenderFrameHost* rfh) {
122 WebPreferences prefs = rfh->GetRenderViewHost()->GetWebkitPreferences();
123 bool is_same_origin = existing_url.is_empty() ||
124 // TODO(japhet): We should only permit navigations
125 // originating from about:blank to be in-page if the
126 // about:blank is the first document that frame loaded.
127 // We don't have sufficient information to identify
128 // that case at the moment, so always allow about:blank
129 // for now.
130 existing_url == GURL(url::kAboutBlankURL) ||
131 existing_url.GetOrigin() == new_url.GetOrigin() ||
132 !prefs.web_security_enabled;
133 if (!is_same_origin && renderer_says_in_page)
134 rfh->GetProcess()->ReceivedBadMessage();
135 return is_same_origin && renderer_says_in_page;
138 // Determines whether or not we should be carrying over a user agent override
139 // between two NavigationEntries.
140 bool ShouldKeepOverride(const NavigationEntry* last_entry) {
141 return last_entry && last_entry->GetIsOverridingUserAgent();
144 } // namespace
146 // NavigationControllerImpl ----------------------------------------------------
148 const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
150 // static
151 size_t NavigationControllerImpl::max_entry_count_for_testing_ =
152 kMaxEntryCountForTestingNotSet;
154 // Should Reload check for post data? The default is true, but is set to false
155 // when testing.
156 static bool g_check_for_repost = true;
158 // static
159 NavigationEntry* NavigationController::CreateNavigationEntry(
160 const GURL& url,
161 const Referrer& referrer,
162 PageTransition transition,
163 bool is_renderer_initiated,
164 const std::string& extra_headers,
165 BrowserContext* browser_context) {
166 // Allow the browser URL handler to rewrite the URL. This will, for example,
167 // remove "view-source:" from the beginning of the URL to get the URL that
168 // will actually be loaded. This real URL won't be shown to the user, just
169 // used internally.
170 GURL loaded_url(url);
171 bool reverse_on_redirect = false;
172 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
173 &loaded_url, browser_context, &reverse_on_redirect);
175 NavigationEntryImpl* entry = new NavigationEntryImpl(
176 NULL, // The site instance for tabs is sent on navigation
177 // (WebContents::GetSiteInstance).
179 loaded_url,
180 referrer,
181 base::string16(),
182 transition,
183 is_renderer_initiated);
184 entry->SetVirtualURL(url);
185 entry->set_user_typed_url(url);
186 entry->set_update_virtual_url_with_url(reverse_on_redirect);
187 entry->set_extra_headers(extra_headers);
188 return entry;
191 // static
192 void NavigationController::DisablePromptOnRepost() {
193 g_check_for_repost = false;
196 base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
197 base::Time t) {
198 // If |t| is between the water marks, we're in a run of duplicates
199 // or just getting out of it, so increase the high-water mark to get
200 // a time that probably hasn't been used before and return it.
201 if (low_water_mark_ <= t && t <= high_water_mark_) {
202 high_water_mark_ += base::TimeDelta::FromMicroseconds(1);
203 return high_water_mark_;
206 // Otherwise, we're clear of the last duplicate run, so reset the
207 // water marks.
208 low_water_mark_ = high_water_mark_ = t;
209 return t;
212 NavigationControllerImpl::NavigationControllerImpl(
213 NavigationControllerDelegate* delegate,
214 BrowserContext* browser_context)
215 : browser_context_(browser_context),
216 pending_entry_(NULL),
217 last_committed_entry_index_(-1),
218 pending_entry_index_(-1),
219 transient_entry_index_(-1),
220 delegate_(delegate),
221 max_restored_page_id_(-1),
222 ssl_manager_(this),
223 needs_reload_(false),
224 is_initial_navigation_(true),
225 in_navigate_to_pending_entry_(false),
226 pending_reload_(NO_RELOAD),
227 get_timestamp_callback_(base::Bind(&base::Time::Now)),
228 screenshot_manager_(new NavigationEntryScreenshotManager(this)) {
229 DCHECK(browser_context_);
232 NavigationControllerImpl::~NavigationControllerImpl() {
233 DiscardNonCommittedEntriesInternal();
236 WebContents* NavigationControllerImpl::GetWebContents() const {
237 return delegate_->GetWebContents();
240 BrowserContext* NavigationControllerImpl::GetBrowserContext() const {
241 return browser_context_;
244 void NavigationControllerImpl::SetBrowserContext(
245 BrowserContext* browser_context) {
246 browser_context_ = browser_context;
249 void NavigationControllerImpl::Restore(
250 int selected_navigation,
251 RestoreType type,
252 std::vector<NavigationEntry*>* entries) {
253 // Verify that this controller is unused and that the input is valid.
254 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
255 DCHECK(selected_navigation >= 0 &&
256 selected_navigation < static_cast<int>(entries->size()));
258 needs_reload_ = true;
259 for (size_t i = 0; i < entries->size(); ++i) {
260 NavigationEntryImpl* entry =
261 NavigationEntryImpl::FromNavigationEntry((*entries)[i]);
262 entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
264 entries->clear();
266 // And finish the restore.
267 FinishRestore(selected_navigation, type);
270 void NavigationControllerImpl::Reload(bool check_for_repost) {
271 ReloadInternal(check_for_repost, RELOAD);
273 void NavigationControllerImpl::ReloadIgnoringCache(bool check_for_repost) {
274 ReloadInternal(check_for_repost, RELOAD_IGNORING_CACHE);
276 void NavigationControllerImpl::ReloadOriginalRequestURL(bool check_for_repost) {
277 ReloadInternal(check_for_repost, RELOAD_ORIGINAL_REQUEST_URL);
280 void NavigationControllerImpl::ReloadInternal(bool check_for_repost,
281 ReloadType reload_type) {
282 if (transient_entry_index_ != -1) {
283 // If an interstitial is showing, treat a reload as a navigation to the
284 // transient entry's URL.
285 NavigationEntryImpl* transient_entry =
286 NavigationEntryImpl::FromNavigationEntry(GetTransientEntry());
287 if (!transient_entry)
288 return;
289 LoadURL(transient_entry->GetURL(),
290 Referrer(),
291 PAGE_TRANSITION_RELOAD,
292 transient_entry->extra_headers());
293 return;
296 NavigationEntryImpl* entry = NULL;
297 int current_index = -1;
299 // If we are reloading the initial navigation, just use the current
300 // pending entry. Otherwise look up the current entry.
301 if (IsInitialNavigation() && pending_entry_) {
302 entry = pending_entry_;
303 // The pending entry might be in entries_ (e.g., after a Clone), so we
304 // should also update the current_index.
305 current_index = pending_entry_index_;
306 } else {
307 DiscardNonCommittedEntriesInternal();
308 current_index = GetCurrentEntryIndex();
309 if (current_index != -1) {
310 entry = NavigationEntryImpl::FromNavigationEntry(
311 GetEntryAtIndex(current_index));
315 // If we are no where, then we can't reload. TODO(darin): We should add a
316 // CanReload method.
317 if (!entry)
318 return;
320 if (reload_type == NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL &&
321 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
322 // We may have been redirected when navigating to the current URL.
323 // Use the URL the user originally intended to visit, if it's valid and if a
324 // POST wasn't involved; the latter case avoids issues with sending data to
325 // the wrong page.
326 entry->SetURL(entry->GetOriginalRequestURL());
327 entry->SetReferrer(Referrer());
330 if (g_check_for_repost && check_for_repost &&
331 entry->GetHasPostData()) {
332 // The user is asking to reload a page with POST data. Prompt to make sure
333 // they really want to do this. If they do, the dialog will call us back
334 // with check_for_repost = false.
335 delegate_->NotifyBeforeFormRepostWarningShow();
337 pending_reload_ = reload_type;
338 delegate_->ActivateAndShowRepostFormWarningDialog();
339 } else {
340 if (!IsInitialNavigation())
341 DiscardNonCommittedEntriesInternal();
343 // If we are reloading an entry that no longer belongs to the current
344 // site instance (for example, refreshing a page for just installed app),
345 // the reload must happen in a new process.
346 // The new entry must have a new page_id and site instance, so it behaves
347 // as new navigation (which happens to clear forward history).
348 // Tabs that are discarded due to low memory conditions may not have a site
349 // instance, and should not be treated as a cross-site reload.
350 SiteInstanceImpl* site_instance = entry->site_instance();
351 // Permit reloading guests without further checks.
352 bool is_isolated_guest = site_instance && site_instance->HasProcess() &&
353 site_instance->GetProcess()->IsIsolatedGuest();
354 if (!is_isolated_guest && site_instance &&
355 site_instance->HasWrongProcessForURL(entry->GetURL())) {
356 // Create a navigation entry that resembles the current one, but do not
357 // copy page id, site instance, content state, or timestamp.
358 NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry(
359 CreateNavigationEntry(
360 entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(),
361 false, entry->extra_headers(), browser_context_));
363 // Mark the reload type as NO_RELOAD, so navigation will not be considered
364 // a reload in the renderer.
365 reload_type = NavigationController::NO_RELOAD;
367 nav_entry->set_should_replace_entry(true);
368 pending_entry_ = nav_entry;
369 } else {
370 pending_entry_ = entry;
371 pending_entry_index_ = current_index;
373 // The title of the page being reloaded might have been removed in the
374 // meanwhile, so we need to revert to the default title upon reload and
375 // invalidate the previously cached title (SetTitle will do both).
376 // See Chromium issue 96041.
377 pending_entry_->SetTitle(base::string16());
379 pending_entry_->SetTransitionType(PAGE_TRANSITION_RELOAD);
382 NavigateToPendingEntry(reload_type);
386 void NavigationControllerImpl::CancelPendingReload() {
387 DCHECK(pending_reload_ != NO_RELOAD);
388 pending_reload_ = NO_RELOAD;
391 void NavigationControllerImpl::ContinuePendingReload() {
392 if (pending_reload_ == NO_RELOAD) {
393 NOTREACHED();
394 } else {
395 ReloadInternal(false, pending_reload_);
396 pending_reload_ = NO_RELOAD;
400 bool NavigationControllerImpl::IsInitialNavigation() const {
401 return is_initial_navigation_;
404 NavigationEntryImpl* NavigationControllerImpl::GetEntryWithPageID(
405 SiteInstance* instance, int32 page_id) const {
406 int index = GetEntryIndexWithPageID(instance, page_id);
407 return (index != -1) ? entries_[index].get() : NULL;
410 void NavigationControllerImpl::LoadEntry(NavigationEntryImpl* entry) {
411 // When navigating to a new page, we don't know for sure if we will actually
412 // end up leaving the current page. The new page load could for example
413 // result in a download or a 'no content' response (e.g., a mailto: URL).
414 SetPendingEntry(entry);
415 NavigateToPendingEntry(NO_RELOAD);
418 void NavigationControllerImpl::SetPendingEntry(NavigationEntryImpl* entry) {
419 DiscardNonCommittedEntriesInternal();
420 pending_entry_ = entry;
421 NotificationService::current()->Notify(
422 NOTIFICATION_NAV_ENTRY_PENDING,
423 Source<NavigationController>(this),
424 Details<NavigationEntry>(entry));
427 NavigationEntry* NavigationControllerImpl::GetActiveEntry() const {
428 if (transient_entry_index_ != -1)
429 return entries_[transient_entry_index_].get();
430 if (pending_entry_)
431 return pending_entry_;
432 return GetLastCommittedEntry();
435 NavigationEntry* NavigationControllerImpl::GetVisibleEntry() const {
436 if (transient_entry_index_ != -1)
437 return entries_[transient_entry_index_].get();
438 // The pending entry is safe to return for new (non-history), browser-
439 // initiated navigations. Most renderer-initiated navigations should not
440 // show the pending entry, to prevent URL spoof attacks.
442 // We make an exception for renderer-initiated navigations in new tabs, as
443 // long as no other page has tried to access the initial empty document in
444 // the new tab. If another page modifies this blank page, a URL spoof is
445 // possible, so we must stop showing the pending entry.
446 bool safe_to_show_pending =
447 pending_entry_ &&
448 // Require a new navigation.
449 pending_entry_->GetPageID() == -1 &&
450 // Require either browser-initiated or an unmodified new tab.
451 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
453 // Also allow showing the pending entry for history navigations in a new tab,
454 // such as Ctrl+Back. In this case, no existing page is visible and no one
455 // can script the new tab before it commits.
456 if (!safe_to_show_pending &&
457 pending_entry_ &&
458 pending_entry_->GetPageID() != -1 &&
459 IsInitialNavigation() &&
460 !pending_entry_->is_renderer_initiated())
461 safe_to_show_pending = true;
463 if (safe_to_show_pending)
464 return pending_entry_;
465 return GetLastCommittedEntry();
468 int NavigationControllerImpl::GetCurrentEntryIndex() const {
469 if (transient_entry_index_ != -1)
470 return transient_entry_index_;
471 if (pending_entry_index_ != -1)
472 return pending_entry_index_;
473 return last_committed_entry_index_;
476 NavigationEntry* NavigationControllerImpl::GetLastCommittedEntry() const {
477 if (last_committed_entry_index_ == -1)
478 return NULL;
479 return entries_[last_committed_entry_index_].get();
482 bool NavigationControllerImpl::CanViewSource() const {
483 const std::string& mime_type = delegate_->GetContentsMimeType();
484 bool is_viewable_mime_type = net::IsSupportedNonImageMimeType(mime_type) &&
485 !net::IsSupportedMediaMimeType(mime_type);
486 NavigationEntry* visible_entry = GetVisibleEntry();
487 return visible_entry && !visible_entry->IsViewSourceMode() &&
488 is_viewable_mime_type && !delegate_->GetInterstitialPage();
491 int NavigationControllerImpl::GetLastCommittedEntryIndex() const {
492 return last_committed_entry_index_;
495 int NavigationControllerImpl::GetEntryCount() const {
496 DCHECK(entries_.size() <= max_entry_count());
497 return static_cast<int>(entries_.size());
500 NavigationEntry* NavigationControllerImpl::GetEntryAtIndex(
501 int index) const {
502 return entries_.at(index).get();
505 NavigationEntry* NavigationControllerImpl::GetEntryAtOffset(
506 int offset) const {
507 int index = GetIndexForOffset(offset);
508 if (index < 0 || index >= GetEntryCount())
509 return NULL;
511 return entries_[index].get();
514 int NavigationControllerImpl::GetIndexForOffset(int offset) const {
515 return GetCurrentEntryIndex() + offset;
518 void NavigationControllerImpl::TakeScreenshot() {
519 screenshot_manager_->TakeScreenshot();
522 void NavigationControllerImpl::SetScreenshotManager(
523 NavigationEntryScreenshotManager* manager) {
524 screenshot_manager_.reset(manager ? manager :
525 new NavigationEntryScreenshotManager(this));
528 bool NavigationControllerImpl::CanGoBack() const {
529 return entries_.size() > 1 && GetCurrentEntryIndex() > 0;
532 bool NavigationControllerImpl::CanGoForward() const {
533 int index = GetCurrentEntryIndex();
534 return index >= 0 && index < (static_cast<int>(entries_.size()) - 1);
537 bool NavigationControllerImpl::CanGoToOffset(int offset) const {
538 int index = GetIndexForOffset(offset);
539 return index >= 0 && index < GetEntryCount();
542 void NavigationControllerImpl::GoBack() {
543 if (!CanGoBack()) {
544 NOTREACHED();
545 return;
548 // Base the navigation on where we are now...
549 int current_index = GetCurrentEntryIndex();
551 DiscardNonCommittedEntries();
553 pending_entry_index_ = current_index - 1;
554 entries_[pending_entry_index_]->SetTransitionType(
555 PageTransitionFromInt(
556 entries_[pending_entry_index_]->GetTransitionType() |
557 PAGE_TRANSITION_FORWARD_BACK));
558 NavigateToPendingEntry(NO_RELOAD);
561 void NavigationControllerImpl::GoForward() {
562 if (!CanGoForward()) {
563 NOTREACHED();
564 return;
567 bool transient = (transient_entry_index_ != -1);
569 // Base the navigation on where we are now...
570 int current_index = GetCurrentEntryIndex();
572 DiscardNonCommittedEntries();
574 pending_entry_index_ = current_index;
575 // If there was a transient entry, we removed it making the current index
576 // the next page.
577 if (!transient)
578 pending_entry_index_++;
580 entries_[pending_entry_index_]->SetTransitionType(
581 PageTransitionFromInt(
582 entries_[pending_entry_index_]->GetTransitionType() |
583 PAGE_TRANSITION_FORWARD_BACK));
584 NavigateToPendingEntry(NO_RELOAD);
587 void NavigationControllerImpl::GoToIndex(int index) {
588 if (index < 0 || index >= static_cast<int>(entries_.size())) {
589 NOTREACHED();
590 return;
593 if (transient_entry_index_ != -1) {
594 if (index == transient_entry_index_) {
595 // Nothing to do when navigating to the transient.
596 return;
598 if (index > transient_entry_index_) {
599 // Removing the transient is goint to shift all entries by 1.
600 index--;
604 DiscardNonCommittedEntries();
606 pending_entry_index_ = index;
607 entries_[pending_entry_index_]->SetTransitionType(
608 PageTransitionFromInt(
609 entries_[pending_entry_index_]->GetTransitionType() |
610 PAGE_TRANSITION_FORWARD_BACK));
611 NavigateToPendingEntry(NO_RELOAD);
614 void NavigationControllerImpl::GoToOffset(int offset) {
615 if (!CanGoToOffset(offset))
616 return;
618 GoToIndex(GetIndexForOffset(offset));
621 bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
622 if (index == last_committed_entry_index_ ||
623 index == pending_entry_index_)
624 return false;
626 RemoveEntryAtIndexInternal(index);
627 return true;
630 void NavigationControllerImpl::UpdateVirtualURLToURL(
631 NavigationEntryImpl* entry, const GURL& new_url) {
632 GURL new_virtual_url(new_url);
633 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
634 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
635 entry->SetVirtualURL(new_virtual_url);
639 void NavigationControllerImpl::LoadURL(
640 const GURL& url,
641 const Referrer& referrer,
642 PageTransition transition,
643 const std::string& extra_headers) {
644 LoadURLParams params(url);
645 params.referrer = referrer;
646 params.transition_type = transition;
647 params.extra_headers = extra_headers;
648 LoadURLWithParams(params);
651 void NavigationControllerImpl::LoadURLWithParams(const LoadURLParams& params) {
652 TRACE_EVENT1("browser,navigation",
653 "NavigationControllerImpl::LoadURLWithParams",
654 "url", params.url.possibly_invalid_spec());
655 if (HandleDebugURL(params.url, params.transition_type)) {
656 // If Telemetry is running, allow the URL load to proceed as if it's
657 // unhandled, otherwise Telemetry can't tell if Navigation completed.
658 if (!CommandLine::ForCurrentProcess()->HasSwitch(
659 cc::switches::kEnableGpuBenchmarking))
660 return;
663 // Any renderer-side debug URLs or javascript: URLs should be ignored if the
664 // renderer process is not live, unless it is the initial navigation of the
665 // tab.
666 if (IsRendererDebugURL(params.url)) {
667 // TODO(creis): Find the RVH for the correct frame.
668 if (!delegate_->GetRenderViewHost()->IsRenderViewLive() &&
669 !IsInitialNavigation())
670 return;
673 // Checks based on params.load_type.
674 switch (params.load_type) {
675 case LOAD_TYPE_DEFAULT:
676 break;
677 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
678 if (!params.url.SchemeIs(url::kHttpScheme) &&
679 !params.url.SchemeIs(url::kHttpsScheme)) {
680 NOTREACHED() << "Http post load must use http(s) scheme.";
681 return;
683 break;
684 case LOAD_TYPE_DATA:
685 if (!params.url.SchemeIs(url::kDataScheme)) {
686 NOTREACHED() << "Data load must use data scheme.";
687 return;
689 break;
690 default:
691 NOTREACHED();
692 break;
695 // The user initiated a load, we don't need to reload anymore.
696 needs_reload_ = false;
698 bool override = false;
699 switch (params.override_user_agent) {
700 case UA_OVERRIDE_INHERIT:
701 override = ShouldKeepOverride(GetLastCommittedEntry());
702 break;
703 case UA_OVERRIDE_TRUE:
704 override = true;
705 break;
706 case UA_OVERRIDE_FALSE:
707 override = false;
708 break;
709 default:
710 NOTREACHED();
711 break;
714 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
715 CreateNavigationEntry(
716 params.url,
717 params.referrer,
718 params.transition_type,
719 params.is_renderer_initiated,
720 params.extra_headers,
721 browser_context_));
722 if (params.frame_tree_node_id != -1)
723 entry->set_frame_tree_node_id(params.frame_tree_node_id);
724 if (params.redirect_chain.size() > 0)
725 entry->SetRedirectChain(params.redirect_chain);
726 if (params.should_replace_current_entry)
727 entry->set_should_replace_entry(true);
728 entry->set_should_clear_history_list(params.should_clear_history_list);
729 entry->SetIsOverridingUserAgent(override);
730 entry->set_transferred_global_request_id(
731 params.transferred_global_request_id);
732 entry->SetFrameToNavigate(params.frame_name);
734 switch (params.load_type) {
735 case LOAD_TYPE_DEFAULT:
736 break;
737 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
738 entry->SetHasPostData(true);
739 entry->SetBrowserInitiatedPostData(
740 params.browser_initiated_post_data.get());
741 break;
742 case LOAD_TYPE_DATA:
743 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
744 entry->SetVirtualURL(params.virtual_url_for_data_url);
745 entry->SetCanLoadLocalResources(params.can_load_local_resources);
746 break;
747 default:
748 NOTREACHED();
749 break;
752 LoadEntry(entry);
755 bool NavigationControllerImpl::RendererDidNavigate(
756 RenderFrameHost* rfh,
757 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
758 LoadCommittedDetails* details) {
759 is_initial_navigation_ = false;
761 // Save the previous state before we clobber it.
762 if (GetLastCommittedEntry()) {
763 details->previous_url = GetLastCommittedEntry()->GetURL();
764 details->previous_entry_index = GetLastCommittedEntryIndex();
765 } else {
766 details->previous_url = GURL();
767 details->previous_entry_index = -1;
770 // If we have a pending entry at this point, it should have a SiteInstance.
771 // Restored entries start out with a null SiteInstance, but we should have
772 // assigned one in NavigateToPendingEntry.
773 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance());
775 // If we are doing a cross-site reload, we need to replace the existing
776 // navigation entry, not add another entry to the history. This has the side
777 // effect of removing forward browsing history, if such existed.
778 // Or if we are doing a cross-site redirect navigation,
779 // we will do a similar thing.
780 details->did_replace_entry =
781 pending_entry_ && pending_entry_->should_replace_entry();
783 // Do navigation-type specific actions. These will make and commit an entry.
784 details->type = ClassifyNavigation(rfh, params);
786 // is_in_page must be computed before the entry gets committed.
787 details->is_in_page = AreURLsInPageNavigation(rfh->GetLastCommittedURL(),
788 params.url, params.was_within_same_page, rfh);
790 switch (details->type) {
791 case NAVIGATION_TYPE_NEW_PAGE:
792 RendererDidNavigateToNewPage(rfh, params, details->did_replace_entry);
793 break;
794 case NAVIGATION_TYPE_EXISTING_PAGE:
795 RendererDidNavigateToExistingPage(rfh, params);
796 break;
797 case NAVIGATION_TYPE_SAME_PAGE:
798 RendererDidNavigateToSamePage(rfh, params);
799 break;
800 case NAVIGATION_TYPE_IN_PAGE:
801 RendererDidNavigateInPage(rfh, params, &details->did_replace_entry);
802 break;
803 case NAVIGATION_TYPE_NEW_SUBFRAME:
804 RendererDidNavigateNewSubframe(rfh, params);
805 break;
806 case NAVIGATION_TYPE_AUTO_SUBFRAME:
807 if (!RendererDidNavigateAutoSubframe(rfh, params))
808 return false;
809 break;
810 case NAVIGATION_TYPE_NAV_IGNORE:
811 // If a pending navigation was in progress, this canceled it. We should
812 // discard it and make sure it is removed from the URL bar. After that,
813 // there is nothing we can do with this navigation, so we just return to
814 // the caller that nothing has happened.
815 if (pending_entry_) {
816 DiscardNonCommittedEntries();
817 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
819 return false;
820 default:
821 NOTREACHED();
824 // At this point, we know that the navigation has just completed, so
825 // record the time.
827 // TODO(akalin): Use "sane time" as described in
828 // http://www.chromium.org/developers/design-documents/sane-time .
829 base::Time timestamp =
830 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
831 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
832 << timestamp.ToInternalValue();
834 // We should not have a pending entry anymore. Clear it again in case any
835 // error cases above forgot to do so.
836 DiscardNonCommittedEntriesInternal();
838 // All committed entries should have nonempty content state so WebKit doesn't
839 // get confused when we go back to them (see the function for details).
840 DCHECK(params.page_state.IsValid());
841 NavigationEntryImpl* active_entry =
842 NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
843 active_entry->SetTimestamp(timestamp);
844 active_entry->SetHttpStatusCode(params.http_status_code);
845 active_entry->SetPageState(params.page_state);
846 active_entry->SetRedirectChain(params.redirects);
848 // Use histogram to track memory impact of redirect chain because it's now
849 // not cleared for committed entries.
850 size_t redirect_chain_size = 0;
851 for (size_t i = 0; i < params.redirects.size(); ++i) {
852 redirect_chain_size += params.redirects[i].spec().length();
854 UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size);
856 // Once it is committed, we no longer need to track several pieces of state on
857 // the entry.
858 active_entry->ResetForCommit();
860 // The active entry's SiteInstance should match our SiteInstance.
861 // TODO(creis): This check won't pass for subframes until we create entries
862 // for subframe navigations.
863 if (PageTransitionIsMainFrame(params.transition))
864 CHECK(active_entry->site_instance() == rfh->GetSiteInstance());
866 // Remember the bindings the renderer process has at this point, so that
867 // we do not grant this entry additional bindings if we come back to it.
868 active_entry->SetBindings(
869 static_cast<RenderFrameHostImpl*>(rfh)->GetEnabledBindings());
871 // Now prep the rest of the details for the notification and broadcast.
872 details->entry = active_entry;
873 details->is_main_frame =
874 PageTransitionIsMainFrame(params.transition);
875 details->serialized_security_info = params.security_info;
876 details->http_status_code = params.http_status_code;
877 NotifyNavigationEntryCommitted(details);
879 return true;
882 NavigationType NavigationControllerImpl::ClassifyNavigation(
883 RenderFrameHost* rfh,
884 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) const {
885 if (params.page_id == -1) {
886 // TODO(nasko, creis): An out-of-process child frame has no way of
887 // knowing the page_id of its parent, so it is passing back -1. The
888 // semantics here should be re-evaluated during session history refactor
889 // (see http://crbug.com/236848). For now, we assume this means the
890 // child frame loaded and proceed. Note that this may do the wrong thing
891 // for cross-process AUTO_SUBFRAME navigations.
892 if (rfh->IsCrossProcessSubframe())
893 return NAVIGATION_TYPE_NEW_SUBFRAME;
895 // The renderer generates the page IDs, and so if it gives us the invalid
896 // page ID (-1) we know it didn't actually navigate. This happens in a few
897 // cases:
899 // - If a page makes a popup navigated to about blank, and then writes
900 // stuff like a subframe navigated to a real page. We'll get the commit
901 // for the subframe, but there won't be any commit for the outer page.
903 // - We were also getting these for failed loads (for example, bug 21849).
904 // The guess is that we get a "load commit" for the alternate error page,
905 // but that doesn't affect the page ID, so we get the "old" one, which
906 // could be invalid. This can also happen for a cross-site transition
907 // that causes us to swap processes. Then the error page load will be in
908 // a new process with no page IDs ever assigned (and hence a -1 value),
909 // yet the navigation controller still might have previous pages in its
910 // list.
912 // In these cases, there's nothing we can do with them, so ignore.
913 return NAVIGATION_TYPE_NAV_IGNORE;
916 if (params.page_id > delegate_->GetMaxPageIDForSiteInstance(
917 rfh->GetSiteInstance())) {
918 // Greater page IDs than we've ever seen before are new pages. We may or may
919 // not have a pending entry for the page, and this may or may not be the
920 // main frame.
921 if (PageTransitionIsMainFrame(params.transition))
922 return NAVIGATION_TYPE_NEW_PAGE;
924 // When this is a new subframe navigation, we should have a committed page
925 // for which it's a suframe in. This may not be the case when an iframe is
926 // navigated on a popup navigated to about:blank (the iframe would be
927 // written into the popup by script on the main page). For these cases,
928 // there isn't any navigation stuff we can do, so just ignore it.
929 if (!GetLastCommittedEntry())
930 return NAVIGATION_TYPE_NAV_IGNORE;
932 // Valid subframe navigation.
933 return NAVIGATION_TYPE_NEW_SUBFRAME;
936 // We only clear the session history when navigating to a new page.
937 DCHECK(!params.history_list_was_cleared);
939 // Now we know that the notification is for an existing page. Find that entry.
940 int existing_entry_index = GetEntryIndexWithPageID(
941 rfh->GetSiteInstance(),
942 params.page_id);
943 if (existing_entry_index == -1) {
944 // The page was not found. It could have been pruned because of the limit on
945 // back/forward entries (not likely since we'll usually tell it to navigate
946 // to such entries). It could also mean that the renderer is smoking crack.
947 NOTREACHED();
949 // Because the unknown entry has committed, we risk showing the wrong URL in
950 // release builds. Instead, we'll kill the renderer process to be safe.
951 LOG(ERROR) << "terminating renderer for bad navigation: " << params.url;
952 RecordAction(base::UserMetricsAction("BadMessageTerminate_NC"));
954 // Temporary code so we can get more information. Format:
955 // http://url/foo.html#page1#max3#frame1#ids:2_Nx,1_1x,3_2
956 std::string temp = params.url.spec();
957 temp.append("#page");
958 temp.append(base::IntToString(params.page_id));
959 temp.append("#max");
960 temp.append(base::IntToString(delegate_->GetMaxPageID()));
961 temp.append("#frame");
962 temp.append(base::IntToString(rfh->GetRoutingID()));
963 temp.append("#ids");
964 for (int i = 0; i < static_cast<int>(entries_.size()); ++i) {
965 // Append entry metadata (e.g., 3_7x):
966 // 3: page_id
967 // 7: SiteInstance ID, or N for null
968 // x: appended if not from the current SiteInstance
969 temp.append(base::IntToString(entries_[i]->GetPageID()));
970 temp.append("_");
971 if (entries_[i]->site_instance())
972 temp.append(base::IntToString(entries_[i]->site_instance()->GetId()));
973 else
974 temp.append("N");
975 if (entries_[i]->site_instance() != rfh->GetSiteInstance())
976 temp.append("x");
977 temp.append(",");
979 GURL url(temp);
980 static_cast<RenderFrameHostImpl*>(rfh)->render_view_host()->Send(
981 new ViewMsg_TempCrashWithData(url));
982 return NAVIGATION_TYPE_NAV_IGNORE;
984 NavigationEntryImpl* existing_entry = entries_[existing_entry_index].get();
986 if (!PageTransitionIsMainFrame(params.transition)) {
987 // All manual subframes would get new IDs and were handled above, so we
988 // know this is auto. Since the current page was found in the navigation
989 // entry list, we're guaranteed to have a last committed entry.
990 DCHECK(GetLastCommittedEntry());
991 return NAVIGATION_TYPE_AUTO_SUBFRAME;
994 // Anything below here we know is a main frame navigation.
995 if (pending_entry_ &&
996 !pending_entry_->is_renderer_initiated() &&
997 existing_entry != pending_entry_ &&
998 pending_entry_->GetPageID() == -1 &&
999 existing_entry == GetLastCommittedEntry()) {
1000 // In this case, we have a pending entry for a URL but WebCore didn't do a
1001 // new navigation. This happens when you press enter in the URL bar to
1002 // reload. We will create a pending entry, but WebKit will convert it to
1003 // a reload since it's the same page and not create a new entry for it
1004 // (the user doesn't want to have a new back/forward entry when they do
1005 // this). If this matches the last committed entry, we want to just ignore
1006 // the pending entry and go back to where we were (the "existing entry").
1007 return NAVIGATION_TYPE_SAME_PAGE;
1010 // Any toplevel navigations with the same base (minus the reference fragment)
1011 // are in-page navigations. We weeded out subframe navigations above. Most of
1012 // the time this doesn't matter since WebKit doesn't tell us about subframe
1013 // navigations that don't actually navigate, but it can happen when there is
1014 // an encoding override (it always sends a navigation request).
1015 if (AreURLsInPageNavigation(existing_entry->GetURL(), params.url,
1016 params.was_within_same_page, rfh)) {
1017 return NAVIGATION_TYPE_IN_PAGE;
1020 // Since we weeded out "new" navigations above, we know this is an existing
1021 // (back/forward) navigation.
1022 return NAVIGATION_TYPE_EXISTING_PAGE;
1025 void NavigationControllerImpl::RendererDidNavigateToNewPage(
1026 RenderFrameHost* rfh,
1027 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
1028 bool replace_entry) {
1029 NavigationEntryImpl* new_entry;
1030 bool update_virtual_url;
1031 // Only make a copy of the pending entry if it is appropriate for the new page
1032 // that was just loaded. We verify this at a coarse grain by checking that
1033 // the SiteInstance hasn't been assigned to something else.
1034 if (pending_entry_ &&
1035 (!pending_entry_->site_instance() ||
1036 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
1037 new_entry = new NavigationEntryImpl(*pending_entry_);
1039 // Don't use the page type from the pending entry. Some interstitial page
1040 // may have set the type to interstitial. Once we commit, however, the page
1041 // type must always be normal.
1042 new_entry->set_page_type(PAGE_TYPE_NORMAL);
1043 update_virtual_url = new_entry->update_virtual_url_with_url();
1044 } else {
1045 new_entry = new NavigationEntryImpl;
1047 // Find out whether the new entry needs to update its virtual URL on URL
1048 // change and set up the entry accordingly. This is needed to correctly
1049 // update the virtual URL when replaceState is called after a pushState.
1050 GURL url = params.url;
1051 bool needs_update = false;
1052 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1053 &url, browser_context_, &needs_update);
1054 new_entry->set_update_virtual_url_with_url(needs_update);
1056 // When navigating to a new page, give the browser URL handler a chance to
1057 // update the virtual URL based on the new URL. For example, this is needed
1058 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1059 // the URL.
1060 update_virtual_url = needs_update;
1063 new_entry->SetURL(params.url);
1064 if (update_virtual_url)
1065 UpdateVirtualURLToURL(new_entry, params.url);
1066 new_entry->SetReferrer(params.referrer);
1067 new_entry->SetPageID(params.page_id);
1068 new_entry->SetTransitionType(params.transition);
1069 new_entry->set_site_instance(
1070 static_cast<SiteInstanceImpl*>(rfh->GetSiteInstance()));
1071 new_entry->SetHasPostData(params.is_post);
1072 new_entry->SetPostID(params.post_id);
1073 new_entry->SetOriginalRequestURL(params.original_request_url);
1074 new_entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1076 // history.pushState() is classified as a navigation to a new page, but
1077 // sets was_within_same_page to true. In this case, we already have the
1078 // title and favicon available, so set them immediately.
1079 if (params.was_within_same_page && GetLastCommittedEntry()) {
1080 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
1081 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
1084 DCHECK(!params.history_list_was_cleared || !replace_entry);
1085 // The browser requested to clear the session history when it initiated the
1086 // navigation. Now we know that the renderer has updated its state accordingly
1087 // and it is safe to also clear the browser side history.
1088 if (params.history_list_was_cleared) {
1089 DiscardNonCommittedEntriesInternal();
1090 entries_.clear();
1091 last_committed_entry_index_ = -1;
1094 InsertOrReplaceEntry(new_entry, replace_entry);
1097 void NavigationControllerImpl::RendererDidNavigateToExistingPage(
1098 RenderFrameHost* rfh,
1099 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1100 // We should only get here for main frame navigations.
1101 DCHECK(PageTransitionIsMainFrame(params.transition));
1103 // This is a back/forward navigation. The existing page for the ID is
1104 // guaranteed to exist by ClassifyNavigation, and we just need to update it
1105 // with new information from the renderer.
1106 int entry_index = GetEntryIndexWithPageID(rfh->GetSiteInstance(),
1107 params.page_id);
1108 DCHECK(entry_index >= 0 &&
1109 entry_index < static_cast<int>(entries_.size()));
1110 NavigationEntryImpl* entry = entries_[entry_index].get();
1112 // The URL may have changed due to redirects.
1113 entry->SetURL(params.url);
1114 entry->SetReferrer(params.referrer);
1115 if (entry->update_virtual_url_with_url())
1116 UpdateVirtualURLToURL(entry, params.url);
1118 // The redirected to page should not inherit the favicon from the previous
1119 // page.
1120 if (PageTransitionIsRedirect(params.transition))
1121 entry->GetFavicon() = FaviconStatus();
1123 // The site instance will normally be the same except during session restore,
1124 // when no site instance will be assigned.
1125 DCHECK(entry->site_instance() == NULL ||
1126 entry->site_instance() == rfh->GetSiteInstance());
1127 entry->set_site_instance(
1128 static_cast<SiteInstanceImpl*>(rfh->GetSiteInstance()));
1130 entry->SetHasPostData(params.is_post);
1131 entry->SetPostID(params.post_id);
1133 // The entry we found in the list might be pending if the user hit
1134 // back/forward/reload. This load should commit it (since it's already in the
1135 // list, we can just discard the pending pointer). We should also discard the
1136 // pending entry if it corresponds to a different navigation, since that one
1137 // is now likely canceled. If it is not canceled, we will treat it as a new
1138 // navigation when it arrives, which is also ok.
1140 // Note that we need to use the "internal" version since we don't want to
1141 // actually change any other state, just kill the pointer.
1142 DiscardNonCommittedEntriesInternal();
1144 // If a transient entry was removed, the indices might have changed, so we
1145 // have to query the entry index again.
1146 last_committed_entry_index_ =
1147 GetEntryIndexWithPageID(rfh->GetSiteInstance(), params.page_id);
1150 void NavigationControllerImpl::RendererDidNavigateToSamePage(
1151 RenderFrameHost* rfh,
1152 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1153 // This mode implies we have a pending entry that's the same as an existing
1154 // entry for this page ID. This entry is guaranteed to exist by
1155 // ClassifyNavigation. All we need to do is update the existing entry.
1156 NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1157 rfh->GetSiteInstance(), params.page_id);
1159 // We assign the entry's unique ID to be that of the new one. Since this is
1160 // always the result of a user action, we want to dismiss infobars, etc. like
1161 // a regular user-initiated navigation.
1162 existing_entry->set_unique_id(pending_entry_->GetUniqueID());
1164 // The URL may have changed due to redirects.
1165 if (existing_entry->update_virtual_url_with_url())
1166 UpdateVirtualURLToURL(existing_entry, params.url);
1167 existing_entry->SetURL(params.url);
1168 existing_entry->SetReferrer(params.referrer);
1170 // The page may have been requested with a different HTTP method.
1171 existing_entry->SetHasPostData(params.is_post);
1172 existing_entry->SetPostID(params.post_id);
1174 DiscardNonCommittedEntries();
1177 void NavigationControllerImpl::RendererDidNavigateInPage(
1178 RenderFrameHost* rfh,
1179 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
1180 bool* did_replace_entry) {
1181 DCHECK(PageTransitionIsMainFrame(params.transition)) <<
1182 "WebKit should only tell us about in-page navs for the main frame.";
1183 // We're guaranteed to have an entry for this one.
1184 NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1185 rfh->GetSiteInstance(), params.page_id);
1187 // Reference fragment navigation. We're guaranteed to have the last_committed
1188 // entry and it will be the same page as the new navigation (minus the
1189 // reference fragments, of course). We'll update the URL of the existing
1190 // entry without pruning the forward history.
1191 existing_entry->SetURL(params.url);
1192 if (existing_entry->update_virtual_url_with_url())
1193 UpdateVirtualURLToURL(existing_entry, params.url);
1195 existing_entry->SetHasPostData(params.is_post);
1196 existing_entry->SetPostID(params.post_id);
1198 // This replaces the existing entry since the page ID didn't change.
1199 *did_replace_entry = true;
1201 DiscardNonCommittedEntriesInternal();
1203 // If a transient entry was removed, the indices might have changed, so we
1204 // have to query the entry index again.
1205 last_committed_entry_index_ =
1206 GetEntryIndexWithPageID(rfh->GetSiteInstance(), params.page_id);
1209 void NavigationControllerImpl::RendererDidNavigateNewSubframe(
1210 RenderFrameHost* rfh,
1211 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1212 if (PageTransitionCoreTypeIs(params.transition,
1213 PAGE_TRANSITION_AUTO_SUBFRAME)) {
1214 // This is not user-initiated. Ignore.
1215 DiscardNonCommittedEntriesInternal();
1216 return;
1219 // Manual subframe navigations just get the current entry cloned so the user
1220 // can go back or forward to it. The actual subframe information will be
1221 // stored in the page state for each of those entries. This happens out of
1222 // band with the actual navigations.
1223 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
1224 << "that a last committed entry exists.";
1225 NavigationEntryImpl* new_entry = new NavigationEntryImpl(
1226 *NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry()));
1227 new_entry->SetPageID(params.page_id);
1228 InsertOrReplaceEntry(new_entry, false);
1231 bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
1232 RenderFrameHost* rfh,
1233 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1234 // We're guaranteed to have a previously committed entry, and we now need to
1235 // handle navigation inside of a subframe in it without creating a new entry.
1236 DCHECK(GetLastCommittedEntry());
1238 // Handle the case where we're navigating back/forward to a previous subframe
1239 // navigation entry. This is case "2." in NAV_AUTO_SUBFRAME comment in the
1240 // header file. In case "1." this will be a NOP.
1241 int entry_index = GetEntryIndexWithPageID(
1242 rfh->GetSiteInstance(),
1243 params.page_id);
1244 if (entry_index < 0 ||
1245 entry_index >= static_cast<int>(entries_.size())) {
1246 NOTREACHED();
1247 return false;
1250 // Update the current navigation entry in case we're going back/forward.
1251 if (entry_index != last_committed_entry_index_) {
1252 last_committed_entry_index_ = entry_index;
1253 DiscardNonCommittedEntriesInternal();
1254 return true;
1257 // We do not need to discard the pending entry in this case, since we will
1258 // not generate commit notifications for this auto-subframe navigation.
1259 return false;
1262 int NavigationControllerImpl::GetIndexOfEntry(
1263 const NavigationEntryImpl* entry) const {
1264 const NavigationEntries::const_iterator i(std::find(
1265 entries_.begin(),
1266 entries_.end(),
1267 entry));
1268 return (i == entries_.end()) ? -1 : static_cast<int>(i - entries_.begin());
1271 bool NavigationControllerImpl::IsURLInPageNavigation(
1272 const GURL& url,
1273 bool renderer_says_in_page,
1274 RenderFrameHost* rfh) const {
1275 NavigationEntry* last_committed = GetLastCommittedEntry();
1276 return last_committed && AreURLsInPageNavigation(
1277 last_committed->GetURL(), url, renderer_says_in_page, rfh);
1280 void NavigationControllerImpl::CopyStateFrom(
1281 const NavigationController& temp) {
1282 const NavigationControllerImpl& source =
1283 static_cast<const NavigationControllerImpl&>(temp);
1284 // Verify that we look new.
1285 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
1287 if (source.GetEntryCount() == 0)
1288 return; // Nothing new to do.
1290 needs_reload_ = true;
1291 InsertEntriesFrom(source, source.GetEntryCount());
1293 for (SessionStorageNamespaceMap::const_iterator it =
1294 source.session_storage_namespace_map_.begin();
1295 it != source.session_storage_namespace_map_.end();
1296 ++it) {
1297 SessionStorageNamespaceImpl* source_namespace =
1298 static_cast<SessionStorageNamespaceImpl*>(it->second.get());
1299 session_storage_namespace_map_[it->first] = source_namespace->Clone();
1302 FinishRestore(source.last_committed_entry_index_, RESTORE_CURRENT_SESSION);
1304 // Copy the max page id map from the old tab to the new tab. This ensures
1305 // that new and existing navigations in the tab's current SiteInstances
1306 // are identified properly.
1307 delegate_->CopyMaxPageIDsFrom(source.delegate()->GetWebContents());
1310 void NavigationControllerImpl::CopyStateFromAndPrune(
1311 NavigationController* temp,
1312 bool replace_entry) {
1313 // It is up to callers to check the invariants before calling this.
1314 CHECK(CanPruneAllButLastCommitted());
1316 NavigationControllerImpl* source =
1317 static_cast<NavigationControllerImpl*>(temp);
1318 // The SiteInstance and page_id of the last committed entry needs to be
1319 // remembered at this point, in case there is only one committed entry
1320 // and it is pruned. We use a scoped_refptr to ensure the SiteInstance
1321 // can't be freed during this time period.
1322 NavigationEntryImpl* last_committed =
1323 NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
1324 scoped_refptr<SiteInstance> site_instance(
1325 last_committed->site_instance());
1326 int32 minimum_page_id = last_committed->GetPageID();
1327 int32 max_page_id =
1328 delegate_->GetMaxPageIDForSiteInstance(site_instance.get());
1330 // Remove all the entries leaving the active entry.
1331 PruneAllButLastCommittedInternal();
1333 // We now have one entry, possibly with a new pending entry. Ensure that
1334 // adding the entries from source won't put us over the limit.
1335 DCHECK_EQ(1, GetEntryCount());
1336 if (!replace_entry)
1337 source->PruneOldestEntryIfFull();
1339 // Insert the entries from source. Don't use source->GetCurrentEntryIndex as
1340 // we don't want to copy over the transient entry. Ignore any pending entry,
1341 // since it has not committed in source.
1342 int max_source_index = source->last_committed_entry_index_;
1343 if (max_source_index == -1)
1344 max_source_index = source->GetEntryCount();
1345 else
1346 max_source_index++;
1348 // Ignore the source's current entry if merging with replacement.
1349 // TODO(davidben): This should preserve entries forward of the current
1350 // too. http://crbug.com/317872
1351 if (replace_entry && max_source_index > 0)
1352 max_source_index--;
1354 InsertEntriesFrom(*source, max_source_index);
1356 // Adjust indices such that the last entry and pending are at the end now.
1357 last_committed_entry_index_ = GetEntryCount() - 1;
1359 delegate_->SetHistoryLengthAndPrune(site_instance.get(),
1360 max_source_index,
1361 minimum_page_id);
1363 // Copy the max page id map from the old tab to the new tab. This ensures
1364 // that new and existing navigations in the tab's current SiteInstances
1365 // are identified properly.
1366 delegate_->CopyMaxPageIDsFrom(source->delegate()->GetWebContents());
1367 max_restored_page_id_ = source->max_restored_page_id_;
1369 // If there is a last committed entry, be sure to include it in the new
1370 // max page ID map.
1371 if (max_page_id > -1) {
1372 delegate_->UpdateMaxPageIDForSiteInstance(site_instance.get(),
1373 max_page_id);
1377 bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
1378 // If there is no last committed entry, we cannot prune. Even if there is a
1379 // pending entry, it may not commit, leaving this WebContents blank, despite
1380 // possibly giving it new entries via CopyStateFromAndPrune.
1381 if (last_committed_entry_index_ == -1)
1382 return false;
1384 // We cannot prune if there is a pending entry at an existing entry index.
1385 // It may not commit, so we have to keep the last committed entry, and thus
1386 // there is no sensible place to keep the pending entry. It is ok to have
1387 // a new pending entry, which can optionally commit as a new navigation.
1388 if (pending_entry_index_ != -1)
1389 return false;
1391 // We should not prune if we are currently showing a transient entry.
1392 if (transient_entry_index_ != -1)
1393 return false;
1395 return true;
1398 void NavigationControllerImpl::PruneAllButLastCommitted() {
1399 PruneAllButLastCommittedInternal();
1401 // We should still have a last committed entry.
1402 DCHECK_NE(-1, last_committed_entry_index_);
1404 // We pass 0 instead of GetEntryCount() for the history_length parameter of
1405 // SetHistoryLengthAndPrune, because it will create history_length additional
1406 // history entries.
1407 // TODO(jochen): This API is confusing and we should clean it up.
1408 // http://crbug.com/178491
1409 NavigationEntryImpl* entry =
1410 NavigationEntryImpl::FromNavigationEntry(GetVisibleEntry());
1411 delegate_->SetHistoryLengthAndPrune(
1412 entry->site_instance(), 0, entry->GetPageID());
1415 void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
1416 // It is up to callers to check the invariants before calling this.
1417 CHECK(CanPruneAllButLastCommitted());
1419 // Erase all entries but the last committed entry. There may still be a
1420 // new pending entry after this.
1421 entries_.erase(entries_.begin(),
1422 entries_.begin() + last_committed_entry_index_);
1423 entries_.erase(entries_.begin() + 1, entries_.end());
1424 last_committed_entry_index_ = 0;
1427 void NavigationControllerImpl::ClearAllScreenshots() {
1428 screenshot_manager_->ClearAllScreenshots();
1431 void NavigationControllerImpl::SetSessionStorageNamespace(
1432 const std::string& partition_id,
1433 SessionStorageNamespace* session_storage_namespace) {
1434 if (!session_storage_namespace)
1435 return;
1437 // We can't overwrite an existing SessionStorage without violating spec.
1438 // Attempts to do so may give a tab access to another tab's session storage
1439 // so die hard on an error.
1440 bool successful_insert = session_storage_namespace_map_.insert(
1441 make_pair(partition_id,
1442 static_cast<SessionStorageNamespaceImpl*>(
1443 session_storage_namespace)))
1444 .second;
1445 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
1448 void NavigationControllerImpl::SetMaxRestoredPageID(int32 max_id) {
1449 max_restored_page_id_ = max_id;
1452 int32 NavigationControllerImpl::GetMaxRestoredPageID() const {
1453 return max_restored_page_id_;
1456 bool NavigationControllerImpl::IsUnmodifiedBlankTab() const {
1457 return IsInitialNavigation() &&
1458 !GetLastCommittedEntry() &&
1459 !delegate_->HasAccessedInitialDocument();
1462 SessionStorageNamespace*
1463 NavigationControllerImpl::GetSessionStorageNamespace(SiteInstance* instance) {
1464 std::string partition_id;
1465 if (instance) {
1466 // TODO(ajwong): When GetDefaultSessionStorageNamespace() goes away, remove
1467 // this if statement so |instance| must not be NULL.
1468 partition_id =
1469 GetContentClient()->browser()->GetStoragePartitionIdForSite(
1470 browser_context_, instance->GetSiteURL());
1473 SessionStorageNamespaceMap::const_iterator it =
1474 session_storage_namespace_map_.find(partition_id);
1475 if (it != session_storage_namespace_map_.end())
1476 return it->second.get();
1478 // Create one if no one has accessed session storage for this partition yet.
1480 // TODO(ajwong): Should this use the |partition_id| directly rather than
1481 // re-lookup via |instance|? http://crbug.com/142685
1482 StoragePartition* partition =
1483 BrowserContext::GetStoragePartition(browser_context_, instance);
1484 SessionStorageNamespaceImpl* session_storage_namespace =
1485 new SessionStorageNamespaceImpl(
1486 static_cast<DOMStorageContextWrapper*>(
1487 partition->GetDOMStorageContext()));
1488 session_storage_namespace_map_[partition_id] = session_storage_namespace;
1490 return session_storage_namespace;
1493 SessionStorageNamespace*
1494 NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
1495 // TODO(ajwong): Remove if statement in GetSessionStorageNamespace().
1496 return GetSessionStorageNamespace(NULL);
1499 const SessionStorageNamespaceMap&
1500 NavigationControllerImpl::GetSessionStorageNamespaceMap() const {
1501 return session_storage_namespace_map_;
1504 bool NavigationControllerImpl::NeedsReload() const {
1505 return needs_reload_;
1508 void NavigationControllerImpl::SetNeedsReload() {
1509 needs_reload_ = true;
1512 void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
1513 DCHECK(index < GetEntryCount());
1514 DCHECK(index != last_committed_entry_index_);
1516 DiscardNonCommittedEntries();
1518 entries_.erase(entries_.begin() + index);
1519 if (last_committed_entry_index_ > index)
1520 last_committed_entry_index_--;
1523 void NavigationControllerImpl::DiscardNonCommittedEntries() {
1524 bool transient = transient_entry_index_ != -1;
1525 DiscardNonCommittedEntriesInternal();
1527 // If there was a transient entry, invalidate everything so the new active
1528 // entry state is shown.
1529 if (transient) {
1530 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
1534 NavigationEntry* NavigationControllerImpl::GetPendingEntry() const {
1535 return pending_entry_;
1538 int NavigationControllerImpl::GetPendingEntryIndex() const {
1539 return pending_entry_index_;
1542 void NavigationControllerImpl::InsertOrReplaceEntry(NavigationEntryImpl* entry,
1543 bool replace) {
1544 DCHECK(entry->GetTransitionType() != PAGE_TRANSITION_AUTO_SUBFRAME);
1546 // Copy the pending entry's unique ID to the committed entry.
1547 // I don't know if pending_entry_index_ can be other than -1 here.
1548 const NavigationEntryImpl* const pending_entry =
1549 (pending_entry_index_ == -1) ?
1550 pending_entry_ : entries_[pending_entry_index_].get();
1551 if (pending_entry)
1552 entry->set_unique_id(pending_entry->GetUniqueID());
1554 DiscardNonCommittedEntriesInternal();
1556 int current_size = static_cast<int>(entries_.size());
1558 if (current_size > 0) {
1559 // Prune any entries which are in front of the current entry.
1560 // Also prune the current entry if we are to replace the current entry.
1561 // last_committed_entry_index_ must be updated here since calls to
1562 // NotifyPrunedEntries() below may re-enter and we must make sure
1563 // last_committed_entry_index_ is not left in an invalid state.
1564 if (replace)
1565 --last_committed_entry_index_;
1567 int num_pruned = 0;
1568 while (last_committed_entry_index_ < (current_size - 1)) {
1569 num_pruned++;
1570 entries_.pop_back();
1571 current_size--;
1573 if (num_pruned > 0) // Only notify if we did prune something.
1574 NotifyPrunedEntries(this, false, num_pruned);
1577 PruneOldestEntryIfFull();
1579 entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
1580 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
1582 // This is a new page ID, so we need everybody to know about it.
1583 delegate_->UpdateMaxPageID(entry->GetPageID());
1586 void NavigationControllerImpl::PruneOldestEntryIfFull() {
1587 if (entries_.size() >= max_entry_count()) {
1588 DCHECK_EQ(max_entry_count(), entries_.size());
1589 DCHECK_GT(last_committed_entry_index_, 0);
1590 RemoveEntryAtIndex(0);
1591 NotifyPrunedEntries(this, true, 1);
1595 void NavigationControllerImpl::NavigateToPendingEntry(ReloadType reload_type) {
1596 needs_reload_ = false;
1598 // If we were navigating to a slow-to-commit page, and the user performs
1599 // a session history navigation to the last committed page, RenderViewHost
1600 // will force the throbber to start, but WebKit will essentially ignore the
1601 // navigation, and won't send a message to stop the throbber. To prevent this
1602 // from happening, we drop the navigation here and stop the slow-to-commit
1603 // page from loading (which would normally happen during the navigation).
1604 if (pending_entry_index_ != -1 &&
1605 pending_entry_index_ == last_committed_entry_index_ &&
1606 (entries_[pending_entry_index_]->restore_type() ==
1607 NavigationEntryImpl::RESTORE_NONE) &&
1608 (entries_[pending_entry_index_]->GetTransitionType() &
1609 PAGE_TRANSITION_FORWARD_BACK)) {
1610 delegate_->Stop();
1612 // If an interstitial page is showing, we want to close it to get back
1613 // to what was showing before.
1614 if (delegate_->GetInterstitialPage())
1615 delegate_->GetInterstitialPage()->DontProceed();
1617 DiscardNonCommittedEntries();
1618 return;
1621 // If an interstitial page is showing, the previous renderer is blocked and
1622 // cannot make new requests. Unblock (and disable) it to allow this
1623 // navigation to succeed. The interstitial will stay visible until the
1624 // resulting DidNavigate.
1625 if (delegate_->GetInterstitialPage()) {
1626 static_cast<InterstitialPageImpl*>(delegate_->GetInterstitialPage())->
1627 CancelForNavigation();
1630 // For session history navigations only the pending_entry_index_ is set.
1631 if (!pending_entry_) {
1632 DCHECK_NE(pending_entry_index_, -1);
1633 pending_entry_ = entries_[pending_entry_index_].get();
1636 // This call does not support re-entrancy. See http://crbug.com/347742.
1637 CHECK(!in_navigate_to_pending_entry_);
1638 in_navigate_to_pending_entry_ = true;
1639 bool success = delegate_->NavigateToPendingEntry(reload_type);
1640 in_navigate_to_pending_entry_ = false;
1642 if (!success)
1643 DiscardNonCommittedEntries();
1645 // If the entry is being restored and doesn't have a SiteInstance yet, fill
1646 // it in now that we know. This allows us to find the entry when it commits.
1647 if (pending_entry_ && !pending_entry_->site_instance() &&
1648 pending_entry_->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
1649 pending_entry_->set_site_instance(static_cast<SiteInstanceImpl*>(
1650 delegate_->GetPendingSiteInstance()));
1651 pending_entry_->set_restore_type(NavigationEntryImpl::RESTORE_NONE);
1655 void NavigationControllerImpl::NotifyNavigationEntryCommitted(
1656 LoadCommittedDetails* details) {
1657 details->entry = GetLastCommittedEntry();
1659 // We need to notify the ssl_manager_ before the web_contents_ so the
1660 // location bar will have up-to-date information about the security style
1661 // when it wants to draw. See http://crbug.com/11157
1662 ssl_manager_.DidCommitProvisionalLoad(*details);
1664 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
1665 delegate_->NotifyNavigationEntryCommitted(*details);
1667 // TODO(avi): Remove. http://crbug.com/170921
1668 NotificationDetails notification_details =
1669 Details<LoadCommittedDetails>(details);
1670 NotificationService::current()->Notify(
1671 NOTIFICATION_NAV_ENTRY_COMMITTED,
1672 Source<NavigationController>(this),
1673 notification_details);
1676 // static
1677 size_t NavigationControllerImpl::max_entry_count() {
1678 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
1679 return max_entry_count_for_testing_;
1680 return kMaxSessionHistoryEntries;
1683 void NavigationControllerImpl::SetActive(bool is_active) {
1684 if (is_active && needs_reload_)
1685 LoadIfNecessary();
1688 void NavigationControllerImpl::LoadIfNecessary() {
1689 if (!needs_reload_)
1690 return;
1692 // Calling Reload() results in ignoring state, and not loading.
1693 // Explicitly use NavigateToPendingEntry so that the renderer uses the
1694 // cached state.
1695 pending_entry_index_ = last_committed_entry_index_;
1696 NavigateToPendingEntry(NO_RELOAD);
1699 void NavigationControllerImpl::NotifyEntryChanged(const NavigationEntry* entry,
1700 int index) {
1701 EntryChangedDetails det;
1702 det.changed_entry = entry;
1703 det.index = index;
1704 NotificationService::current()->Notify(
1705 NOTIFICATION_NAV_ENTRY_CHANGED,
1706 Source<NavigationController>(this),
1707 Details<EntryChangedDetails>(&det));
1710 void NavigationControllerImpl::FinishRestore(int selected_index,
1711 RestoreType type) {
1712 DCHECK(selected_index >= 0 && selected_index < GetEntryCount());
1713 ConfigureEntriesForRestore(&entries_, type);
1715 SetMaxRestoredPageID(static_cast<int32>(GetEntryCount()));
1717 last_committed_entry_index_ = selected_index;
1720 void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
1721 DiscardPendingEntry();
1722 DiscardTransientEntry();
1725 void NavigationControllerImpl::DiscardPendingEntry() {
1726 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
1727 // progress, since this will cause a use-after-free. (We only allow this
1728 // when the tab is being destroyed for shutdown, since it won't return to
1729 // NavigateToEntry in that case.) http://crbug.com/347742.
1730 CHECK(!in_navigate_to_pending_entry_ || delegate_->IsBeingDestroyed());
1732 if (pending_entry_index_ == -1)
1733 delete pending_entry_;
1734 pending_entry_ = NULL;
1735 pending_entry_index_ = -1;
1738 void NavigationControllerImpl::DiscardTransientEntry() {
1739 if (transient_entry_index_ == -1)
1740 return;
1741 entries_.erase(entries_.begin() + transient_entry_index_);
1742 if (last_committed_entry_index_ > transient_entry_index_)
1743 last_committed_entry_index_--;
1744 transient_entry_index_ = -1;
1747 int NavigationControllerImpl::GetEntryIndexWithPageID(
1748 SiteInstance* instance, int32 page_id) const {
1749 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
1750 if ((entries_[i]->site_instance() == instance) &&
1751 (entries_[i]->GetPageID() == page_id))
1752 return i;
1754 return -1;
1757 NavigationEntry* NavigationControllerImpl::GetTransientEntry() const {
1758 if (transient_entry_index_ == -1)
1759 return NULL;
1760 return entries_[transient_entry_index_].get();
1763 void NavigationControllerImpl::SetTransientEntry(NavigationEntry* entry) {
1764 // Discard any current transient entry, we can only have one at a time.
1765 int index = 0;
1766 if (last_committed_entry_index_ != -1)
1767 index = last_committed_entry_index_ + 1;
1768 DiscardTransientEntry();
1769 entries_.insert(
1770 entries_.begin() + index, linked_ptr<NavigationEntryImpl>(
1771 NavigationEntryImpl::FromNavigationEntry(entry)));
1772 transient_entry_index_ = index;
1773 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
1776 void NavigationControllerImpl::InsertEntriesFrom(
1777 const NavigationControllerImpl& source,
1778 int max_index) {
1779 DCHECK_LE(max_index, source.GetEntryCount());
1780 size_t insert_index = 0;
1781 for (int i = 0; i < max_index; i++) {
1782 // When cloning a tab, copy all entries except interstitial pages
1783 if (source.entries_[i].get()->GetPageType() !=
1784 PAGE_TYPE_INTERSTITIAL) {
1785 entries_.insert(entries_.begin() + insert_index++,
1786 linked_ptr<NavigationEntryImpl>(
1787 new NavigationEntryImpl(*source.entries_[i])));
1792 void NavigationControllerImpl::SetGetTimestampCallbackForTest(
1793 const base::Callback<base::Time()>& get_timestamp_callback) {
1794 get_timestamp_callback_ = get_timestamp_callback;
1797 } // namespace content