Fix broken path in extensions/common/PRESUBMIT.py
[chromium-blink-merge.git] / content / browser / frame_host / navigation_controller_impl.cc
blob08555a3f9c5714cf6bfab46bbce3a8887d95cdc7
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/frame_host/navigation_controller_impl.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/logging.h"
10 #include "base/metrics/histogram.h"
11 #include "base/strings/string_number_conversions.h" // Temporary
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/time/time.h"
15 #include "base/trace_event/trace_event.h"
16 #include "cc/base/switches.h"
17 #include "components/mime_util/mime_util.h"
18 #include "content/browser/bad_message.h"
19 #include "content/browser/browser_url_handler_impl.h"
20 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
21 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
22 #include "content/browser/frame_host/debug_urls.h"
23 #include "content/browser/frame_host/interstitial_page_impl.h"
24 #include "content/browser/frame_host/navigation_entry_impl.h"
25 #include "content/browser/frame_host/navigation_entry_screenshot_manager.h"
26 #include "content/browser/renderer_host/render_view_host_impl.h" // Temporary
27 #include "content/browser/site_instance_impl.h"
28 #include "content/common/frame_messages.h"
29 #include "content/common/view_messages.h"
30 #include "content/public/browser/browser_context.h"
31 #include "content/public/browser/content_browser_client.h"
32 #include "content/public/browser/invalidate_type.h"
33 #include "content/public/browser/navigation_details.h"
34 #include "content/public/browser/notification_service.h"
35 #include "content/public/browser/notification_types.h"
36 #include "content/public/browser/render_widget_host.h"
37 #include "content/public/browser/render_widget_host_view.h"
38 #include "content/public/browser/storage_partition.h"
39 #include "content/public/browser/user_metrics.h"
40 #include "content/public/common/content_client.h"
41 #include "content/public/common/content_constants.h"
42 #include "content/public/common/content_switches.h"
43 #include "net/base/escape.h"
44 #include "net/base/mime_util.h"
45 #include "net/base/net_util.h"
46 #include "skia/ext/platform_canvas.h"
47 #include "url/url_constants.h"
49 namespace content {
50 namespace {
52 // Invoked when entries have been pruned, or removed. For example, if the
53 // current entries are [google, digg, yahoo], with the current entry google,
54 // and the user types in cnet, then digg and yahoo are pruned.
55 void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
56 bool from_front,
57 int count) {
58 PrunedDetails details;
59 details.from_front = from_front;
60 details.count = count;
61 NotificationService::current()->Notify(
62 NOTIFICATION_NAV_LIST_PRUNED,
63 Source<NavigationController>(nav_controller),
64 Details<PrunedDetails>(&details));
67 // Ensure the given NavigationEntry has a valid state, so that WebKit does not
68 // get confused if we navigate back to it.
70 // An empty state is treated as a new navigation by WebKit, which would mean
71 // losing the navigation entries and generating a new navigation entry after
72 // this one. We don't want that. To avoid this we create a valid state which
73 // WebKit will not treat as a new navigation.
74 void SetPageStateIfEmpty(NavigationEntryImpl* entry) {
75 if (!entry->GetPageState().IsValid())
76 entry->SetPageState(PageState::CreateFromURL(entry->GetURL()));
79 NavigationEntryImpl::RestoreType ControllerRestoreTypeToEntryType(
80 NavigationController::RestoreType type) {
81 switch (type) {
82 case NavigationController::RESTORE_CURRENT_SESSION:
83 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
84 case NavigationController::RESTORE_LAST_SESSION_EXITED_CLEANLY:
85 return NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY;
86 case NavigationController::RESTORE_LAST_SESSION_CRASHED:
87 return NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED;
89 NOTREACHED();
90 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
93 // Configure all the NavigationEntries in entries for restore. This resets
94 // the transition type to reload and makes sure the content state isn't empty.
95 void ConfigureEntriesForRestore(
96 std::vector<linked_ptr<NavigationEntryImpl> >* entries,
97 NavigationController::RestoreType type) {
98 for (size_t i = 0; i < entries->size(); ++i) {
99 // Use a transition type of reload so that we don't incorrectly increase
100 // the typed count.
101 (*entries)[i]->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
102 (*entries)[i]->set_restore_type(ControllerRestoreTypeToEntryType(type));
103 // NOTE(darin): This code is only needed for backwards compat.
104 SetPageStateIfEmpty((*entries)[i].get());
108 // There are two general cases where a navigation is in page:
109 // 1. A fragment navigation, in which the url is kept the same except for the
110 // reference fragment.
111 // 2. A history API navigation (pushState and replaceState). This case is
112 // always in-page, but the urls are not guaranteed to match excluding the
113 // fragment. The relevant spec allows pushState/replaceState to any URL on
114 // the same origin.
115 // However, due to reloads, even identical urls are *not* guaranteed to be
116 // in-page navigations, we have to trust the renderer almost entirely.
117 // The one thing we do know is that cross-origin navigations will *never* be
118 // in-page. Therefore, trust the renderer if the URLs are on the same origin,
119 // and assume the renderer is malicious if a cross-origin navigation claims to
120 // be in-page.
121 bool AreURLsInPageNavigation(const GURL& existing_url,
122 const GURL& new_url,
123 bool renderer_says_in_page,
124 RenderFrameHost* rfh) {
125 WebPreferences prefs = rfh->GetRenderViewHost()->GetWebkitPreferences();
126 bool is_same_origin = existing_url.is_empty() ||
127 // TODO(japhet): We should only permit navigations
128 // originating from about:blank to be in-page if the
129 // about:blank is the first document that frame loaded.
130 // We don't have sufficient information to identify
131 // that case at the moment, so always allow about:blank
132 // for now.
133 existing_url == GURL(url::kAboutBlankURL) ||
134 existing_url.GetOrigin() == new_url.GetOrigin() ||
135 !prefs.web_security_enabled ||
136 (prefs.allow_universal_access_from_file_urls &&
137 existing_url.SchemeIs(url::kFileScheme));
138 if (!is_same_origin && renderer_says_in_page) {
139 bad_message::ReceivedBadMessage(rfh->GetProcess(),
140 bad_message::NC_IN_PAGE_NAVIGATION);
142 return is_same_origin && renderer_says_in_page;
145 // Determines whether or not we should be carrying over a user agent override
146 // between two NavigationEntries.
147 bool ShouldKeepOverride(const NavigationEntry* last_entry) {
148 return last_entry && last_entry->GetIsOverridingUserAgent();
151 } // namespace
153 // NavigationControllerImpl ----------------------------------------------------
155 const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
157 // static
158 size_t NavigationControllerImpl::max_entry_count_for_testing_ =
159 kMaxEntryCountForTestingNotSet;
161 // Should Reload check for post data? The default is true, but is set to false
162 // when testing.
163 static bool g_check_for_repost = true;
165 // static
166 NavigationEntry* NavigationController::CreateNavigationEntry(
167 const GURL& url,
168 const Referrer& referrer,
169 ui::PageTransition transition,
170 bool is_renderer_initiated,
171 const std::string& extra_headers,
172 BrowserContext* browser_context) {
173 // Fix up the given URL before letting it be rewritten, so that any minor
174 // cleanup (e.g., removing leading dots) will not lead to a virtual URL.
175 GURL dest_url(url);
176 BrowserURLHandlerImpl::GetInstance()->FixupURLBeforeRewrite(&dest_url,
177 browser_context);
179 // Allow the browser URL handler to rewrite the URL. This will, for example,
180 // remove "view-source:" from the beginning of the URL to get the URL that
181 // will actually be loaded. This real URL won't be shown to the user, just
182 // used internally.
183 GURL loaded_url(dest_url);
184 bool reverse_on_redirect = false;
185 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
186 &loaded_url, browser_context, &reverse_on_redirect);
188 NavigationEntryImpl* entry = new NavigationEntryImpl(
189 NULL, // The site instance for tabs is sent on navigation
190 // (WebContents::GetSiteInstance).
192 loaded_url,
193 referrer,
194 base::string16(),
195 transition,
196 is_renderer_initiated);
197 entry->SetVirtualURL(dest_url);
198 entry->set_user_typed_url(dest_url);
199 entry->set_update_virtual_url_with_url(reverse_on_redirect);
200 entry->set_extra_headers(extra_headers);
201 return entry;
204 // static
205 void NavigationController::DisablePromptOnRepost() {
206 g_check_for_repost = false;
209 base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
210 base::Time t) {
211 // If |t| is between the water marks, we're in a run of duplicates
212 // or just getting out of it, so increase the high-water mark to get
213 // a time that probably hasn't been used before and return it.
214 if (low_water_mark_ <= t && t <= high_water_mark_) {
215 high_water_mark_ += base::TimeDelta::FromMicroseconds(1);
216 return high_water_mark_;
219 // Otherwise, we're clear of the last duplicate run, so reset the
220 // water marks.
221 low_water_mark_ = high_water_mark_ = t;
222 return t;
225 NavigationControllerImpl::NavigationControllerImpl(
226 NavigationControllerDelegate* delegate,
227 BrowserContext* browser_context)
228 : browser_context_(browser_context),
229 pending_entry_(NULL),
230 failed_pending_entry_id_(0),
231 failed_pending_entry_should_replace_(false),
232 last_committed_entry_index_(-1),
233 pending_entry_index_(-1),
234 transient_entry_index_(-1),
235 delegate_(delegate),
236 max_restored_page_id_(-1),
237 ssl_manager_(this),
238 needs_reload_(false),
239 is_initial_navigation_(true),
240 in_navigate_to_pending_entry_(false),
241 pending_reload_(NO_RELOAD),
242 get_timestamp_callback_(base::Bind(&base::Time::Now)),
243 screenshot_manager_(new NavigationEntryScreenshotManager(this)) {
244 DCHECK(browser_context_);
247 NavigationControllerImpl::~NavigationControllerImpl() {
248 DiscardNonCommittedEntriesInternal();
251 WebContents* NavigationControllerImpl::GetWebContents() const {
252 return delegate_->GetWebContents();
255 BrowserContext* NavigationControllerImpl::GetBrowserContext() const {
256 return browser_context_;
259 void NavigationControllerImpl::SetBrowserContext(
260 BrowserContext* browser_context) {
261 browser_context_ = browser_context;
264 void NavigationControllerImpl::Restore(
265 int selected_navigation,
266 RestoreType type,
267 std::vector<NavigationEntry*>* entries) {
268 // Verify that this controller is unused and that the input is valid.
269 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
270 DCHECK(selected_navigation >= 0 &&
271 selected_navigation < static_cast<int>(entries->size()));
273 needs_reload_ = true;
274 for (size_t i = 0; i < entries->size(); ++i) {
275 NavigationEntryImpl* entry =
276 NavigationEntryImpl::FromNavigationEntry((*entries)[i]);
277 entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
279 entries->clear();
281 // And finish the restore.
282 FinishRestore(selected_navigation, type);
285 void NavigationControllerImpl::Reload(bool check_for_repost) {
286 ReloadInternal(check_for_repost, RELOAD);
288 void NavigationControllerImpl::ReloadIgnoringCache(bool check_for_repost) {
289 ReloadInternal(check_for_repost, RELOAD_IGNORING_CACHE);
291 void NavigationControllerImpl::ReloadOriginalRequestURL(bool check_for_repost) {
292 ReloadInternal(check_for_repost, RELOAD_ORIGINAL_REQUEST_URL);
295 void NavigationControllerImpl::ReloadInternal(bool check_for_repost,
296 ReloadType reload_type) {
297 if (transient_entry_index_ != -1) {
298 // If an interstitial is showing, treat a reload as a navigation to the
299 // transient entry's URL.
300 NavigationEntryImpl* transient_entry = GetTransientEntry();
301 if (!transient_entry)
302 return;
303 LoadURL(transient_entry->GetURL(),
304 Referrer(),
305 ui::PAGE_TRANSITION_RELOAD,
306 transient_entry->extra_headers());
307 return;
310 NavigationEntryImpl* entry = NULL;
311 int current_index = -1;
313 // If we are reloading the initial navigation, just use the current
314 // pending entry. Otherwise look up the current entry.
315 if (IsInitialNavigation() && pending_entry_) {
316 entry = pending_entry_;
317 // The pending entry might be in entries_ (e.g., after a Clone), so we
318 // should also update the current_index.
319 current_index = pending_entry_index_;
320 } else {
321 DiscardNonCommittedEntriesInternal();
322 current_index = GetCurrentEntryIndex();
323 if (current_index != -1) {
324 entry = GetEntryAtIndex(current_index);
328 // If we are no where, then we can't reload. TODO(darin): We should add a
329 // CanReload method.
330 if (!entry)
331 return;
333 if (reload_type == NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL &&
334 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
335 // We may have been redirected when navigating to the current URL.
336 // Use the URL the user originally intended to visit, if it's valid and if a
337 // POST wasn't involved; the latter case avoids issues with sending data to
338 // the wrong page.
339 entry->SetURL(entry->GetOriginalRequestURL());
340 entry->SetReferrer(Referrer());
343 if (g_check_for_repost && check_for_repost &&
344 entry->GetHasPostData()) {
345 // The user is asking to reload a page with POST data. Prompt to make sure
346 // they really want to do this. If they do, the dialog will call us back
347 // with check_for_repost = false.
348 delegate_->NotifyBeforeFormRepostWarningShow();
350 pending_reload_ = reload_type;
351 delegate_->ActivateAndShowRepostFormWarningDialog();
352 } else {
353 if (!IsInitialNavigation())
354 DiscardNonCommittedEntriesInternal();
356 // If we are reloading an entry that no longer belongs to the current
357 // site instance (for example, refreshing a page for just installed app),
358 // the reload must happen in a new process.
359 // The new entry must have a new page_id and site instance, so it behaves
360 // as new navigation (which happens to clear forward history).
361 // Tabs that are discarded due to low memory conditions may not have a site
362 // instance, and should not be treated as a cross-site reload.
363 SiteInstanceImpl* site_instance = entry->site_instance();
364 // Permit reloading guests without further checks.
365 bool is_isolated_guest = site_instance && site_instance->HasProcess() &&
366 site_instance->GetProcess()->IsIsolatedGuest();
367 if (!is_isolated_guest && site_instance &&
368 site_instance->HasWrongProcessForURL(entry->GetURL())) {
369 // Create a navigation entry that resembles the current one, but do not
370 // copy page id, site instance, content state, or timestamp.
371 NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry(
372 CreateNavigationEntry(
373 entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(),
374 false, entry->extra_headers(), browser_context_));
376 // Mark the reload type as NO_RELOAD, so navigation will not be considered
377 // a reload in the renderer.
378 reload_type = NavigationController::NO_RELOAD;
380 nav_entry->set_should_replace_entry(true);
381 pending_entry_ = nav_entry;
382 } else {
383 pending_entry_ = entry;
384 pending_entry_index_ = current_index;
386 // The title of the page being reloaded might have been removed in the
387 // meanwhile, so we need to revert to the default title upon reload and
388 // invalidate the previously cached title (SetTitle will do both).
389 // See Chromium issue 96041.
390 pending_entry_->SetTitle(base::string16());
392 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
395 NavigateToPendingEntry(reload_type);
399 void NavigationControllerImpl::CancelPendingReload() {
400 DCHECK(pending_reload_ != NO_RELOAD);
401 pending_reload_ = NO_RELOAD;
404 void NavigationControllerImpl::ContinuePendingReload() {
405 if (pending_reload_ == NO_RELOAD) {
406 NOTREACHED();
407 } else {
408 ReloadInternal(false, pending_reload_);
409 pending_reload_ = NO_RELOAD;
413 bool NavigationControllerImpl::IsInitialNavigation() const {
414 return is_initial_navigation_;
417 NavigationEntryImpl* NavigationControllerImpl::GetEntryWithPageID(
418 SiteInstance* instance, int32 page_id) const {
419 int index = GetEntryIndexWithPageID(instance, page_id);
420 return (index != -1) ? entries_[index].get() : NULL;
423 void NavigationControllerImpl::LoadEntry(NavigationEntryImpl* entry) {
424 // When navigating to a new page, we don't know for sure if we will actually
425 // end up leaving the current page. The new page load could for example
426 // result in a download or a 'no content' response (e.g., a mailto: URL).
427 SetPendingEntry(entry);
428 NavigateToPendingEntry(NO_RELOAD);
431 void NavigationControllerImpl::SetPendingEntry(NavigationEntryImpl* entry) {
432 DiscardNonCommittedEntriesInternal();
433 pending_entry_ = entry;
434 NotificationService::current()->Notify(
435 NOTIFICATION_NAV_ENTRY_PENDING,
436 Source<NavigationController>(this),
437 Details<NavigationEntry>(entry));
440 NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() const {
441 if (transient_entry_index_ != -1)
442 return entries_[transient_entry_index_].get();
443 if (pending_entry_)
444 return pending_entry_;
445 return GetLastCommittedEntry();
448 NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() const {
449 if (transient_entry_index_ != -1)
450 return entries_[transient_entry_index_].get();
451 // The pending entry is safe to return for new (non-history), browser-
452 // initiated navigations. Most renderer-initiated navigations should not
453 // show the pending entry, to prevent URL spoof attacks.
455 // We make an exception for renderer-initiated navigations in new tabs, as
456 // long as no other page has tried to access the initial empty document in
457 // the new tab. If another page modifies this blank page, a URL spoof is
458 // possible, so we must stop showing the pending entry.
459 bool safe_to_show_pending =
460 pending_entry_ &&
461 // Require a new navigation.
462 pending_entry_index_ == -1 &&
463 // Require either browser-initiated or an unmodified new tab.
464 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
466 // Also allow showing the pending entry for history navigations in a new tab,
467 // such as Ctrl+Back. In this case, no existing page is visible and no one
468 // can script the new tab before it commits.
469 if (!safe_to_show_pending &&
470 pending_entry_ &&
471 pending_entry_index_ != -1 &&
472 IsInitialNavigation() &&
473 !pending_entry_->is_renderer_initiated())
474 safe_to_show_pending = true;
476 if (safe_to_show_pending)
477 return pending_entry_;
478 return GetLastCommittedEntry();
481 int NavigationControllerImpl::GetCurrentEntryIndex() const {
482 if (transient_entry_index_ != -1)
483 return transient_entry_index_;
484 if (pending_entry_index_ != -1)
485 return pending_entry_index_;
486 return last_committed_entry_index_;
489 NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() const {
490 if (last_committed_entry_index_ == -1)
491 return NULL;
492 return entries_[last_committed_entry_index_].get();
495 bool NavigationControllerImpl::CanViewSource() const {
496 const std::string& mime_type = delegate_->GetContentsMimeType();
497 bool is_viewable_mime_type =
498 mime_util::IsSupportedNonImageMimeType(mime_type) &&
499 !net::IsSupportedMediaMimeType(mime_type);
500 NavigationEntry* visible_entry = GetVisibleEntry();
501 return visible_entry && !visible_entry->IsViewSourceMode() &&
502 is_viewable_mime_type && !delegate_->GetInterstitialPage();
505 int NavigationControllerImpl::GetLastCommittedEntryIndex() const {
506 return last_committed_entry_index_;
509 int NavigationControllerImpl::GetEntryCount() const {
510 DCHECK(entries_.size() <= max_entry_count());
511 return static_cast<int>(entries_.size());
514 NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(
515 int index) const {
516 return entries_.at(index).get();
519 NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(
520 int offset) const {
521 int index = GetIndexForOffset(offset);
522 if (index < 0 || index >= GetEntryCount())
523 return NULL;
525 return entries_[index].get();
528 int NavigationControllerImpl::GetIndexForOffset(int offset) const {
529 return GetCurrentEntryIndex() + offset;
532 void NavigationControllerImpl::TakeScreenshot() {
533 screenshot_manager_->TakeScreenshot();
536 void NavigationControllerImpl::SetScreenshotManager(
537 NavigationEntryScreenshotManager* manager) {
538 screenshot_manager_.reset(manager ? manager :
539 new NavigationEntryScreenshotManager(this));
542 bool NavigationControllerImpl::CanGoBack() const {
543 return entries_.size() > 1 && GetCurrentEntryIndex() > 0;
546 bool NavigationControllerImpl::CanGoForward() const {
547 int index = GetCurrentEntryIndex();
548 return index >= 0 && index < (static_cast<int>(entries_.size()) - 1);
551 bool NavigationControllerImpl::CanGoToOffset(int offset) const {
552 int index = GetIndexForOffset(offset);
553 return index >= 0 && index < GetEntryCount();
556 void NavigationControllerImpl::GoBack() {
557 if (!CanGoBack()) {
558 NOTREACHED();
559 return;
562 // Base the navigation on where we are now...
563 int current_index = GetCurrentEntryIndex();
565 DiscardNonCommittedEntries();
567 pending_entry_index_ = current_index - 1;
568 entries_[pending_entry_index_]->SetTransitionType(
569 ui::PageTransitionFromInt(
570 entries_[pending_entry_index_]->GetTransitionType() |
571 ui::PAGE_TRANSITION_FORWARD_BACK));
572 NavigateToPendingEntry(NO_RELOAD);
575 void NavigationControllerImpl::GoForward() {
576 if (!CanGoForward()) {
577 NOTREACHED();
578 return;
581 bool transient = (transient_entry_index_ != -1);
583 // Base the navigation on where we are now...
584 int current_index = GetCurrentEntryIndex();
586 DiscardNonCommittedEntries();
588 pending_entry_index_ = current_index;
589 // If there was a transient entry, we removed it making the current index
590 // the next page.
591 if (!transient)
592 pending_entry_index_++;
594 entries_[pending_entry_index_]->SetTransitionType(
595 ui::PageTransitionFromInt(
596 entries_[pending_entry_index_]->GetTransitionType() |
597 ui::PAGE_TRANSITION_FORWARD_BACK));
598 NavigateToPendingEntry(NO_RELOAD);
601 void NavigationControllerImpl::GoToIndex(int index) {
602 if (index < 0 || index >= static_cast<int>(entries_.size())) {
603 NOTREACHED();
604 return;
607 if (transient_entry_index_ != -1) {
608 if (index == transient_entry_index_) {
609 // Nothing to do when navigating to the transient.
610 return;
612 if (index > transient_entry_index_) {
613 // Removing the transient is goint to shift all entries by 1.
614 index--;
618 DiscardNonCommittedEntries();
620 pending_entry_index_ = index;
621 entries_[pending_entry_index_]->SetTransitionType(
622 ui::PageTransitionFromInt(
623 entries_[pending_entry_index_]->GetTransitionType() |
624 ui::PAGE_TRANSITION_FORWARD_BACK));
625 NavigateToPendingEntry(NO_RELOAD);
628 void NavigationControllerImpl::GoToOffset(int offset) {
629 if (!CanGoToOffset(offset))
630 return;
632 GoToIndex(GetIndexForOffset(offset));
635 bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
636 if (index == last_committed_entry_index_ ||
637 index == pending_entry_index_)
638 return false;
640 RemoveEntryAtIndexInternal(index);
641 return true;
644 void NavigationControllerImpl::UpdateVirtualURLToURL(
645 NavigationEntryImpl* entry, const GURL& new_url) {
646 GURL new_virtual_url(new_url);
647 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
648 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
649 entry->SetVirtualURL(new_virtual_url);
653 void NavigationControllerImpl::LoadURL(
654 const GURL& url,
655 const Referrer& referrer,
656 ui::PageTransition transition,
657 const std::string& extra_headers) {
658 LoadURLParams params(url);
659 params.referrer = referrer;
660 params.transition_type = transition;
661 params.extra_headers = extra_headers;
662 LoadURLWithParams(params);
665 void NavigationControllerImpl::LoadURLWithParams(const LoadURLParams& params) {
666 TRACE_EVENT1("browser,navigation",
667 "NavigationControllerImpl::LoadURLWithParams",
668 "url", params.url.possibly_invalid_spec());
669 if (HandleDebugURL(params.url, params.transition_type)) {
670 // If Telemetry is running, allow the URL load to proceed as if it's
671 // unhandled, otherwise Telemetry can't tell if Navigation completed.
672 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
673 cc::switches::kEnableGpuBenchmarking))
674 return;
677 // Any renderer-side debug URLs or javascript: URLs should be ignored if the
678 // renderer process is not live, unless it is the initial navigation of the
679 // tab.
680 if (IsRendererDebugURL(params.url)) {
681 // TODO(creis): Find the RVH for the correct frame.
682 if (!delegate_->GetRenderViewHost()->IsRenderViewLive() &&
683 !IsInitialNavigation())
684 return;
687 // Checks based on params.load_type.
688 switch (params.load_type) {
689 case LOAD_TYPE_DEFAULT:
690 break;
691 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
692 if (!params.url.SchemeIs(url::kHttpScheme) &&
693 !params.url.SchemeIs(url::kHttpsScheme)) {
694 NOTREACHED() << "Http post load must use http(s) scheme.";
695 return;
697 break;
698 case LOAD_TYPE_DATA:
699 if (!params.url.SchemeIs(url::kDataScheme)) {
700 NOTREACHED() << "Data load must use data scheme.";
701 return;
703 break;
704 default:
705 NOTREACHED();
706 break;
709 // The user initiated a load, we don't need to reload anymore.
710 needs_reload_ = false;
712 bool override = false;
713 switch (params.override_user_agent) {
714 case UA_OVERRIDE_INHERIT:
715 override = ShouldKeepOverride(GetLastCommittedEntry());
716 break;
717 case UA_OVERRIDE_TRUE:
718 override = true;
719 break;
720 case UA_OVERRIDE_FALSE:
721 override = false;
722 break;
723 default:
724 NOTREACHED();
725 break;
728 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
729 CreateNavigationEntry(
730 params.url,
731 params.referrer,
732 params.transition_type,
733 params.is_renderer_initiated,
734 params.extra_headers,
735 browser_context_));
736 if (!params.frame_name.empty()) {
737 // This is only used for navigating subframes in tests.
738 FrameTreeNode* named_frame =
739 delegate_->GetFrameTree()->FindByName(params.frame_name);
740 if (named_frame)
741 entry->set_frame_tree_node_id(named_frame->frame_tree_node_id());
743 if (params.frame_tree_node_id != -1)
744 entry->set_frame_tree_node_id(params.frame_tree_node_id);
745 entry->set_source_site_instance(
746 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
747 if (params.redirect_chain.size() > 0)
748 entry->SetRedirectChain(params.redirect_chain);
749 // Don't allow an entry replacement if there is no entry to replace.
750 // http://crbug.com/457149
751 if (params.should_replace_current_entry && entries_.size() > 0)
752 entry->set_should_replace_entry(true);
753 entry->set_should_clear_history_list(params.should_clear_history_list);
754 entry->SetIsOverridingUserAgent(override);
755 entry->set_transferred_global_request_id(
756 params.transferred_global_request_id);
758 #if defined(OS_ANDROID)
759 if (params.intent_received_timestamp > 0) {
760 entry->set_intent_received_timestamp(
761 base::TimeTicks() +
762 base::TimeDelta::FromMilliseconds(params.intent_received_timestamp));
764 #endif
766 switch (params.load_type) {
767 case LOAD_TYPE_DEFAULT:
768 break;
769 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
770 entry->SetHasPostData(true);
771 entry->SetBrowserInitiatedPostData(
772 params.browser_initiated_post_data.get());
773 break;
774 case LOAD_TYPE_DATA:
775 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
776 entry->SetVirtualURL(params.virtual_url_for_data_url);
777 entry->SetCanLoadLocalResources(params.can_load_local_resources);
778 break;
779 default:
780 NOTREACHED();
781 break;
784 LoadEntry(entry);
787 bool NavigationControllerImpl::RendererDidNavigate(
788 RenderFrameHostImpl* rfh,
789 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
790 LoadCommittedDetails* details) {
791 is_initial_navigation_ = false;
793 // Save the previous state before we clobber it.
794 if (GetLastCommittedEntry()) {
795 details->previous_url = GetLastCommittedEntry()->GetURL();
796 details->previous_entry_index = GetLastCommittedEntryIndex();
797 } else {
798 details->previous_url = GURL();
799 details->previous_entry_index = -1;
802 // If we have a pending entry at this point, it should have a SiteInstance.
803 // Restored entries start out with a null SiteInstance, but we should have
804 // assigned one in NavigateToPendingEntry.
805 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance());
807 // If we are doing a cross-site reload, we need to replace the existing
808 // navigation entry, not add another entry to the history. This has the side
809 // effect of removing forward browsing history, if such existed. Or if we are
810 // doing a cross-site redirect navigation, we will do a similar thing.
812 // If this is an error load, we may have already removed the pending entry
813 // when we got the notice of the load failure. If so, look at the copy of the
814 // pending parameters that were saved.
815 if (params.url_is_unreachable && failed_pending_entry_id_ != 0) {
816 details->did_replace_entry = failed_pending_entry_should_replace_;
817 } else {
818 details->did_replace_entry = pending_entry_ &&
819 pending_entry_->should_replace_entry();
822 // Do navigation-type specific actions. These will make and commit an entry.
823 details->type = ClassifyNavigation(rfh, params);
824 #if DCHECK_IS_ON()
825 // For site-per-process, both ClassifyNavigation methods get it wrong (see
826 // http://crbug.com/464014) so don't worry about a mismatch if that's the
827 // case.
828 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
829 switches::kSitePerProcess)) {
830 NavigationType new_type = ClassifyNavigationWithoutPageID(rfh, params);
831 // There's constant disagreements over SAME_PAGE between the two classifiers
832 // so ignore disagreements if that's the case. Otherwise, enforce agreement.
833 // TODO(avi): Work this out.
834 if (details->type != NAVIGATION_TYPE_SAME_PAGE &&
835 new_type != NAVIGATION_TYPE_SAME_PAGE) {
836 DCHECK_EQ(details->type, new_type);
839 #endif // DCHECK_IS_ON()
841 // is_in_page must be computed before the entry gets committed.
842 details->is_in_page = AreURLsInPageNavigation(rfh->GetLastCommittedURL(),
843 params.url, params.was_within_same_page, rfh);
845 switch (details->type) {
846 case NAVIGATION_TYPE_NEW_PAGE:
847 RendererDidNavigateToNewPage(rfh, params, details->did_replace_entry);
848 break;
849 case NAVIGATION_TYPE_EXISTING_PAGE:
850 RendererDidNavigateToExistingPage(rfh, params);
851 break;
852 case NAVIGATION_TYPE_SAME_PAGE:
853 RendererDidNavigateToSamePage(rfh, params);
854 break;
855 case NAVIGATION_TYPE_IN_PAGE:
856 RendererDidNavigateInPage(rfh, params, &details->did_replace_entry);
857 break;
858 case NAVIGATION_TYPE_NEW_SUBFRAME:
859 RendererDidNavigateNewSubframe(rfh, params);
860 break;
861 case NAVIGATION_TYPE_AUTO_SUBFRAME:
862 if (!RendererDidNavigateAutoSubframe(rfh, params))
863 return false;
864 break;
865 case NAVIGATION_TYPE_NAV_IGNORE:
866 // If a pending navigation was in progress, this canceled it. We should
867 // discard it and make sure it is removed from the URL bar. After that,
868 // there is nothing we can do with this navigation, so we just return to
869 // the caller that nothing has happened.
870 if (pending_entry_) {
871 DiscardNonCommittedEntries();
872 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
874 return false;
875 default:
876 NOTREACHED();
879 // At this point, we know that the navigation has just completed, so
880 // record the time.
882 // TODO(akalin): Use "sane time" as described in
883 // http://www.chromium.org/developers/design-documents/sane-time .
884 base::Time timestamp =
885 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
886 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
887 << timestamp.ToInternalValue();
889 // We should not have a pending entry anymore. Clear it again in case any
890 // error cases above forgot to do so.
891 DiscardNonCommittedEntriesInternal();
893 // All committed entries should have nonempty content state so WebKit doesn't
894 // get confused when we go back to them (see the function for details).
895 DCHECK(params.page_state.IsValid());
896 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
897 active_entry->SetTimestamp(timestamp);
898 active_entry->SetHttpStatusCode(params.http_status_code);
899 active_entry->SetPageState(params.page_state);
900 active_entry->SetRedirectChain(params.redirects);
902 // Use histogram to track memory impact of redirect chain because it's now
903 // not cleared for committed entries.
904 size_t redirect_chain_size = 0;
905 for (size_t i = 0; i < params.redirects.size(); ++i) {
906 redirect_chain_size += params.redirects[i].spec().length();
908 UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size);
910 // Once it is committed, we no longer need to track several pieces of state on
911 // the entry.
912 active_entry->ResetForCommit();
914 // The active entry's SiteInstance should match our SiteInstance.
915 // TODO(creis): This check won't pass for subframes until we create entries
916 // for subframe navigations.
917 if (ui::PageTransitionIsMainFrame(params.transition))
918 CHECK(active_entry->site_instance() == rfh->GetSiteInstance());
920 // Remember the bindings the renderer process has at this point, so that
921 // we do not grant this entry additional bindings if we come back to it.
922 active_entry->SetBindings(rfh->GetEnabledBindings());
924 // Now prep the rest of the details for the notification and broadcast.
925 details->entry = active_entry;
926 details->is_main_frame =
927 ui::PageTransitionIsMainFrame(params.transition);
928 details->serialized_security_info = params.security_info;
929 details->http_status_code = params.http_status_code;
930 NotifyNavigationEntryCommitted(details);
932 return true;
935 NavigationType NavigationControllerImpl::ClassifyNavigation(
936 RenderFrameHostImpl* rfh,
937 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) const {
938 if (params.page_id == -1) {
939 // TODO(nasko, creis): An out-of-process child frame has no way of knowing
940 // the page_id of its parent, so it is passing back -1. The semantics here
941 // should be re-evaluated during session history refactor (see
942 // http://crbug.com/236848 and in particular http://crbug.com/464014). For
943 // now, we assume this means the child frame loaded and proceed. Note that
944 // this may do the wrong thing for cross-process AUTO_SUBFRAME navigations.
945 if (rfh->IsCrossProcessSubframe())
946 return NAVIGATION_TYPE_NEW_SUBFRAME;
948 // The renderer generates the page IDs, and so if it gives us the invalid
949 // page ID (-1) we know it didn't actually navigate. This happens in a few
950 // cases:
952 // - If a page makes a popup navigated to about blank, and then writes
953 // stuff like a subframe navigated to a real page. We'll get the commit
954 // for the subframe, but there won't be any commit for the outer page.
956 // - We were also getting these for failed loads (for example, bug 21849).
957 // The guess is that we get a "load commit" for the alternate error page,
958 // but that doesn't affect the page ID, so we get the "old" one, which
959 // could be invalid. This can also happen for a cross-site transition
960 // that causes us to swap processes. Then the error page load will be in
961 // a new process with no page IDs ever assigned (and hence a -1 value),
962 // yet the navigation controller still might have previous pages in its
963 // list.
965 // In these cases, there's nothing we can do with them, so ignore.
966 return NAVIGATION_TYPE_NAV_IGNORE;
969 if (params.page_id > delegate_->GetMaxPageIDForSiteInstance(
970 rfh->GetSiteInstance())) {
971 // Greater page IDs than we've ever seen before are new pages. We may or may
972 // not have a pending entry for the page, and this may or may not be the
973 // main frame.
974 if (ui::PageTransitionIsMainFrame(params.transition))
975 return NAVIGATION_TYPE_NEW_PAGE;
977 // When this is a new subframe navigation, we should have a committed page
978 // for which it's a suframe in. This may not be the case when an iframe is
979 // navigated on a popup navigated to about:blank (the iframe would be
980 // written into the popup by script on the main page). For these cases,
981 // there isn't any navigation stuff we can do, so just ignore it.
982 if (!GetLastCommittedEntry())
983 return NAVIGATION_TYPE_NAV_IGNORE;
985 // Valid subframe navigation.
986 return NAVIGATION_TYPE_NEW_SUBFRAME;
989 // We only clear the session history when navigating to a new page.
990 DCHECK(!params.history_list_was_cleared);
992 // Now we know that the notification is for an existing page. Find that entry.
993 int existing_entry_index = GetEntryIndexWithPageID(
994 rfh->GetSiteInstance(),
995 params.page_id);
996 if (existing_entry_index == -1) {
997 // The page was not found. It could have been pruned because of the limit on
998 // back/forward entries (not likely since we'll usually tell it to navigate
999 // to such entries). It could also mean that the renderer is smoking crack.
1000 NOTREACHED();
1002 // Because the unknown entry has committed, we risk showing the wrong URL in
1003 // release builds. Instead, we'll kill the renderer process to be safe.
1004 LOG(ERROR) << "terminating renderer for bad navigation: " << params.url;
1005 RecordAction(base::UserMetricsAction("BadMessageTerminate_NC"));
1007 // Temporary code so we can get more information. Format:
1008 // http://url/foo.html#page1#max3#frame1#ids:2_Nx,1_1x,3_2
1009 std::string temp = params.url.spec();
1010 temp.append("#page");
1011 temp.append(base::IntToString(params.page_id));
1012 temp.append("#max");
1013 temp.append(base::IntToString(delegate_->GetMaxPageID()));
1014 temp.append("#frame");
1015 temp.append(base::IntToString(rfh->GetRoutingID()));
1016 temp.append("#ids");
1017 for (int i = 0; i < static_cast<int>(entries_.size()); ++i) {
1018 // Append entry metadata (e.g., 3_7x):
1019 // 3: page_id
1020 // 7: SiteInstance ID, or N for null
1021 // x: appended if not from the current SiteInstance
1022 temp.append(base::IntToString(entries_[i]->GetPageID()));
1023 temp.append("_");
1024 if (entries_[i]->site_instance())
1025 temp.append(base::IntToString(entries_[i]->site_instance()->GetId()));
1026 else
1027 temp.append("N");
1028 if (entries_[i]->site_instance() != rfh->GetSiteInstance())
1029 temp.append("x");
1030 temp.append(",");
1032 GURL url(temp);
1033 rfh->render_view_host()->Send(new ViewMsg_TempCrashWithData(url));
1034 return NAVIGATION_TYPE_NAV_IGNORE;
1036 NavigationEntryImpl* existing_entry = entries_[existing_entry_index].get();
1038 if (!ui::PageTransitionIsMainFrame(params.transition)) {
1039 // All manual subframes would get new IDs and were handled above, so we
1040 // know this is auto. Since the current page was found in the navigation
1041 // entry list, we're guaranteed to have a last committed entry.
1042 DCHECK(GetLastCommittedEntry());
1043 return NAVIGATION_TYPE_AUTO_SUBFRAME;
1046 // Anything below here we know is a main frame navigation.
1047 if (pending_entry_ &&
1048 !pending_entry_->is_renderer_initiated() &&
1049 existing_entry != pending_entry_ &&
1050 pending_entry_->GetPageID() == -1 &&
1051 existing_entry == GetLastCommittedEntry() &&
1052 !params.was_within_same_page) {
1053 // In order to prevent unrelated pending entries from interfering with
1054 // this classification, make sure that the URL committed matches the URLs
1055 // of both the existing entry and the pending entry. There might have been
1056 // a redirection, though, so allow both the existing and pending entries
1057 // to match either the final URL that committed, or the original one
1058 // before redirection.
1059 GURL original_url;
1060 if (params.redirects.size())
1061 original_url = params.redirects[0];
1063 if ((params.url == existing_entry->GetURL() ||
1064 original_url == existing_entry->GetURL()) &&
1065 (params.url == pending_entry_->GetURL() ||
1066 original_url == pending_entry_->GetURL())) {
1067 // In this case, we have a pending entry for a URL but Blink didn't do a
1068 // new navigation. This happens when you press enter in the URL bar to
1069 // reload. We will create a pending entry, but Blink will convert it to a
1070 // reload since it's the same page and not create a new entry for it (the
1071 // user doesn't want to have a new back/forward entry when they do this).
1072 // If this matches the last committed entry, we want to just ignore the
1073 // pending entry and go back to where we were (the "existing entry").
1074 return NAVIGATION_TYPE_SAME_PAGE;
1078 // Any toplevel navigations with the same base (minus the reference fragment)
1079 // are in-page navigations. We weeded out subframe navigations above. Most of
1080 // the time this doesn't matter since WebKit doesn't tell us about subframe
1081 // navigations that don't actually navigate, but it can happen when there is
1082 // an encoding override (it always sends a navigation request).
1083 if (AreURLsInPageNavigation(existing_entry->GetURL(), params.url,
1084 params.was_within_same_page, rfh)) {
1085 return NAVIGATION_TYPE_IN_PAGE;
1088 // Since we weeded out "new" navigations above, we know this is an existing
1089 // (back/forward) navigation.
1090 return NAVIGATION_TYPE_EXISTING_PAGE;
1093 NavigationType NavigationControllerImpl::ClassifyNavigationWithoutPageID(
1094 RenderFrameHostImpl* rfh,
1095 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) const {
1096 if (params.did_create_new_entry) {
1097 // A new entry. We may or may not have a pending entry for the page, and
1098 // this may or may not be the main frame.
1099 if (ui::PageTransitionIsMainFrame(params.transition)) {
1100 // TODO(avi): I want to use |if (!rfh->GetParent())| here but lots of unit
1101 // tests fake auto subframe commits by sending the main frame a
1102 // PAGE_TRANSITION_AUTO_SUBFRAME transition. Fix those, and adjust here.
1103 return NAVIGATION_TYPE_NEW_PAGE;
1106 // When this is a new subframe navigation, we should have a committed page
1107 // in which it's a subframe. This may not be the case when an iframe is
1108 // navigated on a popup navigated to about:blank (the iframe would be
1109 // written into the popup by script on the main page). For these cases,
1110 // there isn't any navigation stuff we can do, so just ignore it.
1111 if (!GetLastCommittedEntry())
1112 return NAVIGATION_TYPE_NAV_IGNORE;
1114 // Valid subframe navigation.
1115 return NAVIGATION_TYPE_NEW_SUBFRAME;
1118 // We only clear the session history when navigating to a new page.
1119 DCHECK(!params.history_list_was_cleared);
1121 if (!ui::PageTransitionIsMainFrame(params.transition)) {
1122 // All manual subframes would be did_create_new_entry and handled above, so
1123 // we know this is auto.
1124 if (GetLastCommittedEntry()) {
1125 return NAVIGATION_TYPE_AUTO_SUBFRAME;
1126 } else {
1127 // We ignore subframes created in non-committed pages; we'd appreciate if
1128 // people stopped doing that.
1129 return NAVIGATION_TYPE_NAV_IGNORE;
1133 if (params.nav_entry_id == 0) {
1134 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1135 // create a new page.
1137 // Just like above in the did_create_new_entry case, it's possible to
1138 // scribble onto an uncommitted page. Again, there isn't any navigation
1139 // stuff that we can do, so ignore it here as well.
1140 if (!GetLastCommittedEntry())
1141 return NAVIGATION_TYPE_NAV_IGNORE;
1143 if (params.was_within_same_page) {
1144 // This is history.replaceState(), which is renderer-initiated yet within
1145 // the same page.
1146 return NAVIGATION_TYPE_IN_PAGE;
1147 } else {
1148 // This is history.reload() or a client-side redirect.
1149 return NAVIGATION_TYPE_EXISTING_PAGE;
1153 if (pending_entry_ && pending_entry_index_ == -1 &&
1154 pending_entry_->GetUniqueID() == params.nav_entry_id) {
1155 // In this case, we have a pending entry for a load of a new URL but Blink
1156 // didn't do a new navigation (params.did_create_new_entry). This happens
1157 // when you press enter in the URL bar to reload. We will create a pending
1158 // entry, but Blink will convert it to a reload since it's the same page and
1159 // not create a new entry for it (the user doesn't want to have a new
1160 // back/forward entry when they do this). Therefore we want to just ignore
1161 // the pending entry and go back to where we were (the "existing entry").
1162 return NAVIGATION_TYPE_SAME_PAGE;
1165 if (params.intended_as_new_entry) {
1166 // This was intended to be a navigation to a new entry but the pending entry
1167 // got cleared in the meanwhile. Classify as EXISTING_PAGE because we may or
1168 // may not have a pending entry.
1169 return NAVIGATION_TYPE_EXISTING_PAGE;
1172 if (params.url_is_unreachable && failed_pending_entry_id_ != 0 &&
1173 params.nav_entry_id == failed_pending_entry_id_) {
1174 // If the renderer was going to a new pending entry that got cleared because
1175 // of an error, this is the case of the user trying to retry a failed load
1176 // by pressing return. Classify as EXISTING_PAGE because we probably don't
1177 // have a pending entry.
1178 return NAVIGATION_TYPE_EXISTING_PAGE;
1181 // Now we know that the notification is for an existing page. Find that entry.
1182 int existing_entry_index = GetEntryIndexWithUniqueID(params.nav_entry_id);
1183 if (existing_entry_index == -1) {
1184 // The page was not found. It could have been pruned because of the limit on
1185 // back/forward entries (not likely since we'll usually tell it to navigate
1186 // to such entries). It could also mean that the renderer is smoking crack.
1187 // TODO(avi): Crash the renderer like we do in the old ClassifyNavigation?
1188 NOTREACHED() << "Could not find nav entry with id " << params.nav_entry_id;
1189 return NAVIGATION_TYPE_NAV_IGNORE;
1192 // Any top-level navigations with the same base (minus the reference fragment)
1193 // are in-page navigations. (We weeded out subframe navigations above.) Most
1194 // of the time this doesn't matter since Blink doesn't tell us about subframe
1195 // navigations that don't actually navigate, but it can happen when there is
1196 // an encoding override (it always sends a navigation request).
1197 NavigationEntryImpl* existing_entry = entries_[existing_entry_index].get();
1198 if (AreURLsInPageNavigation(existing_entry->GetURL(), params.url,
1199 params.was_within_same_page, rfh)) {
1200 return NAVIGATION_TYPE_IN_PAGE;
1203 // Since we weeded out "new" navigations above, we know this is an existing
1204 // (back/forward) navigation.
1205 return NAVIGATION_TYPE_EXISTING_PAGE;
1208 void NavigationControllerImpl::RendererDidNavigateToNewPage(
1209 RenderFrameHostImpl* rfh,
1210 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
1211 bool replace_entry) {
1212 NavigationEntryImpl* new_entry;
1213 bool update_virtual_url;
1214 // Only make a copy of the pending entry if it is appropriate for the new page
1215 // that was just loaded. We verify this at a coarse grain by checking that
1216 // the SiteInstance hasn't been assigned to something else.
1217 if (pending_entry_ &&
1218 (!pending_entry_->site_instance() ||
1219 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
1220 new_entry = pending_entry_->Clone();
1222 update_virtual_url = new_entry->update_virtual_url_with_url();
1223 } else {
1224 new_entry = new NavigationEntryImpl;
1226 // Find out whether the new entry needs to update its virtual URL on URL
1227 // change and set up the entry accordingly. This is needed to correctly
1228 // update the virtual URL when replaceState is called after a pushState.
1229 GURL url = params.url;
1230 bool needs_update = false;
1231 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1232 &url, browser_context_, &needs_update);
1233 new_entry->set_update_virtual_url_with_url(needs_update);
1235 // When navigating to a new page, give the browser URL handler a chance to
1236 // update the virtual URL based on the new URL. For example, this is needed
1237 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1238 // the URL.
1239 update_virtual_url = needs_update;
1242 // Don't use the page type from the pending entry. Some interstitial page
1243 // may have set the type to interstitial. Once we commit, however, the page
1244 // type must always be normal or error.
1245 new_entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR
1246 : PAGE_TYPE_NORMAL);
1247 new_entry->SetURL(params.url);
1248 if (update_virtual_url)
1249 UpdateVirtualURLToURL(new_entry, params.url);
1250 new_entry->SetReferrer(params.referrer);
1251 new_entry->SetPageID(params.page_id);
1252 new_entry->SetTransitionType(params.transition);
1253 new_entry->set_site_instance(
1254 static_cast<SiteInstanceImpl*>(rfh->GetSiteInstance()));
1255 new_entry->SetHasPostData(params.is_post);
1256 new_entry->SetPostID(params.post_id);
1257 new_entry->SetOriginalRequestURL(params.original_request_url);
1258 new_entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1260 // history.pushState() is classified as a navigation to a new page, but
1261 // sets was_within_same_page to true. In this case, we already have the
1262 // title and favicon available, so set them immediately.
1263 if (params.was_within_same_page && GetLastCommittedEntry()) {
1264 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
1265 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
1268 DCHECK(!params.history_list_was_cleared || !replace_entry);
1269 // The browser requested to clear the session history when it initiated the
1270 // navigation. Now we know that the renderer has updated its state accordingly
1271 // and it is safe to also clear the browser side history.
1272 if (params.history_list_was_cleared) {
1273 DiscardNonCommittedEntriesInternal();
1274 entries_.clear();
1275 last_committed_entry_index_ = -1;
1278 InsertOrReplaceEntry(new_entry, replace_entry);
1281 void NavigationControllerImpl::RendererDidNavigateToExistingPage(
1282 RenderFrameHostImpl* rfh,
1283 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1284 // We should only get here for main frame navigations.
1285 DCHECK(ui::PageTransitionIsMainFrame(params.transition));
1287 // This is a back/forward navigation. The existing page for the ID is
1288 // guaranteed to exist by ClassifyNavigation, and we just need to update it
1289 // with new information from the renderer.
1290 int entry_index = GetEntryIndexWithPageID(rfh->GetSiteInstance(),
1291 params.page_id);
1292 DCHECK(entry_index >= 0 &&
1293 entry_index < static_cast<int>(entries_.size()));
1294 NavigationEntryImpl* entry = entries_[entry_index].get();
1296 // The URL may have changed due to redirects.
1297 entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR
1298 : PAGE_TYPE_NORMAL);
1299 entry->SetURL(params.url);
1300 entry->SetReferrer(params.referrer);
1301 if (entry->update_virtual_url_with_url())
1302 UpdateVirtualURLToURL(entry, params.url);
1304 // The redirected to page should not inherit the favicon from the previous
1305 // page.
1306 if (ui::PageTransitionIsRedirect(params.transition))
1307 entry->GetFavicon() = FaviconStatus();
1309 // The site instance will normally be the same except during session restore,
1310 // when no site instance will be assigned.
1311 DCHECK(entry->site_instance() == NULL ||
1312 entry->site_instance() == rfh->GetSiteInstance());
1313 entry->set_site_instance(
1314 static_cast<SiteInstanceImpl*>(rfh->GetSiteInstance()));
1316 entry->SetHasPostData(params.is_post);
1317 entry->SetPostID(params.post_id);
1319 // The entry we found in the list might be pending if the user hit
1320 // back/forward/reload. This load should commit it (since it's already in the
1321 // list, we can just discard the pending pointer). We should also discard the
1322 // pending entry if it corresponds to a different navigation, since that one
1323 // is now likely canceled. If it is not canceled, we will treat it as a new
1324 // navigation when it arrives, which is also ok.
1326 // Note that we need to use the "internal" version since we don't want to
1327 // actually change any other state, just kill the pointer.
1328 DiscardNonCommittedEntriesInternal();
1330 // If a transient entry was removed, the indices might have changed, so we
1331 // have to query the entry index again.
1332 last_committed_entry_index_ =
1333 GetEntryIndexWithPageID(rfh->GetSiteInstance(), params.page_id);
1336 void NavigationControllerImpl::RendererDidNavigateToSamePage(
1337 RenderFrameHostImpl* rfh,
1338 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1339 // This mode implies we have a pending entry that's the same as an existing
1340 // entry for this page ID. This entry is guaranteed to exist by
1341 // ClassifyNavigation. All we need to do is update the existing entry.
1342 NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1343 rfh->GetSiteInstance(), params.page_id);
1345 // We assign the entry's unique ID to be that of the new one. Since this is
1346 // always the result of a user action, we want to dismiss infobars, etc. like
1347 // a regular user-initiated navigation.
1348 existing_entry->set_unique_id(pending_entry_->GetUniqueID());
1350 // The URL may have changed due to redirects.
1351 existing_entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR
1352 : PAGE_TYPE_NORMAL);
1353 if (existing_entry->update_virtual_url_with_url())
1354 UpdateVirtualURLToURL(existing_entry, params.url);
1355 existing_entry->SetURL(params.url);
1356 existing_entry->SetReferrer(params.referrer);
1358 // The page may have been requested with a different HTTP method.
1359 existing_entry->SetHasPostData(params.is_post);
1360 existing_entry->SetPostID(params.post_id);
1362 DiscardNonCommittedEntries();
1365 void NavigationControllerImpl::RendererDidNavigateInPage(
1366 RenderFrameHostImpl* rfh,
1367 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
1368 bool* did_replace_entry) {
1369 DCHECK(ui::PageTransitionIsMainFrame(params.transition)) <<
1370 "WebKit should only tell us about in-page navs for the main frame.";
1371 // We're guaranteed to have an entry for this one.
1372 NavigationEntryImpl* existing_entry = GetEntryWithPageID(
1373 rfh->GetSiteInstance(), params.page_id);
1375 // Reference fragment navigation. We're guaranteed to have the last_committed
1376 // entry and it will be the same page as the new navigation (minus the
1377 // reference fragments, of course). We'll update the URL of the existing
1378 // entry without pruning the forward history.
1379 existing_entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR
1380 : PAGE_TYPE_NORMAL);
1381 existing_entry->SetURL(params.url);
1382 if (existing_entry->update_virtual_url_with_url())
1383 UpdateVirtualURLToURL(existing_entry, params.url);
1385 existing_entry->SetHasPostData(params.is_post);
1386 existing_entry->SetPostID(params.post_id);
1388 // This replaces the existing entry since the page ID didn't change.
1389 *did_replace_entry = true;
1391 DiscardNonCommittedEntriesInternal();
1393 // If a transient entry was removed, the indices might have changed, so we
1394 // have to query the entry index again.
1395 last_committed_entry_index_ =
1396 GetEntryIndexWithPageID(rfh->GetSiteInstance(), params.page_id);
1399 void NavigationControllerImpl::RendererDidNavigateNewSubframe(
1400 RenderFrameHostImpl* rfh,
1401 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1402 if (!ui::PageTransitionCoreTypeIs(params.transition,
1403 ui::PAGE_TRANSITION_MANUAL_SUBFRAME)) {
1404 // There was a comment here that said, "This is not user-initiated. Ignore."
1405 // But this makes no sense; non-user-initiated navigations should be
1406 // determined to be of type NAVIGATION_TYPE_AUTO_SUBFRAME and sent to
1407 // RendererDidNavigateAutoSubframe below.
1409 // This if clause dates back to https://codereview.chromium.org/115919 and
1410 // the handling of immediate redirects. TODO(avi): Is this still valid? I'm
1411 // pretty sure that's there's nothing left of that code and that we should
1412 // take this out.
1414 // Except for cross-process iframes; this doesn't work yet for them.
1415 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1416 switches::kSitePerProcess)) {
1417 NOTREACHED();
1420 DiscardNonCommittedEntriesInternal();
1421 return;
1424 // Manual subframe navigations just get the current entry cloned so the user
1425 // can go back or forward to it. The actual subframe information will be
1426 // stored in the page state for each of those entries. This happens out of
1427 // band with the actual navigations.
1428 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
1429 << "that a last committed entry exists.";
1430 NavigationEntryImpl* new_entry = GetLastCommittedEntry()->Clone();
1431 new_entry->SetPageID(params.page_id);
1432 InsertOrReplaceEntry(new_entry, false);
1435 bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
1436 RenderFrameHostImpl* rfh,
1437 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1438 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
1439 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
1441 // We're guaranteed to have a previously committed entry, and we now need to
1442 // handle navigation inside of a subframe in it without creating a new entry.
1443 DCHECK(GetLastCommittedEntry());
1445 // Handle the case where we're navigating back/forward to a previous subframe
1446 // navigation entry. This is case "2." in NAV_AUTO_SUBFRAME comment in the
1447 // header file. In case "1." this will be a NOP.
1448 int entry_index = GetEntryIndexWithPageID(
1449 rfh->GetSiteInstance(),
1450 params.page_id);
1451 if (entry_index < 0 ||
1452 entry_index >= static_cast<int>(entries_.size())) {
1453 NOTREACHED();
1454 return false;
1457 // Update the current navigation entry in case we're going back/forward.
1458 if (entry_index != last_committed_entry_index_) {
1459 // Make sure that a subframe commit isn't changing the main frame URL.
1460 // Otherwise the renderer process may be confused, leading to a URL spoof.
1461 if (GetLastCommittedEntry()->GetURL() !=
1462 GetEntryAtIndex(entry_index)->GetURL()) {
1463 bad_message::ReceivedBadMessage(rfh->GetProcess(),
1464 bad_message::NC_AUTO_SUBFRAME);
1466 last_committed_entry_index_ = entry_index;
1467 DiscardNonCommittedEntriesInternal();
1468 return true;
1471 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1472 switches::kSitePerProcess)) {
1473 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
1474 // it may be a "history auto" case where we update an existing one.
1475 int frame_tree_node_id = rfh->frame_tree_node()->frame_tree_node_id();
1476 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
1477 last_committed->AddOrUpdateFrameEntry(frame_tree_node_id,
1478 rfh->GetSiteInstance(),
1479 params.url,
1480 params.referrer);
1483 // We do not need to discard the pending entry in this case, since we will
1484 // not generate commit notifications for this auto-subframe navigation.
1485 return false;
1488 int NavigationControllerImpl::GetIndexOfEntry(
1489 const NavigationEntryImpl* entry) const {
1490 const NavigationEntries::const_iterator i(std::find(
1491 entries_.begin(),
1492 entries_.end(),
1493 entry));
1494 return (i == entries_.end()) ? -1 : static_cast<int>(i - entries_.begin());
1497 bool NavigationControllerImpl::IsURLInPageNavigation(
1498 const GURL& url,
1499 bool renderer_says_in_page,
1500 RenderFrameHost* rfh) const {
1501 NavigationEntry* last_committed = GetLastCommittedEntry();
1502 return last_committed && AreURLsInPageNavigation(
1503 last_committed->GetURL(), url, renderer_says_in_page, rfh);
1506 void NavigationControllerImpl::CopyStateFrom(
1507 const NavigationController& temp) {
1508 const NavigationControllerImpl& source =
1509 static_cast<const NavigationControllerImpl&>(temp);
1510 // Verify that we look new.
1511 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
1513 if (source.GetEntryCount() == 0)
1514 return; // Nothing new to do.
1516 needs_reload_ = true;
1517 InsertEntriesFrom(source, source.GetEntryCount());
1519 for (SessionStorageNamespaceMap::const_iterator it =
1520 source.session_storage_namespace_map_.begin();
1521 it != source.session_storage_namespace_map_.end();
1522 ++it) {
1523 SessionStorageNamespaceImpl* source_namespace =
1524 static_cast<SessionStorageNamespaceImpl*>(it->second.get());
1525 session_storage_namespace_map_[it->first] = source_namespace->Clone();
1528 FinishRestore(source.last_committed_entry_index_, RESTORE_CURRENT_SESSION);
1530 // Copy the max page id map from the old tab to the new tab. This ensures
1531 // that new and existing navigations in the tab's current SiteInstances
1532 // are identified properly.
1533 delegate_->CopyMaxPageIDsFrom(source.delegate()->GetWebContents());
1536 void NavigationControllerImpl::CopyStateFromAndPrune(
1537 NavigationController* temp,
1538 bool replace_entry) {
1539 // It is up to callers to check the invariants before calling this.
1540 CHECK(CanPruneAllButLastCommitted());
1542 NavigationControllerImpl* source =
1543 static_cast<NavigationControllerImpl*>(temp);
1545 // Remove all the entries leaving the last committed entry.
1546 PruneAllButLastCommittedInternal();
1548 // We now have one entry, possibly with a new pending entry. Ensure that
1549 // adding the entries from source won't put us over the limit.
1550 DCHECK_EQ(1, GetEntryCount());
1551 if (!replace_entry)
1552 source->PruneOldestEntryIfFull();
1554 // Insert the entries from source. Don't use source->GetCurrentEntryIndex as
1555 // we don't want to copy over the transient entry. Ignore any pending entry,
1556 // since it has not committed in source.
1557 int max_source_index = source->last_committed_entry_index_;
1558 if (max_source_index == -1)
1559 max_source_index = source->GetEntryCount();
1560 else
1561 max_source_index++;
1563 // Ignore the source's current entry if merging with replacement.
1564 // TODO(davidben): This should preserve entries forward of the current
1565 // too. http://crbug.com/317872
1566 if (replace_entry && max_source_index > 0)
1567 max_source_index--;
1569 InsertEntriesFrom(*source, max_source_index);
1571 // Adjust indices such that the last entry and pending are at the end now.
1572 last_committed_entry_index_ = GetEntryCount() - 1;
1574 delegate_->SetHistoryOffsetAndLength(last_committed_entry_index_,
1575 GetEntryCount());
1577 // Copy the max page id map from the old tab to the new tab. This ensures that
1578 // new and existing navigations in the tab's current SiteInstances are
1579 // identified properly.
1580 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
1581 int32 site_max_page_id =
1582 delegate_->GetMaxPageIDForSiteInstance(last_committed->site_instance());
1583 delegate_->CopyMaxPageIDsFrom(source->delegate()->GetWebContents());
1584 delegate_->UpdateMaxPageIDForSiteInstance(last_committed->site_instance(),
1585 site_max_page_id);
1586 max_restored_page_id_ = source->max_restored_page_id_;
1589 bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
1590 // If there is no last committed entry, we cannot prune. Even if there is a
1591 // pending entry, it may not commit, leaving this WebContents blank, despite
1592 // possibly giving it new entries via CopyStateFromAndPrune.
1593 if (last_committed_entry_index_ == -1)
1594 return false;
1596 // We cannot prune if there is a pending entry at an existing entry index.
1597 // It may not commit, so we have to keep the last committed entry, and thus
1598 // there is no sensible place to keep the pending entry. It is ok to have
1599 // a new pending entry, which can optionally commit as a new navigation.
1600 if (pending_entry_index_ != -1)
1601 return false;
1603 // We should not prune if we are currently showing a transient entry.
1604 if (transient_entry_index_ != -1)
1605 return false;
1607 return true;
1610 void NavigationControllerImpl::PruneAllButLastCommitted() {
1611 PruneAllButLastCommittedInternal();
1613 DCHECK_EQ(0, last_committed_entry_index_);
1614 DCHECK_EQ(1, GetEntryCount());
1616 delegate_->SetHistoryOffsetAndLength(last_committed_entry_index_,
1617 GetEntryCount());
1620 void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
1621 // It is up to callers to check the invariants before calling this.
1622 CHECK(CanPruneAllButLastCommitted());
1624 // Erase all entries but the last committed entry. There may still be a
1625 // new pending entry after this.
1626 entries_.erase(entries_.begin(),
1627 entries_.begin() + last_committed_entry_index_);
1628 entries_.erase(entries_.begin() + 1, entries_.end());
1629 last_committed_entry_index_ = 0;
1632 void NavigationControllerImpl::ClearAllScreenshots() {
1633 screenshot_manager_->ClearAllScreenshots();
1636 void NavigationControllerImpl::SetSessionStorageNamespace(
1637 const std::string& partition_id,
1638 SessionStorageNamespace* session_storage_namespace) {
1639 if (!session_storage_namespace)
1640 return;
1642 // We can't overwrite an existing SessionStorage without violating spec.
1643 // Attempts to do so may give a tab access to another tab's session storage
1644 // so die hard on an error.
1645 bool successful_insert = session_storage_namespace_map_.insert(
1646 make_pair(partition_id,
1647 static_cast<SessionStorageNamespaceImpl*>(
1648 session_storage_namespace)))
1649 .second;
1650 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
1653 void NavigationControllerImpl::SetMaxRestoredPageID(int32 max_id) {
1654 max_restored_page_id_ = max_id;
1657 int32 NavigationControllerImpl::GetMaxRestoredPageID() const {
1658 return max_restored_page_id_;
1661 bool NavigationControllerImpl::IsUnmodifiedBlankTab() const {
1662 return IsInitialNavigation() &&
1663 !GetLastCommittedEntry() &&
1664 !delegate_->HasAccessedInitialDocument();
1667 SessionStorageNamespace*
1668 NavigationControllerImpl::GetSessionStorageNamespace(SiteInstance* instance) {
1669 std::string partition_id;
1670 if (instance) {
1671 // TODO(ajwong): When GetDefaultSessionStorageNamespace() goes away, remove
1672 // this if statement so |instance| must not be NULL.
1673 partition_id =
1674 GetContentClient()->browser()->GetStoragePartitionIdForSite(
1675 browser_context_, instance->GetSiteURL());
1678 SessionStorageNamespaceMap::const_iterator it =
1679 session_storage_namespace_map_.find(partition_id);
1680 if (it != session_storage_namespace_map_.end())
1681 return it->second.get();
1683 // Create one if no one has accessed session storage for this partition yet.
1685 // TODO(ajwong): Should this use the |partition_id| directly rather than
1686 // re-lookup via |instance|? http://crbug.com/142685
1687 StoragePartition* partition =
1688 BrowserContext::GetStoragePartition(browser_context_, instance);
1689 SessionStorageNamespaceImpl* session_storage_namespace =
1690 new SessionStorageNamespaceImpl(
1691 static_cast<DOMStorageContextWrapper*>(
1692 partition->GetDOMStorageContext()));
1693 session_storage_namespace_map_[partition_id] = session_storage_namespace;
1695 return session_storage_namespace;
1698 SessionStorageNamespace*
1699 NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
1700 // TODO(ajwong): Remove if statement in GetSessionStorageNamespace().
1701 return GetSessionStorageNamespace(NULL);
1704 const SessionStorageNamespaceMap&
1705 NavigationControllerImpl::GetSessionStorageNamespaceMap() const {
1706 return session_storage_namespace_map_;
1709 bool NavigationControllerImpl::NeedsReload() const {
1710 return needs_reload_;
1713 void NavigationControllerImpl::SetNeedsReload() {
1714 needs_reload_ = true;
1716 if (last_committed_entry_index_ != -1) {
1717 entries_[last_committed_entry_index_]->SetTransitionType(
1718 ui::PAGE_TRANSITION_RELOAD);
1722 void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
1723 DCHECK(index < GetEntryCount());
1724 DCHECK(index != last_committed_entry_index_);
1726 DiscardNonCommittedEntries();
1728 entries_.erase(entries_.begin() + index);
1729 if (last_committed_entry_index_ > index)
1730 last_committed_entry_index_--;
1733 void NavigationControllerImpl::DiscardNonCommittedEntries() {
1734 bool transient = transient_entry_index_ != -1;
1735 DiscardNonCommittedEntriesInternal();
1737 // If there was a transient entry, invalidate everything so the new active
1738 // entry state is shown.
1739 if (transient) {
1740 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
1744 NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() const {
1745 return pending_entry_;
1748 int NavigationControllerImpl::GetPendingEntryIndex() const {
1749 return pending_entry_index_;
1752 void NavigationControllerImpl::InsertOrReplaceEntry(NavigationEntryImpl* entry,
1753 bool replace) {
1754 DCHECK(entry->GetTransitionType() != ui::PAGE_TRANSITION_AUTO_SUBFRAME);
1756 // Copy the pending entry's unique ID to the committed entry.
1757 // I don't know if pending_entry_index_ can be other than -1 here.
1758 const NavigationEntryImpl* const pending_entry =
1759 (pending_entry_index_ == -1) ?
1760 pending_entry_ : entries_[pending_entry_index_].get();
1761 if (pending_entry)
1762 entry->set_unique_id(pending_entry->GetUniqueID());
1764 DiscardNonCommittedEntriesInternal();
1766 int current_size = static_cast<int>(entries_.size());
1767 DCHECK_IMPLIES(replace, current_size > 0);
1769 if (current_size > 0) {
1770 // Prune any entries which are in front of the current entry.
1771 // Also prune the current entry if we are to replace the current entry.
1772 // last_committed_entry_index_ must be updated here since calls to
1773 // NotifyPrunedEntries() below may re-enter and we must make sure
1774 // last_committed_entry_index_ is not left in an invalid state.
1775 if (replace)
1776 --last_committed_entry_index_;
1778 int num_pruned = 0;
1779 while (last_committed_entry_index_ < (current_size - 1)) {
1780 num_pruned++;
1781 entries_.pop_back();
1782 current_size--;
1784 if (num_pruned > 0) // Only notify if we did prune something.
1785 NotifyPrunedEntries(this, false, num_pruned);
1788 PruneOldestEntryIfFull();
1790 entries_.push_back(linked_ptr<NavigationEntryImpl>(entry));
1791 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
1793 // This is a new page ID, so we need everybody to know about it.
1794 delegate_->UpdateMaxPageID(entry->GetPageID());
1797 void NavigationControllerImpl::PruneOldestEntryIfFull() {
1798 if (entries_.size() >= max_entry_count()) {
1799 DCHECK_EQ(max_entry_count(), entries_.size());
1800 DCHECK_GT(last_committed_entry_index_, 0);
1801 RemoveEntryAtIndex(0);
1802 NotifyPrunedEntries(this, true, 1);
1806 void NavigationControllerImpl::NavigateToPendingEntry(ReloadType reload_type) {
1807 needs_reload_ = false;
1809 // If we were navigating to a slow-to-commit page, and the user performs
1810 // a session history navigation to the last committed page, RenderViewHost
1811 // will force the throbber to start, but WebKit will essentially ignore the
1812 // navigation, and won't send a message to stop the throbber. To prevent this
1813 // from happening, we drop the navigation here and stop the slow-to-commit
1814 // page from loading (which would normally happen during the navigation).
1815 if (pending_entry_index_ != -1 &&
1816 pending_entry_index_ == last_committed_entry_index_ &&
1817 (entries_[pending_entry_index_]->restore_type() ==
1818 NavigationEntryImpl::RESTORE_NONE) &&
1819 (entries_[pending_entry_index_]->GetTransitionType() &
1820 ui::PAGE_TRANSITION_FORWARD_BACK)) {
1821 delegate_->Stop();
1823 // If an interstitial page is showing, we want to close it to get back
1824 // to what was showing before.
1825 if (delegate_->GetInterstitialPage())
1826 delegate_->GetInterstitialPage()->DontProceed();
1828 DiscardNonCommittedEntries();
1829 return;
1832 // If an interstitial page is showing, the previous renderer is blocked and
1833 // cannot make new requests. Unblock (and disable) it to allow this
1834 // navigation to succeed. The interstitial will stay visible until the
1835 // resulting DidNavigate.
1836 if (delegate_->GetInterstitialPage()) {
1837 static_cast<InterstitialPageImpl*>(delegate_->GetInterstitialPage())->
1838 CancelForNavigation();
1841 // For session history navigations only the pending_entry_index_ is set.
1842 if (!pending_entry_) {
1843 DCHECK_NE(pending_entry_index_, -1);
1844 pending_entry_ = entries_[pending_entry_index_].get();
1847 // This call does not support re-entrancy. See http://crbug.com/347742.
1848 CHECK(!in_navigate_to_pending_entry_);
1849 in_navigate_to_pending_entry_ = true;
1850 bool success = delegate_->NavigateToPendingEntry(reload_type);
1851 in_navigate_to_pending_entry_ = false;
1853 if (!success)
1854 DiscardNonCommittedEntries();
1856 // If the entry is being restored and doesn't have a SiteInstance yet, fill
1857 // it in now that we know. This allows us to find the entry when it commits.
1858 if (pending_entry_ && !pending_entry_->site_instance() &&
1859 pending_entry_->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
1860 pending_entry_->set_site_instance(static_cast<SiteInstanceImpl*>(
1861 delegate_->GetPendingSiteInstance()));
1862 pending_entry_->set_restore_type(NavigationEntryImpl::RESTORE_NONE);
1866 void NavigationControllerImpl::NotifyNavigationEntryCommitted(
1867 LoadCommittedDetails* details) {
1868 details->entry = GetLastCommittedEntry();
1870 // We need to notify the ssl_manager_ before the web_contents_ so the
1871 // location bar will have up-to-date information about the security style
1872 // when it wants to draw. See http://crbug.com/11157
1873 ssl_manager_.DidCommitProvisionalLoad(*details);
1875 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
1876 delegate_->NotifyNavigationEntryCommitted(*details);
1878 // TODO(avi): Remove. http://crbug.com/170921
1879 NotificationDetails notification_details =
1880 Details<LoadCommittedDetails>(details);
1881 NotificationService::current()->Notify(
1882 NOTIFICATION_NAV_ENTRY_COMMITTED,
1883 Source<NavigationController>(this),
1884 notification_details);
1887 // static
1888 size_t NavigationControllerImpl::max_entry_count() {
1889 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
1890 return max_entry_count_for_testing_;
1891 return kMaxSessionHistoryEntries;
1894 void NavigationControllerImpl::SetActive(bool is_active) {
1895 if (is_active && needs_reload_)
1896 LoadIfNecessary();
1899 void NavigationControllerImpl::LoadIfNecessary() {
1900 if (!needs_reload_)
1901 return;
1903 // Calling Reload() results in ignoring state, and not loading.
1904 // Explicitly use NavigateToPendingEntry so that the renderer uses the
1905 // cached state.
1906 pending_entry_index_ = last_committed_entry_index_;
1907 NavigateToPendingEntry(NO_RELOAD);
1910 void NavigationControllerImpl::NotifyEntryChanged(const NavigationEntry* entry,
1911 int index) {
1912 EntryChangedDetails det;
1913 det.changed_entry = entry;
1914 det.index = index;
1915 NotificationService::current()->Notify(
1916 NOTIFICATION_NAV_ENTRY_CHANGED,
1917 Source<NavigationController>(this),
1918 Details<EntryChangedDetails>(&det));
1921 void NavigationControllerImpl::FinishRestore(int selected_index,
1922 RestoreType type) {
1923 DCHECK(selected_index >= 0 && selected_index < GetEntryCount());
1924 ConfigureEntriesForRestore(&entries_, type);
1926 SetMaxRestoredPageID(static_cast<int32>(GetEntryCount()));
1928 last_committed_entry_index_ = selected_index;
1931 void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
1932 DiscardPendingEntry(false);
1933 DiscardTransientEntry();
1936 void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
1937 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
1938 // progress, since this will cause a use-after-free. (We only allow this
1939 // when the tab is being destroyed for shutdown, since it won't return to
1940 // NavigateToEntry in that case.) http://crbug.com/347742.
1941 CHECK(!in_navigate_to_pending_entry_ || delegate_->IsBeingDestroyed());
1943 if (was_failure && pending_entry_) {
1944 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
1945 failed_pending_entry_should_replace_ =
1946 pending_entry_->should_replace_entry();
1947 } else {
1948 failed_pending_entry_id_ = 0;
1951 if (pending_entry_index_ == -1)
1952 delete pending_entry_;
1953 pending_entry_ = NULL;
1954 pending_entry_index_ = -1;
1957 void NavigationControllerImpl::DiscardTransientEntry() {
1958 if (transient_entry_index_ == -1)
1959 return;
1960 entries_.erase(entries_.begin() + transient_entry_index_);
1961 if (last_committed_entry_index_ > transient_entry_index_)
1962 last_committed_entry_index_--;
1963 transient_entry_index_ = -1;
1966 int NavigationControllerImpl::GetEntryIndexWithPageID(
1967 SiteInstance* instance, int32 page_id) const {
1968 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
1969 if ((entries_[i]->site_instance() == instance) &&
1970 (entries_[i]->GetPageID() == page_id))
1971 return i;
1973 return -1;
1976 int NavigationControllerImpl::GetEntryIndexWithUniqueID(
1977 int nav_entry_id) const {
1978 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
1979 if (entries_[i]->GetUniqueID() == nav_entry_id)
1980 return i;
1982 return -1;
1985 NavigationEntryImpl* NavigationControllerImpl::GetTransientEntry() const {
1986 if (transient_entry_index_ == -1)
1987 return NULL;
1988 return entries_[transient_entry_index_].get();
1991 void NavigationControllerImpl::SetTransientEntry(NavigationEntry* entry) {
1992 // Discard any current transient entry, we can only have one at a time.
1993 int index = 0;
1994 if (last_committed_entry_index_ != -1)
1995 index = last_committed_entry_index_ + 1;
1996 DiscardTransientEntry();
1997 entries_.insert(
1998 entries_.begin() + index, linked_ptr<NavigationEntryImpl>(
1999 NavigationEntryImpl::FromNavigationEntry(entry)));
2000 transient_entry_index_ = index;
2001 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
2004 void NavigationControllerImpl::InsertEntriesFrom(
2005 const NavigationControllerImpl& source,
2006 int max_index) {
2007 DCHECK_LE(max_index, source.GetEntryCount());
2008 size_t insert_index = 0;
2009 for (int i = 0; i < max_index; i++) {
2010 // When cloning a tab, copy all entries except interstitial pages.
2011 if (source.entries_[i].get()->GetPageType() != PAGE_TYPE_INTERSTITIAL) {
2012 // TODO(creis): Once we start sharing FrameNavigationEntries between
2013 // NavigationEntries, it will not be safe to share them with another tab.
2014 // Must have a version of Clone that recreates them.
2015 entries_.insert(entries_.begin() + insert_index++,
2016 linked_ptr<NavigationEntryImpl>(
2017 source.entries_[i]->Clone()));
2022 void NavigationControllerImpl::SetGetTimestampCallbackForTest(
2023 const base::Callback<base::Time()>& get_timestamp_callback) {
2024 get_timestamp_callback_ = get_timestamp_callback;
2027 } // namespace content