navigation_controller_impl.cc revision 116680a4aac90f2aa7413d9095a592090648e557
1663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// Copyright 2013 The Chromium Authors. All rights reserved.
2663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// Use of this source code is governed by a BSD-style license that can be
3663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// found in the LICENSE file.
4663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
5663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/browser/frame_host/navigation_controller_impl.h"
6663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
7663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "base/bind.h"
8663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "base/command_line.h"
9663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "base/debug/trace_event.h"
10663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "base/logging.h"
11663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "base/metrics/histogram.h"
12663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "base/strings/string_number_conversions.h"  // Temporary
13663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "base/strings/string_util.h"
14663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "base/strings/utf_string_conversions.h"
15663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "base/time/time.h"
16663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "cc/base/switches.h"
17663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/browser/browser_url_handler_impl.h"
18663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
19663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/browser/dom_storage/session_storage_namespace_impl.h"
20663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/browser/frame_host/debug_urls.h"
21663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/browser/frame_host/interstitial_page_impl.h"
22663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/browser/frame_host/navigation_entry_impl.h"
23663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/browser/frame_host/navigation_entry_screenshot_manager.h"
24663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/browser/renderer_host/render_view_host_impl.h"  // Temporary
25663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/browser/site_instance_impl.h"
26663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/common/frame_messages.h"
27663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/common/view_messages.h"
28663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/browser/browser_context.h"
29663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/browser/content_browser_client.h"
30663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/browser/invalidate_type.h"
31663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/browser/navigation_details.h"
32663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/browser/notification_service.h"
33663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/browser/notification_types.h"
34663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/browser/render_widget_host.h"
35663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/browser/render_widget_host_view.h"
36663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/browser/storage_partition.h"
37663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/browser/user_metrics.h"
38663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/common/content_client.h"
39663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "content/public/common/content_constants.h"
40663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "net/base/escape.h"
41663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "net/base/mime_util.h"
42663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "net/base/net_util.h"
43663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "skia/ext/platform_canvas.h"
44663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng#include "url/url_constants.h"
45663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
46663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengnamespace content {
47663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengnamespace {
48663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
49663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengconst unsigned kInvalidateAll = 0xFFFFFFFF;
50663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
51663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// Invoked when entries have been pruned, or removed. For example, if the
52663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// current entries are [google, digg, yahoo], with the current entry google,
53663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// and the user types in cnet, then digg and yahoo are pruned.
54663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
55663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                         bool from_front,
56663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                         int count) {
57663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  PrunedDetails details;
58663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  details.from_front = from_front;
59663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  details.count = count;
60663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  NotificationService::current()->Notify(
61663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      NOTIFICATION_NAV_LIST_PRUNED,
62663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      Source<NavigationController>(nav_controller),
63663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      Details<PrunedDetails>(&details));
64663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
65663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
66663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// Ensure the given NavigationEntry has a valid state, so that WebKit does not
67663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// get confused if we navigate back to it.
68663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//
69663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// An empty state is treated as a new navigation by WebKit, which would mean
70663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// losing the navigation entries and generating a new navigation entry after
71663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// this one. We don't want that. To avoid this we create a valid state which
72663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// WebKit will not treat as a new navigation.
73663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid SetPageStateIfEmpty(NavigationEntryImpl* entry) {
74663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (!entry->GetPageState().IsValid())
75663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    entry->SetPageState(PageState::CreateFromURL(entry->GetURL()));
76663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
77663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
78663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengNavigationEntryImpl::RestoreType ControllerRestoreTypeToEntryType(
79663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    NavigationController::RestoreType type) {
80663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  switch (type) {
81663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    case NavigationController::RESTORE_CURRENT_SESSION:
82663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
83663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    case NavigationController::RESTORE_LAST_SESSION_EXITED_CLEANLY:
84663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      return NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY;
85663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    case NavigationController::RESTORE_LAST_SESSION_CRASHED:
86663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      return NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED;
87663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  }
88663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  NOTREACHED();
89663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
90663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
91663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
92663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// Configure all the NavigationEntries in entries for restore. This resets
93663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// the transition type to reload and makes sure the content state isn't empty.
94663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid ConfigureEntriesForRestore(
95663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    std::vector<linked_ptr<NavigationEntryImpl> >* entries,
96663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    NavigationController::RestoreType type) {
97663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  for (size_t i = 0; i < entries->size(); ++i) {
98663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // Use a transition type of reload so that we don't incorrectly increase
99663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // the typed count.
100663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    (*entries)[i]->SetTransitionType(PAGE_TRANSITION_RELOAD);
101663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    (*entries)[i]->set_restore_type(ControllerRestoreTypeToEntryType(type));
102663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // NOTE(darin): This code is only needed for backwards compat.
103663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    SetPageStateIfEmpty((*entries)[i].get());
104663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  }
105663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
106663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
107663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// There are two general cases where a navigation is in page:
108663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// 1. A fragment navigation, in which the url is kept the same except for the
109663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//    reference fragment.
110663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// 2. A history API navigation (pushState and replaceState). This case is
111663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//    always in-page, but the urls are not guaranteed to match excluding the
112663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//    fragment. The relevant spec allows pushState/replaceState to any URL on
113663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng//    the same origin.
114663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// However, due to reloads, even identical urls are *not* guaranteed to be
115663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// in-page navigations, we have to trust the renderer almost entirely.
116663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// The one thing we do know is that cross-origin navigations will *never* be
117663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// in-page. Therefore, trust the renderer if the URLs are on the same origin,
118663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// and assume the renderer is malicious if a cross-origin navigation claims to
119663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// be in-page.
120663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengbool AreURLsInPageNavigation(const GURL& existing_url,
121663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                             const GURL& new_url,
122663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                             bool renderer_says_in_page,
123663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                             RenderFrameHost* rfh) {
124663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  WebPreferences prefs = rfh->GetRenderViewHost()->GetWebkitPreferences();
125663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  bool is_same_origin = existing_url.is_empty() ||
126663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                        // TODO(japhet): We should only permit navigations
127663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                        // originating from about:blank to be in-page if the
128663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                        // about:blank is the first document that frame loaded.
129663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                        // We don't have sufficient information to identify
130663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                        // that case at the moment, so always allow about:blank
131663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                        // for now.
132663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                        existing_url == GURL(url::kAboutBlankURL) ||
133663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                        existing_url.GetOrigin() == new_url.GetOrigin() ||
134663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                        !prefs.web_security_enabled;
135663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (!is_same_origin && renderer_says_in_page)
136663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      rfh->GetProcess()->ReceivedBadMessage();
137663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return is_same_origin && renderer_says_in_page;
138663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
139663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
140663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// Determines whether or not we should be carrying over a user agent override
141663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// between two NavigationEntries.
142663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengbool ShouldKeepOverride(const NavigationEntry* last_entry) {
143663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return last_entry && last_entry->GetIsOverridingUserAgent();
144663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
145663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
146663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}  // namespace
147663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
148663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// NavigationControllerImpl ----------------------------------------------------
149663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
150663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengconst size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
151663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
152663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// static
153663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengsize_t NavigationControllerImpl::max_entry_count_for_testing_ =
154663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    kMaxEntryCountForTestingNotSet;
155663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
156663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// Should Reload check for post data? The default is true, but is set to false
157663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// when testing.
158663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengstatic bool g_check_for_repost = true;
159663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
160663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// static
161663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengNavigationEntry* NavigationController::CreateNavigationEntry(
162663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      const GURL& url,
163663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      const Referrer& referrer,
164663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      PageTransition transition,
165663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      bool is_renderer_initiated,
166663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      const std::string& extra_headers,
167663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      BrowserContext* browser_context) {
168663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // Allow the browser URL handler to rewrite the URL. This will, for example,
169663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // remove "view-source:" from the beginning of the URL to get the URL that
170663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // will actually be loaded. This real URL won't be shown to the user, just
171663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // used internally.
172663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  GURL loaded_url(url);
173663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  bool reverse_on_redirect = false;
174663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
175663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      &loaded_url, browser_context, &reverse_on_redirect);
176663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
177663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  NavigationEntryImpl* entry = new NavigationEntryImpl(
178663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      NULL,  // The site instance for tabs is sent on navigation
179663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng             // (WebContents::GetSiteInstance).
180663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      -1,
181663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      loaded_url,
182663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      referrer,
183663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      base::string16(),
184663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      transition,
185663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      is_renderer_initiated);
186663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  entry->SetVirtualURL(url);
187663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  entry->set_user_typed_url(url);
188663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  entry->set_update_virtual_url_with_url(reverse_on_redirect);
189663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  entry->set_extra_headers(extra_headers);
190663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return entry;
191663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
192663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
193663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng// static
194663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NavigationController::DisablePromptOnRepost() {
195663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  g_check_for_repost = false;
196663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
197663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
198663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengbase::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
199663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    base::Time t) {
200663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // If |t| is between the water marks, we're in a run of duplicates
201663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // or just getting out of it, so increase the high-water mark to get
202663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // a time that probably hasn't been used before and return it.
203663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (low_water_mark_ <= t && t <= high_water_mark_) {
204663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    high_water_mark_ += base::TimeDelta::FromMicroseconds(1);
205663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return high_water_mark_;
206663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  }
207663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
208663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // Otherwise, we're clear of the last duplicate run, so reset the
209663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // water marks.
210663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  low_water_mark_ = high_water_mark_ = t;
211663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return t;
212663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
213663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
214663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengNavigationControllerImpl::NavigationControllerImpl(
215663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    NavigationControllerDelegate* delegate,
216663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    BrowserContext* browser_context)
217663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    : browser_context_(browser_context),
218663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_entry_(NULL),
219663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      last_committed_entry_index_(-1),
220663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_entry_index_(-1),
221663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      transient_entry_index_(-1),
222663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      delegate_(delegate),
223663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      max_restored_page_id_(-1),
224663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      ssl_manager_(this),
225663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      needs_reload_(false),
226663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      is_initial_navigation_(true),
227663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      in_navigate_to_pending_entry_(false),
228663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_reload_(NO_RELOAD),
229663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      get_timestamp_callback_(base::Bind(&base::Time::Now)),
230663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      screenshot_manager_(new NavigationEntryScreenshotManager(this)) {
231663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  DCHECK(browser_context_);
232663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
233663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
234663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengNavigationControllerImpl::~NavigationControllerImpl() {
235663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  DiscardNonCommittedEntriesInternal();
236663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
237663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
238663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengWebContents* NavigationControllerImpl::GetWebContents() const {
239663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return delegate_->GetWebContents();
240663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
241663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
242663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengBrowserContext* NavigationControllerImpl::GetBrowserContext() const {
243663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return browser_context_;
244663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
245663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
246663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NavigationControllerImpl::SetBrowserContext(
247663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    BrowserContext* browser_context) {
248663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  browser_context_ = browser_context;
249663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
250663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
251663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NavigationControllerImpl::Restore(
252663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    int selected_navigation,
253663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    RestoreType type,
254663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    std::vector<NavigationEntry*>* entries) {
255663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // Verify that this controller is unused and that the input is valid.
256663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
257663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  DCHECK(selected_navigation >= 0 &&
258663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng         selected_navigation < static_cast<int>(entries->size()));
259663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
260663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  needs_reload_ = true;
261663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  for (size_t i = 0; i < entries->size(); ++i) {
262663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    NavigationEntryImpl* entry =
263663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng        NavigationEntryImpl::FromNavigationEntry((*entries)[i]);
264663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
265663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  }
266663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  entries->clear();
267663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
268663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // And finish the restore.
269663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  FinishRestore(selected_navigation, type);
270663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
271663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
272663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NavigationControllerImpl::Reload(bool check_for_repost) {
273663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  ReloadInternal(check_for_repost, RELOAD);
274663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
275663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NavigationControllerImpl::ReloadIgnoringCache(bool check_for_repost) {
276663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  ReloadInternal(check_for_repost, RELOAD_IGNORING_CACHE);
277663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
278663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NavigationControllerImpl::ReloadOriginalRequestURL(bool check_for_repost) {
279663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  ReloadInternal(check_for_repost, RELOAD_ORIGINAL_REQUEST_URL);
280663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
281663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
282663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NavigationControllerImpl::ReloadInternal(bool check_for_repost,
283663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng                                              ReloadType reload_type) {
284663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (transient_entry_index_ != -1) {
285663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // If an interstitial is showing, treat a reload as a navigation to the
286663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // transient entry's URL.
287663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    NavigationEntryImpl* transient_entry =
288663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng        NavigationEntryImpl::FromNavigationEntry(GetTransientEntry());
289663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    if (!transient_entry)
290663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      return;
291663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    LoadURL(transient_entry->GetURL(),
292663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng            Referrer(),
293663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng            PAGE_TRANSITION_RELOAD,
294663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng            transient_entry->extra_headers());
295663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return;
296663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  }
297663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
298663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  NavigationEntryImpl* entry = NULL;
299663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  int current_index = -1;
300663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
301663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // If we are reloading the initial navigation, just use the current
302663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // pending entry.  Otherwise look up the current entry.
303663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (IsInitialNavigation() && pending_entry_) {
304663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    entry = pending_entry_;
305663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // The pending entry might be in entries_ (e.g., after a Clone), so we
306663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // should also update the current_index.
307663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    current_index = pending_entry_index_;
308663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  } else {
309663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    DiscardNonCommittedEntriesInternal();
310663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    current_index = GetCurrentEntryIndex();
311663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    if (current_index != -1) {
312663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      entry = NavigationEntryImpl::FromNavigationEntry(
313663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng          GetEntryAtIndex(current_index));
314663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    }
315663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  }
316663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
317663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // If we are no where, then we can't reload.  TODO(darin): We should add a
318663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // CanReload method.
319663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (!entry)
320663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return;
321663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
322663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (reload_type == NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL &&
323663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
324663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // We may have been redirected when navigating to the current URL.
325663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // Use the URL the user originally intended to visit, if it's valid and if a
326663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // POST wasn't involved; the latter case avoids issues with sending data to
327663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // the wrong page.
328663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    entry->SetURL(entry->GetOriginalRequestURL());
329663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    entry->SetReferrer(Referrer());
330663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  }
331663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
332663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (g_check_for_repost && check_for_repost &&
333663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      entry->GetHasPostData()) {
334663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // The user is asking to reload a page with POST data. Prompt to make sure
335663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // they really want to do this. If they do, the dialog will call us back
336663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // with check_for_repost = false.
337663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    delegate_->NotifyBeforeFormRepostWarningShow();
338663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
339663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    pending_reload_ = reload_type;
340663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    delegate_->ActivateAndShowRepostFormWarningDialog();
341663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  } else {
342663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    if (!IsInitialNavigation())
343663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      DiscardNonCommittedEntriesInternal();
344663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
345663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // If we are reloading an entry that no longer belongs to the current
346663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // site instance (for example, refreshing a page for just installed app),
347663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // the reload must happen in a new process.
348663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // The new entry must have a new page_id and site instance, so it behaves
349663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // as new navigation (which happens to clear forward history).
350663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // Tabs that are discarded due to low memory conditions may not have a site
351663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // instance, and should not be treated as a cross-site reload.
352663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    SiteInstanceImpl* site_instance = entry->site_instance();
353663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    // Permit reloading guests without further checks.
354663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    bool is_isolated_guest = site_instance && site_instance->HasProcess() &&
355663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng        site_instance->GetProcess()->IsIsolatedGuest();
356663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    if (!is_isolated_guest && site_instance &&
357663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng        site_instance->HasWrongProcessForURL(entry->GetURL())) {
358663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      // Create a navigation entry that resembles the current one, but do not
359663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      // copy page id, site instance, content state, or timestamp.
360663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry(
361663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng          CreateNavigationEntry(
362663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng              entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(),
363663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng              false, entry->extra_headers(), browser_context_));
364663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
365663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      // Mark the reload type as NO_RELOAD, so navigation will not be considered
366663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      // a reload in the renderer.
367663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      reload_type = NavigationController::NO_RELOAD;
368663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
369663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      nav_entry->set_should_replace_entry(true);
370663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_entry_ = nav_entry;
371663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    } else {
372663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_entry_ = entry;
373663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_entry_index_ = current_index;
374663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
375663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      // The title of the page being reloaded might have been removed in the
376663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      // meanwhile, so we need to revert to the default title upon reload and
377663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      // invalidate the previously cached title (SetTitle will do both).
378663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      // See Chromium issue 96041.
379663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_entry_->SetTitle(base::string16());
380663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
381663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_entry_->SetTransitionType(PAGE_TRANSITION_RELOAD);
382663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    }
383663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
384663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    NavigateToPendingEntry(reload_type);
385663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  }
386663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
387663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
388663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NavigationControllerImpl::CancelPendingReload() {
389663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  DCHECK(pending_reload_ != NO_RELOAD);
390663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  pending_reload_ = NO_RELOAD;
391663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
392663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
393663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NavigationControllerImpl::ContinuePendingReload() {
394663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (pending_reload_ == NO_RELOAD) {
395663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    NOTREACHED();
396663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  } else {
397663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    ReloadInternal(false, pending_reload_);
398663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    pending_reload_ = NO_RELOAD;
399663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  }
400663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
401663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
402663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengbool NavigationControllerImpl::IsInitialNavigation() const {
403663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return is_initial_navigation_;
404663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
405663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
406663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengNavigationEntryImpl* NavigationControllerImpl::GetEntryWithPageID(
407663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  SiteInstance* instance, int32 page_id) const {
408663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  int index = GetEntryIndexWithPageID(instance, page_id);
409663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return (index != -1) ? entries_[index].get() : NULL;
410663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
411663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
412663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NavigationControllerImpl::LoadEntry(NavigationEntryImpl* entry) {
413663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // When navigating to a new page, we don't know for sure if we will actually
414663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // end up leaving the current page.  The new page load could for example
415663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // result in a download or a 'no content' response (e.g., a mailto: URL).
416663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  SetPendingEntry(entry);
417663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  NavigateToPendingEntry(NO_RELOAD);
418663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
419663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
420663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengvoid NavigationControllerImpl::SetPendingEntry(NavigationEntryImpl* entry) {
421663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  DiscardNonCommittedEntriesInternal();
422663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  pending_entry_ = entry;
423663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  NotificationService::current()->Notify(
424663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      NOTIFICATION_NAV_ENTRY_PENDING,
425663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      Source<NavigationController>(this),
426663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      Details<NavigationEntry>(entry));
427663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
428663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
429663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengNavigationEntry* NavigationControllerImpl::GetActiveEntry() const {
430663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (transient_entry_index_ != -1)
431663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return entries_[transient_entry_index_].get();
432663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (pending_entry_)
433663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return pending_entry_;
434663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return GetLastCommittedEntry();
435663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
436663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
437663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengNavigationEntry* NavigationControllerImpl::GetVisibleEntry() const {
438663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (transient_entry_index_ != -1)
439663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return entries_[transient_entry_index_].get();
440663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // The pending entry is safe to return for new (non-history), browser-
441663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // initiated navigations.  Most renderer-initiated navigations should not
442663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // show the pending entry, to prevent URL spoof attacks.
443663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  //
444663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // We make an exception for renderer-initiated navigations in new tabs, as
445663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // long as no other page has tried to access the initial empty document in
446663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // the new tab.  If another page modifies this blank page, a URL spoof is
447663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // possible, so we must stop showing the pending entry.
448663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  bool safe_to_show_pending =
449663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_entry_ &&
450663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      // Require a new navigation.
451663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_entry_->GetPageID() == -1 &&
452663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      // Require either browser-initiated or an unmodified new tab.
453663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
454663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
455663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // Also allow showing the pending entry for history navigations in a new tab,
456663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // such as Ctrl+Back.  In this case, no existing page is visible and no one
457663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  // can script the new tab before it commits.
458663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (!safe_to_show_pending &&
459663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_entry_ &&
460663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      pending_entry_->GetPageID() != -1 &&
461663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      IsInitialNavigation() &&
462663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      !pending_entry_->is_renderer_initiated())
463663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    safe_to_show_pending = true;
464663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
465663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (safe_to_show_pending)
466663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return pending_entry_;
467663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return GetLastCommittedEntry();
468663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
469663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
470663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengint NavigationControllerImpl::GetCurrentEntryIndex() const {
471663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (transient_entry_index_ != -1)
472663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return transient_entry_index_;
473663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (pending_entry_index_ != -1)
474663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return pending_entry_index_;
475663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return last_committed_entry_index_;
476663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
477663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
478663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengNavigationEntry* NavigationControllerImpl::GetLastCommittedEntry() const {
479663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  if (last_committed_entry_index_ == -1)
480663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    return NULL;
481663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return entries_[last_committed_entry_index_].get();
482663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
483663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
484663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengbool NavigationControllerImpl::CanViewSource() const {
485663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  const std::string& mime_type = delegate_->GetContentsMimeType();
486663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  bool is_viewable_mime_type = net::IsSupportedNonImageMimeType(mime_type) &&
487663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      !net::IsSupportedMediaMimeType(mime_type);
488663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  NavigationEntry* visible_entry = GetVisibleEntry();
489663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return visible_entry && !visible_entry->IsViewSourceMode() &&
490663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng      is_viewable_mime_type && !delegate_->GetInterstitialPage();
491663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
492663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
493663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengint NavigationControllerImpl::GetLastCommittedEntryIndex() const {
494663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return last_committed_entry_index_;
495663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
496663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
497663860b1408516d02ebfcb3a9999a134e6cfb223Ben Chengint NavigationControllerImpl::GetEntryCount() const {
498663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  DCHECK(entries_.size() <= max_entry_count());
499663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return static_cast<int>(entries_.size());
500663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng}
501663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng
502663860b1408516d02ebfcb3a9999a134e6cfb223Ben ChengNavigationEntry* NavigationControllerImpl::GetEntryAtIndex(
503663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng    int index) const {
504663860b1408516d02ebfcb3a9999a134e6cfb223Ben Cheng  return entries_.at(index).get();
505}
506
507NavigationEntry* NavigationControllerImpl::GetEntryAtOffset(
508    int offset) const {
509  int index = GetIndexForOffset(offset);
510  if (index < 0 || index >= GetEntryCount())
511    return NULL;
512
513  return entries_[index].get();
514}
515
516int NavigationControllerImpl::GetIndexForOffset(int offset) const {
517  return GetCurrentEntryIndex() + offset;
518}
519
520void NavigationControllerImpl::TakeScreenshot() {
521  screenshot_manager_->TakeScreenshot();
522}
523
524void NavigationControllerImpl::SetScreenshotManager(
525    NavigationEntryScreenshotManager* manager) {
526  screenshot_manager_.reset(manager ? manager :
527                            new NavigationEntryScreenshotManager(this));
528}
529
530bool NavigationControllerImpl::CanGoBack() const {
531  return entries_.size() > 1 && GetCurrentEntryIndex() > 0;
532}
533
534bool NavigationControllerImpl::CanGoForward() const {
535  int index = GetCurrentEntryIndex();
536  return index >= 0 && index < (static_cast<int>(entries_.size()) - 1);
537}
538
539bool NavigationControllerImpl::CanGoToOffset(int offset) const {
540  int index = GetIndexForOffset(offset);
541  return index >= 0 && index < GetEntryCount();
542}
543
544void NavigationControllerImpl::GoBack() {
545  if (!CanGoBack()) {
546    NOTREACHED();
547    return;
548  }
549
550  // Base the navigation on where we are now...
551  int current_index = GetCurrentEntryIndex();
552
553  DiscardNonCommittedEntries();
554
555  pending_entry_index_ = current_index - 1;
556  entries_[pending_entry_index_]->SetTransitionType(
557      PageTransitionFromInt(
558          entries_[pending_entry_index_]->GetTransitionType() |
559          PAGE_TRANSITION_FORWARD_BACK));
560  NavigateToPendingEntry(NO_RELOAD);
561}
562
563void NavigationControllerImpl::GoForward() {
564  if (!CanGoForward()) {
565    NOTREACHED();
566    return;
567  }
568
569  bool transient = (transient_entry_index_ != -1);
570
571  // Base the navigation on where we are now...
572  int current_index = GetCurrentEntryIndex();
573
574  DiscardNonCommittedEntries();
575
576  pending_entry_index_ = current_index;
577  // If there was a transient entry, we removed it making the current index
578  // the next page.
579  if (!transient)
580    pending_entry_index_++;
581
582  entries_[pending_entry_index_]->SetTransitionType(
583      PageTransitionFromInt(
584          entries_[pending_entry_index_]->GetTransitionType() |
585          PAGE_TRANSITION_FORWARD_BACK));
586  NavigateToPendingEntry(NO_RELOAD);
587}
588
589void NavigationControllerImpl::GoToIndex(int index) {
590  if (index < 0 || index >= static_cast<int>(entries_.size())) {
591    NOTREACHED();
592    return;
593  }
594
595  if (transient_entry_index_ != -1) {
596    if (index == transient_entry_index_) {
597      // Nothing to do when navigating to the transient.
598      return;
599    }
600    if (index > transient_entry_index_) {
601      // Removing the transient is goint to shift all entries by 1.
602      index--;
603    }
604  }
605
606  DiscardNonCommittedEntries();
607
608  pending_entry_index_ = index;
609  entries_[pending_entry_index_]->SetTransitionType(
610      PageTransitionFromInt(
611          entries_[pending_entry_index_]->GetTransitionType() |
612          PAGE_TRANSITION_FORWARD_BACK));
613  NavigateToPendingEntry(NO_RELOAD);
614}
615
616void NavigationControllerImpl::GoToOffset(int offset) {
617  if (!CanGoToOffset(offset))
618    return;
619
620  GoToIndex(GetIndexForOffset(offset));
621}
622
623bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
624  if (index == last_committed_entry_index_ ||
625      index == pending_entry_index_)
626    return false;
627
628  RemoveEntryAtIndexInternal(index);
629  return true;
630}
631
632void NavigationControllerImpl::UpdateVirtualURLToURL(
633    NavigationEntryImpl* entry, const GURL& new_url) {
634  GURL new_virtual_url(new_url);
635  if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
636          &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
637    entry->SetVirtualURL(new_virtual_url);
638  }
639}
640
641void NavigationControllerImpl::LoadURL(
642    const GURL& url,
643    const Referrer& referrer,
644    PageTransition transition,
645    const std::string& extra_headers) {
646  LoadURLParams params(url);
647  params.referrer = referrer;
648  params.transition_type = transition;
649  params.extra_headers = extra_headers;
650  LoadURLWithParams(params);
651}
652
653void NavigationControllerImpl::LoadURLWithParams(const LoadURLParams& params) {
654  TRACE_EVENT0("browser", "NavigationControllerImpl::LoadURLWithParams");
655  if (HandleDebugURL(params.url, params.transition_type))
656    return;
657
658  // Any renderer-side debug URLs or javascript: URLs should be ignored if the
659  // renderer process is not live, unless it is the initial navigation of the
660  // tab.
661  if (IsRendererDebugURL(params.url)) {
662    // TODO(creis): Find the RVH for the correct frame.
663    if (!delegate_->GetRenderViewHost()->IsRenderViewLive() &&
664        !IsInitialNavigation())
665      return;
666  }
667
668  // Checks based on params.load_type.
669  switch (params.load_type) {
670    case LOAD_TYPE_DEFAULT:
671      break;
672    case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
673      if (!params.url.SchemeIs(url::kHttpScheme) &&
674          !params.url.SchemeIs(url::kHttpsScheme)) {
675        NOTREACHED() << "Http post load must use http(s) scheme.";
676        return;
677      }
678      break;
679    case LOAD_TYPE_DATA:
680      if (!params.url.SchemeIs(url::kDataScheme)) {
681        NOTREACHED() << "Data load must use data scheme.";
682        return;
683      }
684      break;
685    default:
686      NOTREACHED();
687      break;
688  };
689
690  // The user initiated a load, we don't need to reload anymore.
691  needs_reload_ = false;
692
693  bool override = false;
694  switch (params.override_user_agent) {
695    case UA_OVERRIDE_INHERIT:
696      override = ShouldKeepOverride(GetLastCommittedEntry());
697      break;
698    case UA_OVERRIDE_TRUE:
699      override = true;
700      break;
701    case UA_OVERRIDE_FALSE:
702      override = false;
703      break;
704    default:
705      NOTREACHED();
706      break;
707  }
708
709  NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
710      CreateNavigationEntry(
711          params.url,
712          params.referrer,
713          params.transition_type,
714          params.is_renderer_initiated,
715          params.extra_headers,
716          browser_context_));
717  if (params.frame_tree_node_id != -1)
718    entry->set_frame_tree_node_id(params.frame_tree_node_id);
719  if (params.redirect_chain.size() > 0)
720    entry->SetRedirectChain(params.redirect_chain);
721  if (params.should_replace_current_entry)
722    entry->set_should_replace_entry(true);
723  entry->set_should_clear_history_list(params.should_clear_history_list);
724  entry->SetIsOverridingUserAgent(override);
725  entry->set_transferred_global_request_id(
726      params.transferred_global_request_id);
727  entry->SetFrameToNavigate(params.frame_name);
728
729  switch (params.load_type) {
730    case LOAD_TYPE_DEFAULT:
731      break;
732    case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
733      entry->SetHasPostData(true);
734      entry->SetBrowserInitiatedPostData(
735          params.browser_initiated_post_data.get());
736      break;
737    case LOAD_TYPE_DATA:
738      entry->SetBaseURLForDataURL(params.base_url_for_data_url);
739      entry->SetVirtualURL(params.virtual_url_for_data_url);
740      entry->SetCanLoadLocalResources(params.can_load_local_resources);
741      break;
742    default:
743      NOTREACHED();
744      break;
745  };
746
747  LoadEntry(entry);
748}
749
750bool NavigationControllerImpl::RendererDidNavigate(
751    RenderFrameHost* rfh,
752    const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
753    LoadCommittedDetails* details) {
754  is_initial_navigation_ = false;
755
756  // Save the previous state before we clobber it.
757  if (GetLastCommittedEntry()) {
758    details->previous_url = GetLastCommittedEntry()->GetURL();
759    details->previous_entry_index = GetLastCommittedEntryIndex();
760  } else {
761    details->previous_url = GURL();
762    details->previous_entry_index = -1;
763  }
764
765  // If we have a pending entry at this point, it should have a SiteInstance.
766  // Restored entries start out with a null SiteInstance, but we should have
767  // assigned one in NavigateToPendingEntry.
768  DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance());
769
770  // If we are doing a cross-site reload, we need to replace the existing
771  // navigation entry, not add another entry to the history. This has the side
772  // effect of removing forward browsing history, if such existed.
773  // Or if we are doing a cross-site redirect navigation,
774  // we will do a similar thing.
775  details->did_replace_entry =
776      pending_entry_ && pending_entry_->should_replace_entry();
777
778  // Do navigation-type specific actions. These will make and commit an entry.
779  details->type = ClassifyNavigation(rfh, params);
780
781  // is_in_page must be computed before the entry gets committed.
782  details->is_in_page = AreURLsInPageNavigation(rfh->GetLastCommittedURL(),
783      params.url, params.was_within_same_page, rfh);
784
785  switch (details->type) {
786    case NAVIGATION_TYPE_NEW_PAGE:
787      RendererDidNavigateToNewPage(rfh, params, details->did_replace_entry);
788      break;
789    case NAVIGATION_TYPE_EXISTING_PAGE:
790      RendererDidNavigateToExistingPage(rfh, params);
791      break;
792    case NAVIGATION_TYPE_SAME_PAGE:
793      RendererDidNavigateToSamePage(rfh, params);
794      break;
795    case NAVIGATION_TYPE_IN_PAGE:
796      RendererDidNavigateInPage(rfh, params, &details->did_replace_entry);
797      break;
798    case NAVIGATION_TYPE_NEW_SUBFRAME:
799      RendererDidNavigateNewSubframe(rfh, params);
800      break;
801    case NAVIGATION_TYPE_AUTO_SUBFRAME:
802      if (!RendererDidNavigateAutoSubframe(rfh, params))
803        return false;
804      break;
805    case NAVIGATION_TYPE_NAV_IGNORE:
806      // If a pending navigation was in progress, this canceled it.  We should
807      // discard it and make sure it is removed from the URL bar.  After that,
808      // there is nothing we can do with this navigation, so we just return to
809      // the caller that nothing has happened.
810      if (pending_entry_) {
811        DiscardNonCommittedEntries();
812        delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
813      }
814      return false;
815    default:
816      NOTREACHED();
817  }
818
819  // At this point, we know that the navigation has just completed, so
820  // record the time.
821  //
822  // TODO(akalin): Use "sane time" as described in
823  // http://www.chromium.org/developers/design-documents/sane-time .
824  base::Time timestamp =
825      time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
826  DVLOG(1) << "Navigation finished at (smoothed) timestamp "
827           << timestamp.ToInternalValue();
828
829  // We should not have a pending entry anymore.  Clear it again in case any
830  // error cases above forgot to do so.
831  DiscardNonCommittedEntriesInternal();
832
833  // All committed entries should have nonempty content state so WebKit doesn't
834  // get confused when we go back to them (see the function for details).
835  DCHECK(params.page_state.IsValid());
836  NavigationEntryImpl* active_entry =
837      NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
838  active_entry->SetTimestamp(timestamp);
839  active_entry->SetHttpStatusCode(params.http_status_code);
840  active_entry->SetPageState(params.page_state);
841  active_entry->SetRedirectChain(params.redirects);
842
843  // Use histogram to track memory impact of redirect chain because it's now
844  // not cleared for committed entries.
845  size_t redirect_chain_size = 0;
846  for (size_t i = 0; i < params.redirects.size(); ++i) {
847    redirect_chain_size += params.redirects[i].spec().length();
848  }
849  UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size);
850
851  // Once it is committed, we no longer need to track several pieces of state on
852  // the entry.
853  active_entry->ResetForCommit();
854
855  // The active entry's SiteInstance should match our SiteInstance.
856  // TODO(creis): This check won't pass for subframes until we create entries
857  // for subframe navigations.
858  if (PageTransitionIsMainFrame(params.transition))
859    CHECK(active_entry->site_instance() == rfh->GetSiteInstance());
860
861  // Remember the bindings the renderer process has at this point, so that
862  // we do not grant this entry additional bindings if we come back to it.
863  active_entry->SetBindings(
864      static_cast<RenderFrameHostImpl*>(rfh)->GetEnabledBindings());
865
866  // Now prep the rest of the details for the notification and broadcast.
867  details->entry = active_entry;
868  details->is_main_frame =
869      PageTransitionIsMainFrame(params.transition);
870  details->serialized_security_info = params.security_info;
871  details->http_status_code = params.http_status_code;
872  NotifyNavigationEntryCommitted(details);
873
874  return true;
875}
876
877NavigationType NavigationControllerImpl::ClassifyNavigation(
878    RenderFrameHost* rfh,
879    const FrameHostMsg_DidCommitProvisionalLoad_Params& params) const {
880  if (params.page_id == -1) {
881    // The renderer generates the page IDs, and so if it gives us the invalid
882    // page ID (-1) we know it didn't actually navigate. This happens in a few
883    // cases:
884    //
885    // - If a page makes a popup navigated to about blank, and then writes
886    //   stuff like a subframe navigated to a real page. We'll get the commit
887    //   for the subframe, but there won't be any commit for the outer page.
888    //
889    // - We were also getting these for failed loads (for example, bug 21849).
890    //   The guess is that we get a "load commit" for the alternate error page,
891    //   but that doesn't affect the page ID, so we get the "old" one, which
892    //   could be invalid. This can also happen for a cross-site transition
893    //   that causes us to swap processes. Then the error page load will be in
894    //   a new process with no page IDs ever assigned (and hence a -1 value),
895    //   yet the navigation controller still might have previous pages in its
896    //   list.
897    //
898    // In these cases, there's nothing we can do with them, so ignore.
899    return NAVIGATION_TYPE_NAV_IGNORE;
900  }
901
902  if (params.page_id > delegate_->GetMaxPageIDForSiteInstance(
903          rfh->GetSiteInstance())) {
904    // Greater page IDs than we've ever seen before are new pages. We may or may
905    // not have a pending entry for the page, and this may or may not be the
906    // main frame.
907    if (PageTransitionIsMainFrame(params.transition))
908      return NAVIGATION_TYPE_NEW_PAGE;
909
910    // When this is a new subframe navigation, we should have a committed page
911    // for which it's a suframe in. This may not be the case when an iframe is
912    // navigated on a popup navigated to about:blank (the iframe would be
913    // written into the popup by script on the main page). For these cases,
914    // there isn't any navigation stuff we can do, so just ignore it.
915    if (!GetLastCommittedEntry())
916      return NAVIGATION_TYPE_NAV_IGNORE;
917
918    // Valid subframe navigation.
919    return NAVIGATION_TYPE_NEW_SUBFRAME;
920  }
921
922  // We only clear the session history when navigating to a new page.
923  DCHECK(!params.history_list_was_cleared);
924
925  // Now we know that the notification is for an existing page. Find that entry.
926  int existing_entry_index = GetEntryIndexWithPageID(
927      rfh->GetSiteInstance(),
928      params.page_id);
929  if (existing_entry_index == -1) {
930    // The page was not found. It could have been pruned because of the limit on
931    // back/forward entries (not likely since we'll usually tell it to navigate
932    // to such entries). It could also mean that the renderer is smoking crack.
933    NOTREACHED();
934
935    // Because the unknown entry has committed, we risk showing the wrong URL in
936    // release builds. Instead, we'll kill the renderer process to be safe.
937    LOG(ERROR) << "terminating renderer for bad navigation: " << params.url;
938    RecordAction(base::UserMetricsAction("BadMessageTerminate_NC"));
939
940    // Temporary code so we can get more information.  Format:
941    //  http://url/foo.html#page1#max3#frame1#ids:2_Nx,1_1x,3_2
942    std::string temp = params.url.spec();
943    temp.append("#page");
944    temp.append(base::IntToString(params.page_id));
945    temp.append("#max");
946    temp.append(base::IntToString(delegate_->GetMaxPageID()));
947    temp.append("#frame");
948    temp.append(base::IntToString(rfh->GetRoutingID()));
949    temp.append("#ids");
950    for (int i = 0; i < static_cast<int>(entries_.size()); ++i) {
951      // Append entry metadata (e.g., 3_7x):
952      //  3: page_id
953      //  7: SiteInstance ID, or N for null
954      //  x: appended if not from the current SiteInstance
955      temp.append(base::IntToString(entries_[i]->GetPageID()));
956      temp.append("_");
957      if (entries_[i]->site_instance())
958        temp.append(base::IntToString(entries_[i]->site_instance()->GetId()));
959      else
960        temp.append("N");
961      if (entries_[i]->site_instance() != rfh->GetSiteInstance())
962        temp.append("x");
963      temp.append(",");
964    }
965    GURL url(temp);
966    static_cast<RenderFrameHostImpl*>(rfh)->render_view_host()->Send(
967        new ViewMsg_TempCrashWithData(url));
968    return NAVIGATION_TYPE_NAV_IGNORE;
969  }
970  NavigationEntryImpl* existing_entry = entries_[existing_entry_index].get();
971
972  if (!PageTransitionIsMainFrame(params.transition)) {
973    // All manual subframes would get new IDs and were handled above, so we
974    // know this is auto. Since the current page was found in the navigation
975    // entry list, we're guaranteed to have a last committed entry.
976    DCHECK(GetLastCommittedEntry());
977    return NAVIGATION_TYPE_AUTO_SUBFRAME;
978  }
979
980  // Anything below here we know is a main frame navigation.
981  if (pending_entry_ &&
982      !pending_entry_->is_renderer_initiated() &&
983      existing_entry != pending_entry_ &&
984      pending_entry_->GetPageID() == -1 &&
985      existing_entry == GetLastCommittedEntry()) {
986    // In this case, we have a pending entry for a URL but WebCore didn't do a
987    // new navigation. This happens when you press enter in the URL bar to
988    // reload. We will create a pending entry, but WebKit will convert it to
989    // a reload since it's the same page and not create a new entry for it
990    // (the user doesn't want to have a new back/forward entry when they do
991    // this). If this matches the last committed entry, we want to just ignore
992    // the pending entry and go back to where we were (the "existing entry").
993    return NAVIGATION_TYPE_SAME_PAGE;
994  }
995
996  // Any toplevel navigations with the same base (minus the reference fragment)
997  // are in-page navigations. We weeded out subframe navigations above. Most of
998  // the time this doesn't matter since WebKit doesn't tell us about subframe
999  // navigations that don't actually navigate, but it can happen when there is
1000  // an encoding override (it always sends a navigation request).
1001  if (AreURLsInPageNavigation(existing_entry->GetURL(), params.url,
1002                              params.was_within_same_page, rfh)) {
1003    return NAVIGATION_TYPE_IN_PAGE;
1004  }
1005
1006  // Since we weeded out "new" navigations above, we know this is an existing
1007  // (back/forward) navigation.
1008  return NAVIGATION_TYPE_EXISTING_PAGE;
1009}
1010
1011void NavigationControllerImpl::RendererDidNavigateToNewPage(
1012    RenderFrameHost* rfh,
1013    const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
1014    bool replace_entry) {
1015  NavigationEntryImpl* new_entry;
1016  bool update_virtual_url;
1017  // Only make a copy of the pending entry if it is appropriate for the new page
1018  // that was just loaded.  We verify this at a coarse grain by checking that
1019  // the SiteInstance hasn't been assigned to something else.
1020  if (pending_entry_ &&
1021      (!pending_entry_->site_instance() ||
1022       pending_entry_->site_instance() == rfh->GetSiteInstance())) {
1023    new_entry = new NavigationEntryImpl(*pending_entry_);
1024
1025    // Don't use the page type from the pending entry. Some interstitial page
1026    // may have set the type to interstitial. Once we commit, however, the page
1027    // type must always be normal.
1028    new_entry->set_page_type(PAGE_TYPE_NORMAL);
1029    update_virtual_url = new_entry->update_virtual_url_with_url();
1030  } else {
1031    new_entry = new NavigationEntryImpl;
1032
1033    // Find out whether the new entry needs to update its virtual URL on URL
1034    // change and set up the entry accordingly. This is needed to correctly
1035    // update the virtual URL when replaceState is called after a pushState.
1036    GURL url = params.url;
1037    bool needs_update = false;
1038    // We call RewriteURLIfNecessary twice: once when page navigation
1039    // begins in CreateNavigationEntry, and once here when it commits.
1040    // With the kEnableGpuBenchmarking flag, the rewriting includes
1041    // handling debug URLs which cause an action to occur, and thus we
1042    // should not rewrite them a second time.
1043    bool skip_rewrite =
1044        IsDebugURL(url) && base::CommandLine::ForCurrentProcess()->HasSwitch(
1045            cc::switches::kEnableGpuBenchmarking);
1046    if (!skip_rewrite) {
1047      BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1048          &url, browser_context_, &needs_update);
1049    }
1050    new_entry->set_update_virtual_url_with_url(needs_update);
1051
1052    // When navigating to a new page, give the browser URL handler a chance to
1053    // update the virtual URL based on the new URL. For example, this is needed
1054    // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1055    // the URL.
1056    update_virtual_url = needs_update;
1057  }
1058
1059  new_entry->SetURL(params.url);
1060  if (update_virtual_url)
1061    UpdateVirtualURLToURL(new_entry, params.url);
1062  new_entry->SetReferrer(params.referrer);
1063  new_entry->SetPageID(params.page_id);
1064  new_entry->SetTransitionType(params.transition);
1065  new_entry->set_site_instance(
1066      static_cast<SiteInstanceImpl*>(rfh->GetSiteInstance()));
1067  new_entry->SetHasPostData(params.is_post);
1068  new_entry->SetPostID(params.post_id);
1069  new_entry->SetOriginalRequestURL(params.original_request_url);
1070  new_entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1071
1072  // history.pushState() is classified as a navigation to a new page, but
1073  // sets was_within_same_page to true. In this case, we already have the
1074  // title available, so set it immediately.
1075  if (params.was_within_same_page && GetLastCommittedEntry())
1076    new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
1077
1078  DCHECK(!params.history_list_was_cleared || !replace_entry);
1079  // The browser requested to clear the session history when it initiated the
1080  // navigation. Now we know that the renderer has updated its state accordingly
1081  // and it is safe to also clear the browser side history.
1082  if (params.history_list_was_cleared) {
1083    DiscardNonCommittedEntriesInternal();
1084    entries_.clear();
1085    last_committed_entry_index_ = -1;
1086  }
1087
1088  InsertOrReplaceEntry(new_entry, replace_entry);
1089}
1090
1091void NavigationControllerImpl::RendererDidNavigateToExistingPage(
1092    RenderFrameHost* rfh,
1093    const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1094  // We should only get here for main frame navigations.
1095  DCHECK(PageTransitionIsMainFrame(params.transition));
1096
1097  // This is a back/forward navigation. The existing page for the ID is
1098  // guaranteed to exist by ClassifyNavigation, and we just need to update it
1099  // with new information from the renderer.
1100  int entry_index = GetEntryIndexWithPageID(rfh->GetSiteInstance(),
1101                                            params.page_id);
1102  DCHECK(entry_index >= 0 &&
1103         entry_index < static_cast<int>(entries_.size()));
1104  NavigationEntryImpl* entry = entries_[entry_index].get();
1105
1106  // The URL may have changed due to redirects.
1107  entry->SetURL(params.url);
1108  entry->SetReferrer(params.referrer);
1109  if (entry->update_virtual_url_with_url())
1110    UpdateVirtualURLToURL(entry, params.url);
1111
1112  // The redirected to page should not inherit the favicon from the previous
1113  // page.
1114  if (PageTransitionIsRedirect(params.transition))
1115    entry->GetFavicon() = FaviconStatus();
1116
1117  // The site instance will normally be the same except during session restore,
1118  // when no site instance will be assigned.
1119  DCHECK(entry->site_instance() == NULL ||
1120         entry->site_instance() == rfh->GetSiteInstance());
1121  entry->set_site_instance(
1122      static_cast<SiteInstanceImpl*>(rfh->GetSiteInstance()));
1123
1124  entry->SetHasPostData(params.is_post);
1125  entry->SetPostID(params.post_id);
1126
1127  // The entry we found in the list might be pending if the user hit
1128  // back/forward/reload. This load should commit it (since it's already in the
1129  // list, we can just discard the pending pointer).  We should also discard the
1130  // pending entry if it corresponds to a different navigation, since that one
1131  // is now likely canceled.  If it is not canceled, we will treat it as a new
1132  // navigation when it arrives, which is also ok.
1133  //
1134  // Note that we need to use the "internal" version since we don't want to
1135  // actually change any other state, just kill the pointer.
1136  DiscardNonCommittedEntriesInternal();
1137
1138  // If a transient entry was removed, the indices might have changed, so we
1139  // have to query the entry index again.
1140  last_committed_entry_index_ =
1141      GetEntryIndexWithPageID(rfh->GetSiteInstance(), params.page_id);
1142}
1143
1144void NavigationControllerImpl::RendererDidNavigateToSamePage(
1145    RenderFrameHost* rfh,
1146    const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1147  // This mode implies we have a pending entry that's the same as an existing
1148  // entry for this page ID. This entry is guaranteed to exist by
1149  // ClassifyNavigation. All we need to do is update the existing entry.
1150  NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1151      rfh->GetSiteInstance(), params.page_id);
1152
1153  // We assign the entry's unique ID to be that of the new one. Since this is
1154  // always the result of a user action, we want to dismiss infobars, etc. like
1155  // a regular user-initiated navigation.
1156  existing_entry->set_unique_id(pending_entry_->GetUniqueID());
1157
1158  // The URL may have changed due to redirects.
1159  if (existing_entry->update_virtual_url_with_url())
1160    UpdateVirtualURLToURL(existing_entry, params.url);
1161  existing_entry->SetURL(params.url);
1162  existing_entry->SetReferrer(params.referrer);
1163
1164  // The page may have been requested with a different HTTP method.
1165  existing_entry->SetHasPostData(params.is_post);
1166  existing_entry->SetPostID(params.post_id);
1167
1168  DiscardNonCommittedEntries();
1169}
1170
1171void NavigationControllerImpl::RendererDidNavigateInPage(
1172    RenderFrameHost* rfh,
1173    const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
1174    bool* did_replace_entry) {
1175  DCHECK(PageTransitionIsMainFrame(params.transition)) <<
1176      "WebKit should only tell us about in-page navs for the main frame.";
1177  // We're guaranteed to have an entry for this one.
1178  NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1179      rfh->GetSiteInstance(), params.page_id);
1180
1181  // Reference fragment navigation. We're guaranteed to have the last_committed
1182  // entry and it will be the same page as the new navigation (minus the
1183  // reference fragments, of course).  We'll update the URL of the existing
1184  // entry without pruning the forward history.
1185  existing_entry->SetURL(params.url);
1186  if (existing_entry->update_virtual_url_with_url())
1187    UpdateVirtualURLToURL(existing_entry, params.url);
1188
1189  existing_entry->SetHasPostData(params.is_post);
1190  existing_entry->SetPostID(params.post_id);
1191
1192  // This replaces the existing entry since the page ID didn't change.
1193  *did_replace_entry = true;
1194
1195  DiscardNonCommittedEntriesInternal();
1196
1197  // If a transient entry was removed, the indices might have changed, so we
1198  // have to query the entry index again.
1199  last_committed_entry_index_ =
1200      GetEntryIndexWithPageID(rfh->GetSiteInstance(), params.page_id);
1201}
1202
1203void NavigationControllerImpl::RendererDidNavigateNewSubframe(
1204    RenderFrameHost* rfh,
1205    const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1206  if (PageTransitionCoreTypeIs(params.transition,
1207                               PAGE_TRANSITION_AUTO_SUBFRAME)) {
1208    // This is not user-initiated. Ignore.
1209    DiscardNonCommittedEntriesInternal();
1210    return;
1211  }
1212
1213  // Manual subframe navigations just get the current entry cloned so the user
1214  // can go back or forward to it. The actual subframe information will be
1215  // stored in the page state for each of those entries. This happens out of
1216  // band with the actual navigations.
1217  DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
1218                                  << "that a last committed entry exists.";
1219  NavigationEntryImpl* new_entry = new NavigationEntryImpl(
1220      *NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry()));
1221  new_entry->SetPageID(params.page_id);
1222  InsertOrReplaceEntry(new_entry, false);
1223}
1224
1225bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
1226    RenderFrameHost* rfh,
1227    const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1228  // We're guaranteed to have a previously committed entry, and we now need to
1229  // handle navigation inside of a subframe in it without creating a new entry.
1230  DCHECK(GetLastCommittedEntry());
1231
1232  // Handle the case where we're navigating back/forward to a previous subframe
1233  // navigation entry. This is case "2." in NAV_AUTO_SUBFRAME comment in the
1234  // header file. In case "1." this will be a NOP.
1235  int entry_index = GetEntryIndexWithPageID(
1236      rfh->GetSiteInstance(),
1237      params.page_id);
1238  if (entry_index < 0 ||
1239      entry_index >= static_cast<int>(entries_.size())) {
1240    NOTREACHED();
1241    return false;
1242  }
1243
1244  // Update the current navigation entry in case we're going back/forward.
1245  if (entry_index != last_committed_entry_index_) {
1246    last_committed_entry_index_ = entry_index;
1247    DiscardNonCommittedEntriesInternal();
1248    return true;
1249  }
1250
1251  // We do not need to discard the pending entry in this case, since we will
1252  // not generate commit notifications for this auto-subframe navigation.
1253  return false;
1254}
1255
1256int NavigationControllerImpl::GetIndexOfEntry(
1257    const NavigationEntryImpl* entry) const {
1258  const NavigationEntries::const_iterator i(std::find(
1259      entries_.begin(),
1260      entries_.end(),
1261      entry));
1262  return (i == entries_.end()) ? -1 : static_cast<int>(i - entries_.begin());
1263}
1264
1265bool NavigationControllerImpl::IsURLInPageNavigation(
1266    const GURL& url,
1267    bool renderer_says_in_page,
1268    RenderFrameHost* rfh) const {
1269  NavigationEntry* last_committed = GetLastCommittedEntry();
1270  return last_committed && AreURLsInPageNavigation(
1271      last_committed->GetURL(), url, renderer_says_in_page, rfh);
1272}
1273
1274void NavigationControllerImpl::CopyStateFrom(
1275    const NavigationController& temp) {
1276  const NavigationControllerImpl& source =
1277      static_cast<const NavigationControllerImpl&>(temp);
1278  // Verify that we look new.
1279  DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
1280
1281  if (source.GetEntryCount() == 0)
1282    return;  // Nothing new to do.
1283
1284  needs_reload_ = true;
1285  InsertEntriesFrom(source, source.GetEntryCount());
1286
1287  for (SessionStorageNamespaceMap::const_iterator it =
1288           source.session_storage_namespace_map_.begin();
1289       it != source.session_storage_namespace_map_.end();
1290       ++it) {
1291    SessionStorageNamespaceImpl* source_namespace =
1292        static_cast<SessionStorageNamespaceImpl*>(it->second.get());
1293    session_storage_namespace_map_[it->first] = source_namespace->Clone();
1294  }
1295
1296  FinishRestore(source.last_committed_entry_index_, RESTORE_CURRENT_SESSION);
1297
1298  // Copy the max page id map from the old tab to the new tab.  This ensures
1299  // that new and existing navigations in the tab's current SiteInstances
1300  // are identified properly.
1301  delegate_->CopyMaxPageIDsFrom(source.delegate()->GetWebContents());
1302}
1303
1304void NavigationControllerImpl::CopyStateFromAndPrune(
1305    NavigationController* temp,
1306    bool replace_entry) {
1307  // It is up to callers to check the invariants before calling this.
1308  CHECK(CanPruneAllButLastCommitted());
1309
1310  NavigationControllerImpl* source =
1311      static_cast<NavigationControllerImpl*>(temp);
1312  // The SiteInstance and page_id of the last committed entry needs to be
1313  // remembered at this point, in case there is only one committed entry
1314  // and it is pruned.  We use a scoped_refptr to ensure the SiteInstance
1315  // can't be freed during this time period.
1316  NavigationEntryImpl* last_committed =
1317      NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
1318  scoped_refptr<SiteInstance> site_instance(
1319      last_committed->site_instance());
1320  int32 minimum_page_id = last_committed->GetPageID();
1321  int32 max_page_id =
1322      delegate_->GetMaxPageIDForSiteInstance(site_instance.get());
1323
1324  // Remove all the entries leaving the active entry.
1325  PruneAllButLastCommittedInternal();
1326
1327  // We now have one entry, possibly with a new pending entry.  Ensure that
1328  // adding the entries from source won't put us over the limit.
1329  DCHECK_EQ(1, GetEntryCount());
1330  if (!replace_entry)
1331    source->PruneOldestEntryIfFull();
1332
1333  // Insert the entries from source. Don't use source->GetCurrentEntryIndex as
1334  // we don't want to copy over the transient entry.  Ignore any pending entry,
1335  // since it has not committed in source.
1336  int max_source_index = source->last_committed_entry_index_;
1337  if (max_source_index == -1)
1338    max_source_index = source->GetEntryCount();
1339  else
1340    max_source_index++;
1341
1342  // Ignore the source's current entry if merging with replacement.
1343  // TODO(davidben): This should preserve entries forward of the current
1344  // too. http://crbug.com/317872
1345  if (replace_entry && max_source_index > 0)
1346    max_source_index--;
1347
1348  InsertEntriesFrom(*source, max_source_index);
1349
1350  // Adjust indices such that the last entry and pending are at the end now.
1351  last_committed_entry_index_ = GetEntryCount() - 1;
1352
1353  delegate_->SetHistoryLengthAndPrune(site_instance.get(),
1354                                      max_source_index,
1355                                      minimum_page_id);
1356
1357  // Copy the max page id map from the old tab to the new tab.  This ensures
1358  // that new and existing navigations in the tab's current SiteInstances
1359  // are identified properly.
1360  delegate_->CopyMaxPageIDsFrom(source->delegate()->GetWebContents());
1361  max_restored_page_id_ = source->max_restored_page_id_;
1362
1363  // If there is a last committed entry, be sure to include it in the new
1364  // max page ID map.
1365  if (max_page_id > -1) {
1366    delegate_->UpdateMaxPageIDForSiteInstance(site_instance.get(),
1367                                              max_page_id);
1368  }
1369}
1370
1371bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
1372  // If there is no last committed entry, we cannot prune.  Even if there is a
1373  // pending entry, it may not commit, leaving this WebContents blank, despite
1374  // possibly giving it new entries via CopyStateFromAndPrune.
1375  if (last_committed_entry_index_ == -1)
1376    return false;
1377
1378  // We cannot prune if there is a pending entry at an existing entry index.
1379  // It may not commit, so we have to keep the last committed entry, and thus
1380  // there is no sensible place to keep the pending entry.  It is ok to have
1381  // a new pending entry, which can optionally commit as a new navigation.
1382  if (pending_entry_index_ != -1)
1383    return false;
1384
1385  // We should not prune if we are currently showing a transient entry.
1386  if (transient_entry_index_ != -1)
1387    return false;
1388
1389  return true;
1390}
1391
1392void NavigationControllerImpl::PruneAllButLastCommitted() {
1393  PruneAllButLastCommittedInternal();
1394
1395  // We should still have a last committed entry.
1396  DCHECK_NE(-1, last_committed_entry_index_);
1397
1398  // We pass 0 instead of GetEntryCount() for the history_length parameter of
1399  // SetHistoryLengthAndPrune, because it will create history_length additional
1400  // history entries.
1401  // TODO(jochen): This API is confusing and we should clean it up.
1402  // http://crbug.com/178491
1403  NavigationEntryImpl* entry =
1404      NavigationEntryImpl::FromNavigationEntry(GetVisibleEntry());
1405  delegate_->SetHistoryLengthAndPrune(
1406      entry->site_instance(), 0, entry->GetPageID());
1407}
1408
1409void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
1410  // It is up to callers to check the invariants before calling this.
1411  CHECK(CanPruneAllButLastCommitted());
1412
1413  // Erase all entries but the last committed entry.  There may still be a
1414  // new pending entry after this.
1415  entries_.erase(entries_.begin(),
1416                 entries_.begin() + last_committed_entry_index_);
1417  entries_.erase(entries_.begin() + 1, entries_.end());
1418  last_committed_entry_index_ = 0;
1419}
1420
1421void NavigationControllerImpl::ClearAllScreenshots() {
1422  screenshot_manager_->ClearAllScreenshots();
1423}
1424
1425void NavigationControllerImpl::SetSessionStorageNamespace(
1426    const std::string& partition_id,
1427    SessionStorageNamespace* session_storage_namespace) {
1428  if (!session_storage_namespace)
1429    return;
1430
1431  // We can't overwrite an existing SessionStorage without violating spec.
1432  // Attempts to do so may give a tab access to another tab's session storage
1433  // so die hard on an error.
1434  bool successful_insert = session_storage_namespace_map_.insert(
1435      make_pair(partition_id,
1436                static_cast<SessionStorageNamespaceImpl*>(
1437                    session_storage_namespace)))
1438          .second;
1439  CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
1440}
1441
1442void NavigationControllerImpl::SetMaxRestoredPageID(int32 max_id) {
1443  max_restored_page_id_ = max_id;
1444}
1445
1446int32 NavigationControllerImpl::GetMaxRestoredPageID() const {
1447  return max_restored_page_id_;
1448}
1449
1450bool NavigationControllerImpl::IsUnmodifiedBlankTab() const {
1451  return IsInitialNavigation() &&
1452         !GetLastCommittedEntry() &&
1453         !delegate_->HasAccessedInitialDocument();
1454}
1455
1456SessionStorageNamespace*
1457NavigationControllerImpl::GetSessionStorageNamespace(SiteInstance* instance) {
1458  std::string partition_id;
1459  if (instance) {
1460    // TODO(ajwong): When GetDefaultSessionStorageNamespace() goes away, remove
1461    // this if statement so |instance| must not be NULL.
1462    partition_id =
1463        GetContentClient()->browser()->GetStoragePartitionIdForSite(
1464            browser_context_, instance->GetSiteURL());
1465  }
1466
1467  SessionStorageNamespaceMap::const_iterator it =
1468      session_storage_namespace_map_.find(partition_id);
1469  if (it != session_storage_namespace_map_.end())
1470    return it->second.get();
1471
1472  // Create one if no one has accessed session storage for this partition yet.
1473  //
1474  // TODO(ajwong): Should this use the |partition_id| directly rather than
1475  // re-lookup via |instance|?  http://crbug.com/142685
1476  StoragePartition* partition =
1477              BrowserContext::GetStoragePartition(browser_context_, instance);
1478  SessionStorageNamespaceImpl* session_storage_namespace =
1479      new SessionStorageNamespaceImpl(
1480          static_cast<DOMStorageContextWrapper*>(
1481              partition->GetDOMStorageContext()));
1482  session_storage_namespace_map_[partition_id] = session_storage_namespace;
1483
1484  return session_storage_namespace;
1485}
1486
1487SessionStorageNamespace*
1488NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
1489  // TODO(ajwong): Remove if statement in GetSessionStorageNamespace().
1490  return GetSessionStorageNamespace(NULL);
1491}
1492
1493const SessionStorageNamespaceMap&
1494NavigationControllerImpl::GetSessionStorageNamespaceMap() const {
1495  return session_storage_namespace_map_;
1496}
1497
1498bool NavigationControllerImpl::NeedsReload() const {
1499  return needs_reload_;
1500}
1501
1502void NavigationControllerImpl::SetNeedsReload() {
1503  needs_reload_ = true;
1504}
1505
1506void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
1507  DCHECK(index < GetEntryCount());
1508  DCHECK(index != last_committed_entry_index_);
1509
1510  DiscardNonCommittedEntries();
1511
1512  entries_.erase(entries_.begin() + index);
1513  if (last_committed_entry_index_ > index)
1514    last_committed_entry_index_--;
1515}
1516
1517void NavigationControllerImpl::DiscardNonCommittedEntries() {
1518  bool transient = transient_entry_index_ != -1;
1519  DiscardNonCommittedEntriesInternal();
1520
1521  // If there was a transient entry, invalidate everything so the new active
1522  // entry state is shown.
1523  if (transient) {
1524    delegate_->NotifyNavigationStateChanged(kInvalidateAll);
1525  }
1526}
1527
1528NavigationEntry* NavigationControllerImpl::GetPendingEntry() const {
1529  return pending_entry_;
1530}
1531
1532int NavigationControllerImpl::GetPendingEntryIndex() const {
1533  return pending_entry_index_;
1534}
1535
1536void NavigationControllerImpl::InsertOrReplaceEntry(NavigationEntryImpl* entry,
1537                                                    bool replace) {
1538  DCHECK(entry->GetTransitionType() != PAGE_TRANSITION_AUTO_SUBFRAME);
1539
1540  // Copy the pending entry's unique ID to the committed entry.
1541  // I don't know if pending_entry_index_ can be other than -1 here.
1542  const NavigationEntryImpl* const pending_entry =
1543      (pending_entry_index_ == -1) ?
1544          pending_entry_ : entries_[pending_entry_index_].get();
1545  if (pending_entry)
1546    entry->set_unique_id(pending_entry->GetUniqueID());
1547
1548  DiscardNonCommittedEntriesInternal();
1549
1550  int current_size = static_cast<int>(entries_.size());
1551
1552  if (current_size > 0) {
1553    // Prune any entries which are in front of the current entry.
1554    // Also prune the current entry if we are to replace the current entry.
1555    // last_committed_entry_index_ must be updated here since calls to
1556    // NotifyPrunedEntries() below may re-enter and we must make sure
1557    // last_committed_entry_index_ is not left in an invalid state.
1558    if (replace)
1559      --last_committed_entry_index_;
1560
1561    int num_pruned = 0;
1562    while (last_committed_entry_index_ < (current_size - 1)) {
1563      num_pruned++;
1564      entries_.pop_back();
1565      current_size--;
1566    }
1567    if (num_pruned > 0)  // Only notify if we did prune something.
1568      NotifyPrunedEntries(this, false, num_pruned);
1569  }
1570
1571  PruneOldestEntryIfFull();
1572
1573  entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
1574  last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
1575
1576  // This is a new page ID, so we need everybody to know about it.
1577  delegate_->UpdateMaxPageID(entry->GetPageID());
1578}
1579
1580void NavigationControllerImpl::PruneOldestEntryIfFull() {
1581  if (entries_.size() >= max_entry_count()) {
1582    DCHECK_EQ(max_entry_count(), entries_.size());
1583    DCHECK_GT(last_committed_entry_index_, 0);
1584    RemoveEntryAtIndex(0);
1585    NotifyPrunedEntries(this, true, 1);
1586  }
1587}
1588
1589void NavigationControllerImpl::NavigateToPendingEntry(ReloadType reload_type) {
1590  needs_reload_ = false;
1591
1592  // If we were navigating to a slow-to-commit page, and the user performs
1593  // a session history navigation to the last committed page, RenderViewHost
1594  // will force the throbber to start, but WebKit will essentially ignore the
1595  // navigation, and won't send a message to stop the throbber. To prevent this
1596  // from happening, we drop the navigation here and stop the slow-to-commit
1597  // page from loading (which would normally happen during the navigation).
1598  if (pending_entry_index_ != -1 &&
1599      pending_entry_index_ == last_committed_entry_index_ &&
1600      (entries_[pending_entry_index_]->restore_type() ==
1601          NavigationEntryImpl::RESTORE_NONE) &&
1602      (entries_[pending_entry_index_]->GetTransitionType() &
1603          PAGE_TRANSITION_FORWARD_BACK)) {
1604    delegate_->Stop();
1605
1606    // If an interstitial page is showing, we want to close it to get back
1607    // to what was showing before.
1608    if (delegate_->GetInterstitialPage())
1609      delegate_->GetInterstitialPage()->DontProceed();
1610
1611    DiscardNonCommittedEntries();
1612    return;
1613  }
1614
1615  // If an interstitial page is showing, the previous renderer is blocked and
1616  // cannot make new requests.  Unblock (and disable) it to allow this
1617  // navigation to succeed.  The interstitial will stay visible until the
1618  // resulting DidNavigate.
1619  if (delegate_->GetInterstitialPage()) {
1620    static_cast<InterstitialPageImpl*>(delegate_->GetInterstitialPage())->
1621        CancelForNavigation();
1622  }
1623
1624  // For session history navigations only the pending_entry_index_ is set.
1625  if (!pending_entry_) {
1626    DCHECK_NE(pending_entry_index_, -1);
1627    pending_entry_ = entries_[pending_entry_index_].get();
1628  }
1629
1630  // This call does not support re-entrancy.  See http://crbug.com/347742.
1631  CHECK(!in_navigate_to_pending_entry_);
1632  in_navigate_to_pending_entry_ = true;
1633  bool success = delegate_->NavigateToPendingEntry(reload_type);
1634  in_navigate_to_pending_entry_ = false;
1635
1636  if (!success)
1637    DiscardNonCommittedEntries();
1638
1639  // If the entry is being restored and doesn't have a SiteInstance yet, fill
1640  // it in now that we know. This allows us to find the entry when it commits.
1641  if (pending_entry_ && !pending_entry_->site_instance() &&
1642      pending_entry_->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
1643    pending_entry_->set_site_instance(static_cast<SiteInstanceImpl*>(
1644        delegate_->GetPendingSiteInstance()));
1645    pending_entry_->set_restore_type(NavigationEntryImpl::RESTORE_NONE);
1646  }
1647}
1648
1649void NavigationControllerImpl::NotifyNavigationEntryCommitted(
1650    LoadCommittedDetails* details) {
1651  details->entry = GetLastCommittedEntry();
1652
1653  // We need to notify the ssl_manager_ before the web_contents_ so the
1654  // location bar will have up-to-date information about the security style
1655  // when it wants to draw.  See http://crbug.com/11157
1656  ssl_manager_.DidCommitProvisionalLoad(*details);
1657
1658  delegate_->NotifyNavigationStateChanged(kInvalidateAll);
1659  delegate_->NotifyNavigationEntryCommitted(*details);
1660
1661  // TODO(avi): Remove. http://crbug.com/170921
1662  NotificationDetails notification_details =
1663      Details<LoadCommittedDetails>(details);
1664  NotificationService::current()->Notify(
1665      NOTIFICATION_NAV_ENTRY_COMMITTED,
1666      Source<NavigationController>(this),
1667      notification_details);
1668}
1669
1670// static
1671size_t NavigationControllerImpl::max_entry_count() {
1672  if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
1673     return max_entry_count_for_testing_;
1674  return kMaxSessionHistoryEntries;
1675}
1676
1677void NavigationControllerImpl::SetActive(bool is_active) {
1678  if (is_active && needs_reload_)
1679    LoadIfNecessary();
1680}
1681
1682void NavigationControllerImpl::LoadIfNecessary() {
1683  if (!needs_reload_)
1684    return;
1685
1686  // Calling Reload() results in ignoring state, and not loading.
1687  // Explicitly use NavigateToPendingEntry so that the renderer uses the
1688  // cached state.
1689  pending_entry_index_ = last_committed_entry_index_;
1690  NavigateToPendingEntry(NO_RELOAD);
1691}
1692
1693void NavigationControllerImpl::NotifyEntryChanged(const NavigationEntry* entry,
1694                                                  int index) {
1695  EntryChangedDetails det;
1696  det.changed_entry = entry;
1697  det.index = index;
1698  NotificationService::current()->Notify(
1699      NOTIFICATION_NAV_ENTRY_CHANGED,
1700      Source<NavigationController>(this),
1701      Details<EntryChangedDetails>(&det));
1702}
1703
1704void NavigationControllerImpl::FinishRestore(int selected_index,
1705                                             RestoreType type) {
1706  DCHECK(selected_index >= 0 && selected_index < GetEntryCount());
1707  ConfigureEntriesForRestore(&entries_, type);
1708
1709  SetMaxRestoredPageID(static_cast<int32>(GetEntryCount()));
1710
1711  last_committed_entry_index_ = selected_index;
1712}
1713
1714void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
1715  DiscardPendingEntry();
1716  DiscardTransientEntry();
1717}
1718
1719void NavigationControllerImpl::DiscardPendingEntry() {
1720  // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
1721  // progress, since this will cause a use-after-free.  (We only allow this
1722  // when the tab is being destroyed for shutdown, since it won't return to
1723  // NavigateToEntry in that case.)  http://crbug.com/347742.
1724  CHECK(!in_navigate_to_pending_entry_ || delegate_->IsBeingDestroyed());
1725
1726  if (pending_entry_index_ == -1)
1727    delete pending_entry_;
1728  pending_entry_ = NULL;
1729  pending_entry_index_ = -1;
1730}
1731
1732void NavigationControllerImpl::DiscardTransientEntry() {
1733  if (transient_entry_index_ == -1)
1734    return;
1735  entries_.erase(entries_.begin() + transient_entry_index_);
1736  if (last_committed_entry_index_ > transient_entry_index_)
1737    last_committed_entry_index_--;
1738  transient_entry_index_ = -1;
1739}
1740
1741int NavigationControllerImpl::GetEntryIndexWithPageID(
1742    SiteInstance* instance, int32 page_id) const {
1743  for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
1744    if ((entries_[i]->site_instance() == instance) &&
1745        (entries_[i]->GetPageID() == page_id))
1746      return i;
1747  }
1748  return -1;
1749}
1750
1751NavigationEntry* NavigationControllerImpl::GetTransientEntry() const {
1752  if (transient_entry_index_ == -1)
1753    return NULL;
1754  return entries_[transient_entry_index_].get();
1755}
1756
1757void NavigationControllerImpl::SetTransientEntry(NavigationEntry* entry) {
1758  // Discard any current transient entry, we can only have one at a time.
1759  int index = 0;
1760  if (last_committed_entry_index_ != -1)
1761    index = last_committed_entry_index_ + 1;
1762  DiscardTransientEntry();
1763  entries_.insert(
1764      entries_.begin() + index, linked_ptr<NavigationEntryImpl>(
1765          NavigationEntryImpl::FromNavigationEntry(entry)));
1766  transient_entry_index_ = index;
1767  delegate_->NotifyNavigationStateChanged(kInvalidateAll);
1768}
1769
1770void NavigationControllerImpl::InsertEntriesFrom(
1771    const NavigationControllerImpl& source,
1772    int max_index) {
1773  DCHECK_LE(max_index, source.GetEntryCount());
1774  size_t insert_index = 0;
1775  for (int i = 0; i < max_index; i++) {
1776    // When cloning a tab, copy all entries except interstitial pages
1777    if (source.entries_[i].get()->GetPageType() !=
1778        PAGE_TYPE_INTERSTITIAL) {
1779      entries_.insert(entries_.begin() + insert_index++,
1780                      linked_ptr<NavigationEntryImpl>(
1781                          new NavigationEntryImpl(*source.entries_[i])));
1782    }
1783  }
1784}
1785
1786void NavigationControllerImpl::SetGetTimestampCallbackForTest(
1787    const base::Callback<base::Time()>& get_timestamp_callback) {
1788  get_timestamp_callback_ = get_timestamp_callback;
1789}
1790
1791}  // namespace content
1792