Fix race when reloading original URL.
[chromium-blink-merge.git] / content / browser / frame_host / navigation_controller_impl.cc
blob35a1d075c93fe7df83d8f27741cfa52906726ba0
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 /*
6 * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
8 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved.
9 * (http://www.torchmobile.com/)
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
21 * its contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
25 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
28 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #include "content/browser/frame_host/navigation_controller_impl.h"
38 #include "base/bind.h"
39 #include "base/command_line.h"
40 #include "base/logging.h"
41 #include "base/metrics/histogram.h"
42 #include "base/strings/string_number_conversions.h" // Temporary
43 #include "base/strings/string_util.h"
44 #include "base/strings/utf_string_conversions.h"
45 #include "base/time/time.h"
46 #include "base/trace_event/trace_event.h"
47 #include "build/build_config.h"
48 #include "cc/base/switches.h"
49 #include "components/mime_util/mime_util.h"
50 #include "content/browser/bad_message.h"
51 #include "content/browser/browser_url_handler_impl.h"
52 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
53 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
54 #include "content/browser/frame_host/debug_urls.h"
55 #include "content/browser/frame_host/interstitial_page_impl.h"
56 #include "content/browser/frame_host/navigation_entry_impl.h"
57 #include "content/browser/frame_host/navigation_entry_screenshot_manager.h"
58 #include "content/browser/frame_host/navigator.h"
59 #include "content/browser/renderer_host/render_view_host_impl.h" // Temporary
60 #include "content/browser/site_instance_impl.h"
61 #include "content/common/frame_messages.h"
62 #include "content/common/ssl_status_serialization.h"
63 #include "content/common/view_messages.h"
64 #include "content/public/browser/browser_context.h"
65 #include "content/public/browser/content_browser_client.h"
66 #include "content/public/browser/invalidate_type.h"
67 #include "content/public/browser/navigation_details.h"
68 #include "content/public/browser/notification_service.h"
69 #include "content/public/browser/notification_types.h"
70 #include "content/public/browser/render_widget_host.h"
71 #include "content/public/browser/render_widget_host_view.h"
72 #include "content/public/browser/storage_partition.h"
73 #include "content/public/browser/user_metrics.h"
74 #include "content/public/common/content_client.h"
75 #include "content/public/common/content_constants.h"
76 #include "content/public/common/content_switches.h"
77 #include "media/base/mime_util.h"
78 #include "net/base/escape.h"
79 #include "net/base/net_util.h"
80 #include "skia/ext/platform_canvas.h"
81 #include "url/url_constants.h"
83 namespace content {
84 namespace {
86 // Invoked when entries have been pruned, or removed. For example, if the
87 // current entries are [google, digg, yahoo], with the current entry google,
88 // and the user types in cnet, then digg and yahoo are pruned.
89 void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
90 bool from_front,
91 int count) {
92 PrunedDetails details;
93 details.from_front = from_front;
94 details.count = count;
95 NotificationService::current()->Notify(
96 NOTIFICATION_NAV_LIST_PRUNED,
97 Source<NavigationController>(nav_controller),
98 Details<PrunedDetails>(&details));
101 // Ensure the given NavigationEntry has a valid state, so that WebKit does not
102 // get confused if we navigate back to it.
104 // An empty state is treated as a new navigation by WebKit, which would mean
105 // losing the navigation entries and generating a new navigation entry after
106 // this one. We don't want that. To avoid this we create a valid state which
107 // WebKit will not treat as a new navigation.
108 void SetPageStateIfEmpty(NavigationEntryImpl* entry) {
109 if (!entry->GetPageState().IsValid())
110 entry->SetPageState(PageState::CreateFromURL(entry->GetURL()));
113 NavigationEntryImpl::RestoreType ControllerRestoreTypeToEntryType(
114 NavigationController::RestoreType type) {
115 switch (type) {
116 case NavigationController::RESTORE_CURRENT_SESSION:
117 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
118 case NavigationController::RESTORE_LAST_SESSION_EXITED_CLEANLY:
119 return NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY;
120 case NavigationController::RESTORE_LAST_SESSION_CRASHED:
121 return NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED;
123 NOTREACHED();
124 return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
127 // Configure all the NavigationEntries in entries for restore. This resets
128 // the transition type to reload and makes sure the content state isn't empty.
129 void ConfigureEntriesForRestore(
130 ScopedVector<NavigationEntryImpl>* entries,
131 NavigationController::RestoreType type) {
132 for (size_t i = 0; i < entries->size(); ++i) {
133 // Use a transition type of reload so that we don't incorrectly increase
134 // the typed count.
135 (*entries)[i]->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
136 (*entries)[i]->set_restore_type(ControllerRestoreTypeToEntryType(type));
137 // NOTE(darin): This code is only needed for backwards compat.
138 SetPageStateIfEmpty((*entries)[i]);
142 // Determines whether or not we should be carrying over a user agent override
143 // between two NavigationEntries.
144 bool ShouldKeepOverride(const NavigationEntry* last_entry) {
145 return last_entry && last_entry->GetIsOverridingUserAgent();
148 } // namespace
150 // NavigationControllerImpl ----------------------------------------------------
152 const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
154 // static
155 size_t NavigationControllerImpl::max_entry_count_for_testing_ =
156 kMaxEntryCountForTestingNotSet;
158 // Should Reload check for post data? The default is true, but is set to false
159 // when testing.
160 static bool g_check_for_repost = true;
162 // static
163 scoped_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
164 const GURL& url,
165 const Referrer& referrer,
166 ui::PageTransition transition,
167 bool is_renderer_initiated,
168 const std::string& extra_headers,
169 BrowserContext* browser_context) {
170 // Fix up the given URL before letting it be rewritten, so that any minor
171 // cleanup (e.g., removing leading dots) will not lead to a virtual URL.
172 GURL dest_url(url);
173 BrowserURLHandlerImpl::GetInstance()->FixupURLBeforeRewrite(&dest_url,
174 browser_context);
176 // Allow the browser URL handler to rewrite the URL. This will, for example,
177 // remove "view-source:" from the beginning of the URL to get the URL that
178 // will actually be loaded. This real URL won't be shown to the user, just
179 // used internally.
180 GURL loaded_url(dest_url);
181 bool reverse_on_redirect = false;
182 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
183 &loaded_url, browser_context, &reverse_on_redirect);
185 NavigationEntryImpl* entry = new NavigationEntryImpl(
186 NULL, // The site instance for tabs is sent on navigation
187 // (WebContents::GetSiteInstance).
189 loaded_url,
190 referrer,
191 base::string16(),
192 transition,
193 is_renderer_initiated);
194 entry->SetVirtualURL(dest_url);
195 entry->set_user_typed_url(dest_url);
196 entry->set_update_virtual_url_with_url(reverse_on_redirect);
197 entry->set_extra_headers(extra_headers);
198 return make_scoped_ptr(entry);
201 // static
202 void NavigationController::DisablePromptOnRepost() {
203 g_check_for_repost = false;
206 base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
207 base::Time t) {
208 // If |t| is between the water marks, we're in a run of duplicates
209 // or just getting out of it, so increase the high-water mark to get
210 // a time that probably hasn't been used before and return it.
211 if (low_water_mark_ <= t && t <= high_water_mark_) {
212 high_water_mark_ += base::TimeDelta::FromMicroseconds(1);
213 return high_water_mark_;
216 // Otherwise, we're clear of the last duplicate run, so reset the
217 // water marks.
218 low_water_mark_ = high_water_mark_ = t;
219 return t;
222 NavigationControllerImpl::NavigationControllerImpl(
223 NavigationControllerDelegate* delegate,
224 BrowserContext* browser_context)
225 : browser_context_(browser_context),
226 pending_entry_(NULL),
227 failed_pending_entry_id_(0),
228 failed_pending_entry_should_replace_(false),
229 last_committed_entry_index_(-1),
230 pending_entry_index_(-1),
231 transient_entry_index_(-1),
232 delegate_(delegate),
233 max_restored_page_id_(-1),
234 ssl_manager_(this),
235 needs_reload_(false),
236 is_initial_navigation_(true),
237 in_navigate_to_pending_entry_(false),
238 pending_reload_(NO_RELOAD),
239 get_timestamp_callback_(base::Bind(&base::Time::Now)),
240 screenshot_manager_(new NavigationEntryScreenshotManager(this)) {
241 DCHECK(browser_context_);
244 NavigationControllerImpl::~NavigationControllerImpl() {
245 DiscardNonCommittedEntriesInternal();
248 WebContents* NavigationControllerImpl::GetWebContents() const {
249 return delegate_->GetWebContents();
252 BrowserContext* NavigationControllerImpl::GetBrowserContext() const {
253 return browser_context_;
256 void NavigationControllerImpl::SetBrowserContext(
257 BrowserContext* browser_context) {
258 browser_context_ = browser_context;
261 void NavigationControllerImpl::Restore(
262 int selected_navigation,
263 RestoreType type,
264 ScopedVector<NavigationEntry>* entries) {
265 // Verify that this controller is unused and that the input is valid.
266 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
267 DCHECK(selected_navigation >= 0 &&
268 selected_navigation < static_cast<int>(entries->size()));
270 needs_reload_ = true;
271 for (size_t i = 0; i < entries->size(); ++i) {
272 NavigationEntryImpl* entry =
273 NavigationEntryImpl::FromNavigationEntry((*entries)[i]);
274 entries_.push_back(entry);
276 entries->weak_clear();
278 // And finish the restore.
279 FinishRestore(selected_navigation, type);
282 void NavigationControllerImpl::Reload(bool check_for_repost) {
283 ReloadInternal(check_for_repost, RELOAD);
285 void NavigationControllerImpl::ReloadIgnoringCache(bool check_for_repost) {
286 ReloadInternal(check_for_repost, RELOAD_IGNORING_CACHE);
288 void NavigationControllerImpl::ReloadOriginalRequestURL(bool check_for_repost) {
289 ReloadInternal(check_for_repost, RELOAD_ORIGINAL_REQUEST_URL);
292 void NavigationControllerImpl::ReloadInternal(bool check_for_repost,
293 ReloadType reload_type) {
294 if (transient_entry_index_ != -1) {
295 // If an interstitial is showing, treat a reload as a navigation to the
296 // transient entry's URL.
297 NavigationEntryImpl* transient_entry = GetTransientEntry();
298 if (!transient_entry)
299 return;
300 LoadURL(transient_entry->GetURL(),
301 Referrer(),
302 ui::PAGE_TRANSITION_RELOAD,
303 transient_entry->extra_headers());
304 return;
307 NavigationEntryImpl* entry = NULL;
308 int current_index = -1;
310 // If we are reloading the initial navigation, just use the current
311 // pending entry. Otherwise look up the current entry.
312 if (IsInitialNavigation() && pending_entry_) {
313 entry = pending_entry_;
314 // The pending entry might be in entries_ (e.g., after a Clone), so we
315 // should also update the current_index.
316 current_index = pending_entry_index_;
317 } else {
318 DiscardNonCommittedEntriesInternal();
319 current_index = GetCurrentEntryIndex();
320 if (current_index != -1) {
321 entry = GetEntryAtIndex(current_index);
325 // If we are no where, then we can't reload. TODO(darin): We should add a
326 // CanReload method.
327 if (!entry)
328 return;
330 if (g_check_for_repost && check_for_repost &&
331 entry->GetHasPostData()) {
332 // The user is asking to reload a page with POST data. Prompt to make sure
333 // they really want to do this. If they do, the dialog will call us back
334 // with check_for_repost = false.
335 delegate_->NotifyBeforeFormRepostWarningShow();
337 pending_reload_ = reload_type;
338 delegate_->ActivateAndShowRepostFormWarningDialog();
339 } else {
340 if (!IsInitialNavigation())
341 DiscardNonCommittedEntriesInternal();
343 // If we are reloading an entry that no longer belongs to the current
344 // site instance (for example, refreshing a page for just installed app),
345 // the reload must happen in a new process.
346 // The new entry must have a new page_id and site instance, so it behaves
347 // as new navigation (which happens to clear forward history).
348 // Tabs that are discarded due to low memory conditions may not have a site
349 // instance, and should not be treated as a cross-site reload.
350 SiteInstanceImpl* site_instance = entry->site_instance();
351 // Permit reloading guests without further checks.
352 bool is_for_guests_only = site_instance && site_instance->HasProcess() &&
353 site_instance->GetProcess()->IsForGuestsOnly();
354 if (!is_for_guests_only && site_instance &&
355 site_instance->HasWrongProcessForURL(entry->GetURL())) {
356 // Create a navigation entry that resembles the current one, but do not
357 // copy page id, site instance, content state, or timestamp. TODO(avi):
358 // This seems wrong. We're setting |pending_entry_| to a different value
359 // than what |pending_entry_index_| points to. Doesn't this leak?
360 NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry(
361 CreateNavigationEntry(
362 entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(),
363 false, entry->extra_headers(), browser_context_).release());
365 // Mark the reload type as NO_RELOAD, so navigation will not be considered
366 // a reload in the renderer.
367 reload_type = NavigationController::NO_RELOAD;
369 nav_entry->set_should_replace_entry(true);
370 pending_entry_ = nav_entry;
371 } else {
372 pending_entry_ = entry;
373 pending_entry_index_ = current_index;
375 // The title of the page being reloaded might have been removed in the
376 // meanwhile, so we need to revert to the default title upon reload and
377 // invalidate the previously cached title (SetTitle will do both).
378 // See Chromium issue 96041.
379 pending_entry_->SetTitle(base::string16());
381 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
384 NavigateToPendingEntry(reload_type);
388 void NavigationControllerImpl::CancelPendingReload() {
389 DCHECK(pending_reload_ != NO_RELOAD);
390 pending_reload_ = NO_RELOAD;
393 void NavigationControllerImpl::ContinuePendingReload() {
394 if (pending_reload_ == NO_RELOAD) {
395 NOTREACHED();
396 } else {
397 ReloadInternal(false, pending_reload_);
398 pending_reload_ = NO_RELOAD;
402 bool NavigationControllerImpl::IsInitialNavigation() const {
403 return is_initial_navigation_;
406 NavigationEntryImpl* NavigationControllerImpl::GetEntryWithPageID(
407 SiteInstance* instance, int32 page_id) const {
408 int index = GetEntryIndexWithPageID(instance, page_id);
409 return (index != -1) ? entries_[index] : nullptr;
412 NavigationEntryImpl*
413 NavigationControllerImpl::GetEntryWithUniqueID(int nav_entry_id) const {
414 int index = GetEntryIndexWithUniqueID(nav_entry_id);
415 return (index != -1) ? entries_[index] : nullptr;
418 bool NavigationControllerImpl::HasCommittedRealLoad(
419 FrameTreeNode* frame_tree_node) const {
420 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
421 return last_committed && last_committed->GetFrameEntry(frame_tree_node);
424 void NavigationControllerImpl::LoadEntry(
425 scoped_ptr<NavigationEntryImpl> entry) {
426 // When navigating to a new page, we don't know for sure if we will actually
427 // end up leaving the current page. The new page load could for example
428 // result in a download or a 'no content' response (e.g., a mailto: URL).
429 SetPendingEntry(entry.Pass());
430 NavigateToPendingEntry(NO_RELOAD);
433 void NavigationControllerImpl::SetPendingEntry(
434 scoped_ptr<NavigationEntryImpl> entry) {
435 DiscardNonCommittedEntriesInternal();
436 pending_entry_ = entry.release();
437 NotificationService::current()->Notify(
438 NOTIFICATION_NAV_ENTRY_PENDING,
439 Source<NavigationController>(this),
440 Details<NavigationEntry>(pending_entry_));
443 NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() const {
444 if (transient_entry_index_ != -1)
445 return entries_[transient_entry_index_];
446 if (pending_entry_)
447 return pending_entry_;
448 return GetLastCommittedEntry();
451 NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() const {
452 if (transient_entry_index_ != -1)
453 return entries_[transient_entry_index_];
454 // The pending entry is safe to return for new (non-history), browser-
455 // initiated navigations. Most renderer-initiated navigations should not
456 // show the pending entry, to prevent URL spoof attacks.
458 // We make an exception for renderer-initiated navigations in new tabs, as
459 // long as no other page has tried to access the initial empty document in
460 // the new tab. If another page modifies this blank page, a URL spoof is
461 // possible, so we must stop showing the pending entry.
462 bool safe_to_show_pending =
463 pending_entry_ &&
464 // Require a new navigation.
465 pending_entry_index_ == -1 &&
466 // Require either browser-initiated or an unmodified new tab.
467 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
469 // Also allow showing the pending entry for history navigations in a new tab,
470 // such as Ctrl+Back. In this case, no existing page is visible and no one
471 // can script the new tab before it commits.
472 if (!safe_to_show_pending &&
473 pending_entry_ &&
474 pending_entry_index_ != -1 &&
475 IsInitialNavigation() &&
476 !pending_entry_->is_renderer_initiated())
477 safe_to_show_pending = true;
479 if (safe_to_show_pending)
480 return pending_entry_;
481 return GetLastCommittedEntry();
484 int NavigationControllerImpl::GetCurrentEntryIndex() const {
485 if (transient_entry_index_ != -1)
486 return transient_entry_index_;
487 if (pending_entry_index_ != -1)
488 return pending_entry_index_;
489 return last_committed_entry_index_;
492 NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() const {
493 if (last_committed_entry_index_ == -1)
494 return NULL;
495 return entries_[last_committed_entry_index_];
498 bool NavigationControllerImpl::CanViewSource() const {
499 const std::string& mime_type = delegate_->GetContentsMimeType();
500 bool is_viewable_mime_type =
501 mime_util::IsSupportedNonImageMimeType(mime_type) &&
502 !media::IsSupportedMediaMimeType(mime_type);
503 NavigationEntry* visible_entry = GetVisibleEntry();
504 return visible_entry && !visible_entry->IsViewSourceMode() &&
505 is_viewable_mime_type && !delegate_->GetInterstitialPage();
508 int NavigationControllerImpl::GetLastCommittedEntryIndex() const {
509 return last_committed_entry_index_;
512 int NavigationControllerImpl::GetEntryCount() const {
513 DCHECK(entries_.size() <= max_entry_count());
514 return static_cast<int>(entries_.size());
517 NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(
518 int index) const {
519 if (index < 0 || index >= GetEntryCount())
520 return nullptr;
522 return entries_[index];
525 NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(
526 int offset) const {
527 return GetEntryAtIndex(GetIndexForOffset(offset));
530 int NavigationControllerImpl::GetIndexForOffset(int offset) const {
531 return GetCurrentEntryIndex() + offset;
534 void NavigationControllerImpl::TakeScreenshot() {
535 screenshot_manager_->TakeScreenshot();
538 void NavigationControllerImpl::SetScreenshotManager(
539 NavigationEntryScreenshotManager* manager) {
540 screenshot_manager_.reset(manager ? manager :
541 new NavigationEntryScreenshotManager(this));
544 bool NavigationControllerImpl::CanGoBack() const {
545 return entries_.size() > 1 && GetCurrentEntryIndex() > 0;
548 bool NavigationControllerImpl::CanGoForward() const {
549 int index = GetCurrentEntryIndex();
550 return index >= 0 && index < (static_cast<int>(entries_.size()) - 1);
553 bool NavigationControllerImpl::CanGoToOffset(int offset) const {
554 int index = GetIndexForOffset(offset);
555 return index >= 0 && index < GetEntryCount();
558 void NavigationControllerImpl::GoBack() {
559 if (!CanGoBack()) {
560 NOTREACHED();
561 return;
564 // Base the navigation on where we are now...
565 int current_index = GetCurrentEntryIndex();
567 DiscardNonCommittedEntries();
569 pending_entry_index_ = current_index - 1;
570 entries_[pending_entry_index_]->SetTransitionType(
571 ui::PageTransitionFromInt(
572 entries_[pending_entry_index_]->GetTransitionType() |
573 ui::PAGE_TRANSITION_FORWARD_BACK));
574 NavigateToPendingEntry(NO_RELOAD);
577 void NavigationControllerImpl::GoForward() {
578 if (!CanGoForward()) {
579 NOTREACHED();
580 return;
583 bool transient = (transient_entry_index_ != -1);
585 // Base the navigation on where we are now...
586 int current_index = GetCurrentEntryIndex();
588 DiscardNonCommittedEntries();
590 pending_entry_index_ = current_index;
591 // If there was a transient entry, we removed it making the current index
592 // the next page.
593 if (!transient)
594 pending_entry_index_++;
596 entries_[pending_entry_index_]->SetTransitionType(
597 ui::PageTransitionFromInt(
598 entries_[pending_entry_index_]->GetTransitionType() |
599 ui::PAGE_TRANSITION_FORWARD_BACK));
600 NavigateToPendingEntry(NO_RELOAD);
603 void NavigationControllerImpl::GoToIndex(int index) {
604 if (index < 0 || index >= static_cast<int>(entries_.size())) {
605 NOTREACHED();
606 return;
609 if (transient_entry_index_ != -1) {
610 if (index == transient_entry_index_) {
611 // Nothing to do when navigating to the transient.
612 return;
614 if (index > transient_entry_index_) {
615 // Removing the transient is goint to shift all entries by 1.
616 index--;
620 DiscardNonCommittedEntries();
622 pending_entry_index_ = index;
623 entries_[pending_entry_index_]->SetTransitionType(
624 ui::PageTransitionFromInt(
625 entries_[pending_entry_index_]->GetTransitionType() |
626 ui::PAGE_TRANSITION_FORWARD_BACK));
627 NavigateToPendingEntry(NO_RELOAD);
630 void NavigationControllerImpl::GoToOffset(int offset) {
631 if (!CanGoToOffset(offset))
632 return;
634 GoToIndex(GetIndexForOffset(offset));
637 bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
638 if (index == last_committed_entry_index_ ||
639 index == pending_entry_index_)
640 return false;
642 RemoveEntryAtIndexInternal(index);
643 return true;
646 void NavigationControllerImpl::UpdateVirtualURLToURL(
647 NavigationEntryImpl* entry, const GURL& new_url) {
648 GURL new_virtual_url(new_url);
649 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
650 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
651 entry->SetVirtualURL(new_virtual_url);
655 void NavigationControllerImpl::LoadURL(
656 const GURL& url,
657 const Referrer& referrer,
658 ui::PageTransition transition,
659 const std::string& extra_headers) {
660 LoadURLParams params(url);
661 params.referrer = referrer;
662 params.transition_type = transition;
663 params.extra_headers = extra_headers;
664 LoadURLWithParams(params);
667 void NavigationControllerImpl::LoadURLWithParams(const LoadURLParams& params) {
668 TRACE_EVENT1("browser,navigation",
669 "NavigationControllerImpl::LoadURLWithParams",
670 "url", params.url.possibly_invalid_spec());
671 if (HandleDebugURL(params.url, params.transition_type)) {
672 // If Telemetry is running, allow the URL load to proceed as if it's
673 // unhandled, otherwise Telemetry can't tell if Navigation completed.
674 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
675 cc::switches::kEnableGpuBenchmarking))
676 return;
679 // Any renderer-side debug URLs or javascript: URLs should be ignored if the
680 // renderer process is not live, unless it is the initial navigation of the
681 // tab.
682 if (IsRendererDebugURL(params.url)) {
683 // TODO(creis): Find the RVH for the correct frame.
684 if (!delegate_->GetRenderViewHost()->IsRenderViewLive() &&
685 !IsInitialNavigation())
686 return;
689 // Checks based on params.load_type.
690 switch (params.load_type) {
691 case LOAD_TYPE_DEFAULT:
692 break;
693 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
694 if (!params.url.SchemeIs(url::kHttpScheme) &&
695 !params.url.SchemeIs(url::kHttpsScheme)) {
696 NOTREACHED() << "Http post load must use http(s) scheme.";
697 return;
699 break;
700 case LOAD_TYPE_DATA:
701 if (!params.url.SchemeIs(url::kDataScheme)) {
702 NOTREACHED() << "Data load must use data scheme.";
703 return;
705 break;
706 default:
707 NOTREACHED();
708 break;
711 // The user initiated a load, we don't need to reload anymore.
712 needs_reload_ = false;
714 bool override = false;
715 switch (params.override_user_agent) {
716 case UA_OVERRIDE_INHERIT:
717 override = ShouldKeepOverride(GetLastCommittedEntry());
718 break;
719 case UA_OVERRIDE_TRUE:
720 override = true;
721 break;
722 case UA_OVERRIDE_FALSE:
723 override = false;
724 break;
725 default:
726 NOTREACHED();
727 break;
730 scoped_ptr<NavigationEntryImpl> entry;
732 // For subframes, create a pending entry with a corresponding frame entry.
733 int frame_tree_node_id = params.frame_tree_node_id;
734 if (frame_tree_node_id != -1 || !params.frame_name.empty()) {
735 FrameTreeNode* node =
736 params.frame_tree_node_id != -1
737 ? delegate_->GetFrameTree()->FindByID(params.frame_tree_node_id)
738 : delegate_->GetFrameTree()->FindByName(params.frame_name);
739 if (node && !node->IsMainFrame()) {
740 DCHECK(GetLastCommittedEntry());
742 // Update the FTN ID to use below in case we found a named frame.
743 frame_tree_node_id = node->frame_tree_node_id();
745 // In --site-per-process, create an identical NavigationEntry with a
746 // new FrameNavigationEntry for the target subframe.
747 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
748 switches::kSitePerProcess)) {
749 entry = GetLastCommittedEntry()->Clone();
750 entry->SetPageID(-1);
751 entry->AddOrUpdateFrameEntry(node, -1, -1, nullptr, params.url,
752 params.referrer, PageState());
757 // Otherwise, create a pending entry for the main frame.
758 if (!entry) {
759 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
760 params.url, params.referrer, params.transition_type,
761 params.is_renderer_initiated, params.extra_headers, browser_context_));
763 // Set the FTN ID (only used in non-site-per-process, for tests).
764 entry->set_frame_tree_node_id(frame_tree_node_id);
765 entry->set_source_site_instance(
766 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
767 if (params.redirect_chain.size() > 0)
768 entry->SetRedirectChain(params.redirect_chain);
769 // Don't allow an entry replacement if there is no entry to replace.
770 // http://crbug.com/457149
771 if (params.should_replace_current_entry && entries_.size() > 0)
772 entry->set_should_replace_entry(true);
773 entry->set_should_clear_history_list(params.should_clear_history_list);
774 entry->SetIsOverridingUserAgent(override);
775 entry->set_transferred_global_request_id(
776 params.transferred_global_request_id);
778 #if defined(OS_ANDROID)
779 if (params.intent_received_timestamp > 0) {
780 entry->set_intent_received_timestamp(
781 base::TimeTicks() +
782 base::TimeDelta::FromMilliseconds(params.intent_received_timestamp));
784 #endif
786 switch (params.load_type) {
787 case LOAD_TYPE_DEFAULT:
788 break;
789 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST:
790 entry->SetHasPostData(true);
791 entry->SetBrowserInitiatedPostData(
792 params.browser_initiated_post_data.get());
793 break;
794 case LOAD_TYPE_DATA:
795 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
796 entry->SetVirtualURL(params.virtual_url_for_data_url);
797 entry->SetCanLoadLocalResources(params.can_load_local_resources);
798 break;
799 default:
800 NOTREACHED();
801 break;
804 LoadEntry(entry.Pass());
807 bool NavigationControllerImpl::RendererDidNavigate(
808 RenderFrameHostImpl* rfh,
809 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
810 LoadCommittedDetails* details) {
811 is_initial_navigation_ = false;
813 // Save the previous state before we clobber it.
814 if (GetLastCommittedEntry()) {
815 details->previous_url = GetLastCommittedEntry()->GetURL();
816 details->previous_entry_index = GetLastCommittedEntryIndex();
817 } else {
818 details->previous_url = GURL();
819 details->previous_entry_index = -1;
822 // If we have a pending entry at this point, it should have a SiteInstance.
823 // Restored entries start out with a null SiteInstance, but we should have
824 // assigned one in NavigateToPendingEntry.
825 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance());
827 // If we are doing a cross-site reload, we need to replace the existing
828 // navigation entry, not add another entry to the history. This has the side
829 // effect of removing forward browsing history, if such existed. Or if we are
830 // doing a cross-site redirect navigation, we will do a similar thing.
832 // If this is an error load, we may have already removed the pending entry
833 // when we got the notice of the load failure. If so, look at the copy of the
834 // pending parameters that were saved.
835 if (params.url_is_unreachable && failed_pending_entry_id_ != 0) {
836 details->did_replace_entry = failed_pending_entry_should_replace_;
837 } else {
838 details->did_replace_entry = pending_entry_ &&
839 pending_entry_->should_replace_entry();
842 // Do navigation-type specific actions. These will make and commit an entry.
843 details->type = ClassifyNavigation(rfh, params);
845 // is_in_page must be computed before the entry gets committed.
846 details->is_in_page = IsURLInPageNavigation(
847 params.url, params.was_within_same_page, rfh);
849 switch (details->type) {
850 case NAVIGATION_TYPE_NEW_PAGE:
851 RendererDidNavigateToNewPage(rfh, params, details->did_replace_entry);
852 break;
853 case NAVIGATION_TYPE_EXISTING_PAGE:
854 details->did_replace_entry = details->is_in_page;
855 RendererDidNavigateToExistingPage(rfh, params);
856 break;
857 case NAVIGATION_TYPE_SAME_PAGE:
858 RendererDidNavigateToSamePage(rfh, params);
859 break;
860 case NAVIGATION_TYPE_NEW_SUBFRAME:
861 RendererDidNavigateNewSubframe(rfh, params);
862 break;
863 case NAVIGATION_TYPE_AUTO_SUBFRAME:
864 if (!RendererDidNavigateAutoSubframe(rfh, params))
865 return false;
866 break;
867 case NAVIGATION_TYPE_NAV_IGNORE:
868 // If a pending navigation was in progress, this canceled it. We should
869 // discard it and make sure it is removed from the URL bar. After that,
870 // there is nothing we can do with this navigation, so we just return to
871 // the caller that nothing has happened.
872 if (pending_entry_) {
873 DiscardNonCommittedEntries();
874 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
876 return false;
877 default:
878 NOTREACHED();
881 // At this point, we know that the navigation has just completed, so
882 // record the time.
884 // TODO(akalin): Use "sane time" as described in
885 // http://www.chromium.org/developers/design-documents/sane-time .
886 base::Time timestamp =
887 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
888 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
889 << timestamp.ToInternalValue();
891 // We should not have a pending entry anymore. Clear it again in case any
892 // error cases above forgot to do so.
893 DiscardNonCommittedEntriesInternal();
895 // All committed entries should have nonempty content state so WebKit doesn't
896 // get confused when we go back to them (see the function for details).
897 DCHECK(params.page_state.IsValid());
898 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
899 active_entry->SetTimestamp(timestamp);
900 active_entry->SetHttpStatusCode(params.http_status_code);
901 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
902 switches::kSitePerProcess)) {
903 // Update the frame-specific PageState.
904 FrameNavigationEntry* frame_entry =
905 active_entry->GetFrameEntry(rfh->frame_tree_node());
906 frame_entry->set_page_state(params.page_state);
907 } else {
908 active_entry->SetPageState(params.page_state);
910 active_entry->SetRedirectChain(params.redirects);
912 // Use histogram to track memory impact of redirect chain because it's now
913 // not cleared for committed entries.
914 size_t redirect_chain_size = 0;
915 for (size_t i = 0; i < params.redirects.size(); ++i) {
916 redirect_chain_size += params.redirects[i].spec().length();
918 UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size);
920 // Once it is committed, we no longer need to track several pieces of state on
921 // the entry.
922 active_entry->ResetForCommit();
924 // The active entry's SiteInstance should match our SiteInstance.
925 // TODO(creis): This check won't pass for subframes until we create entries
926 // for subframe navigations.
927 if (!rfh->GetParent())
928 CHECK(active_entry->site_instance() == rfh->GetSiteInstance());
930 // Remember the bindings the renderer process has at this point, so that
931 // we do not grant this entry additional bindings if we come back to it.
932 active_entry->SetBindings(rfh->GetEnabledBindings());
934 // Now prep the rest of the details for the notification and broadcast.
935 details->entry = active_entry;
936 details->is_main_frame = !rfh->GetParent();
937 details->http_status_code = params.http_status_code;
939 // Deserialize the security info and kill the renderer if
940 // deserialization fails. The navigation will continue with default
941 // SSLStatus values.
942 if (!DeserializeSecurityInfo(params.security_info, &details->ssl_status)) {
943 bad_message::ReceivedBadMessage(
944 rfh->GetProcess(),
945 bad_message::WC_RENDERER_DID_NAVIGATE_BAD_SECURITY_INFO);
948 NotifyNavigationEntryCommitted(details);
950 return true;
953 NavigationType NavigationControllerImpl::ClassifyNavigation(
954 RenderFrameHostImpl* rfh,
955 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) const {
956 if (params.did_create_new_entry) {
957 // A new entry. We may or may not have a pending entry for the page, and
958 // this may or may not be the main frame.
959 if (!rfh->GetParent()) {
960 return NAVIGATION_TYPE_NEW_PAGE;
963 // When this is a new subframe navigation, we should have a committed page
964 // in which it's a subframe. This may not be the case when an iframe is
965 // navigated on a popup navigated to about:blank (the iframe would be
966 // written into the popup by script on the main page). For these cases,
967 // there isn't any navigation stuff we can do, so just ignore it.
968 if (!GetLastCommittedEntry())
969 return NAVIGATION_TYPE_NAV_IGNORE;
971 // Valid subframe navigation.
972 return NAVIGATION_TYPE_NEW_SUBFRAME;
975 // We only clear the session history when navigating to a new page.
976 DCHECK(!params.history_list_was_cleared);
978 if (rfh->GetParent()) {
979 // All manual subframes would be did_create_new_entry and handled above, so
980 // we know this is auto.
981 if (GetLastCommittedEntry()) {
982 return NAVIGATION_TYPE_AUTO_SUBFRAME;
983 } else {
984 // We ignore subframes created in non-committed pages; we'd appreciate if
985 // people stopped doing that.
986 return NAVIGATION_TYPE_NAV_IGNORE;
990 if (params.nav_entry_id == 0) {
991 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
992 // create a new page.
994 // Just like above in the did_create_new_entry case, it's possible to
995 // scribble onto an uncommitted page. Again, there isn't any navigation
996 // stuff that we can do, so ignore it here as well.
997 NavigationEntry* last_committed = GetLastCommittedEntry();
998 if (!last_committed)
999 return NAVIGATION_TYPE_NAV_IGNORE;
1001 // This is history.replaceState(), history.reload(), or a client-side
1002 // redirect.
1003 return NAVIGATION_TYPE_EXISTING_PAGE;
1006 if (pending_entry_ && pending_entry_index_ == -1 &&
1007 pending_entry_->GetUniqueID() == params.nav_entry_id) {
1008 // In this case, we have a pending entry for a load of a new URL but Blink
1009 // didn't do a new navigation (params.did_create_new_entry). This happens
1010 // when you press enter in the URL bar to reload. We will create a pending
1011 // entry, but Blink will convert it to a reload since it's the same page and
1012 // not create a new entry for it (the user doesn't want to have a new
1013 // back/forward entry when they do this). Therefore we want to just ignore
1014 // the pending entry and go back to where we were (the "existing entry").
1015 return NAVIGATION_TYPE_SAME_PAGE;
1018 if (params.intended_as_new_entry) {
1019 // This was intended to be a navigation to a new entry but the pending entry
1020 // got cleared in the meanwhile. Classify as EXISTING_PAGE because we may or
1021 // may not have a pending entry.
1022 return NAVIGATION_TYPE_EXISTING_PAGE;
1025 if (params.url_is_unreachable && failed_pending_entry_id_ != 0 &&
1026 params.nav_entry_id == failed_pending_entry_id_) {
1027 // If the renderer was going to a new pending entry that got cleared because
1028 // of an error, this is the case of the user trying to retry a failed load
1029 // by pressing return. Classify as EXISTING_PAGE because we probably don't
1030 // have a pending entry.
1031 return NAVIGATION_TYPE_EXISTING_PAGE;
1034 // Now we know that the notification is for an existing page. Find that entry.
1035 int existing_entry_index = GetEntryIndexWithUniqueID(params.nav_entry_id);
1036 if (existing_entry_index == -1) {
1037 // The renderer has committed a navigation to an entry that no longer
1038 // exists. Because the renderer is showing that page, resurrect that entry.
1039 return NAVIGATION_TYPE_NEW_PAGE;
1042 // Since we weeded out "new" navigations above, we know this is an existing
1043 // (back/forward) navigation.
1044 return NAVIGATION_TYPE_EXISTING_PAGE;
1047 void NavigationControllerImpl::RendererDidNavigateToNewPage(
1048 RenderFrameHostImpl* rfh,
1049 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
1050 bool replace_entry) {
1051 scoped_ptr<NavigationEntryImpl> new_entry;
1052 bool update_virtual_url;
1053 // Only make a copy of the pending entry if it is appropriate for the new page
1054 // that was just loaded. We verify this at a coarse grain by checking that
1055 // the SiteInstance hasn't been assigned to something else, and by making sure
1056 // that the pending entry was intended as a new entry (rather than being a
1057 // history navigation that was interrupted by an unrelated, renderer-initiated
1058 // navigation).
1059 if (pending_entry_ && pending_entry_index_ == -1 &&
1060 (!pending_entry_->site_instance() ||
1061 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
1062 new_entry = pending_entry_->Clone();
1064 update_virtual_url = new_entry->update_virtual_url_with_url();
1065 } else {
1066 new_entry = make_scoped_ptr(new NavigationEntryImpl);
1068 // Find out whether the new entry needs to update its virtual URL on URL
1069 // change and set up the entry accordingly. This is needed to correctly
1070 // update the virtual URL when replaceState is called after a pushState.
1071 GURL url = params.url;
1072 bool needs_update = false;
1073 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1074 &url, browser_context_, &needs_update);
1075 new_entry->set_update_virtual_url_with_url(needs_update);
1077 // When navigating to a new page, give the browser URL handler a chance to
1078 // update the virtual URL based on the new URL. For example, this is needed
1079 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1080 // the URL.
1081 update_virtual_url = needs_update;
1084 // Don't use the page type from the pending entry. Some interstitial page
1085 // may have set the type to interstitial. Once we commit, however, the page
1086 // type must always be normal or error.
1087 new_entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR
1088 : PAGE_TYPE_NORMAL);
1089 new_entry->SetURL(params.url);
1090 if (update_virtual_url)
1091 UpdateVirtualURLToURL(new_entry.get(), params.url);
1092 new_entry->SetReferrer(params.referrer);
1093 new_entry->SetPageID(params.page_id);
1094 new_entry->SetTransitionType(params.transition);
1095 new_entry->set_site_instance(
1096 static_cast<SiteInstanceImpl*>(rfh->GetSiteInstance()));
1097 new_entry->SetHasPostData(params.is_post);
1098 new_entry->SetPostID(params.post_id);
1099 new_entry->SetOriginalRequestURL(params.original_request_url);
1100 new_entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1102 // Update the FrameNavigationEntry for new main frame commits.
1103 FrameNavigationEntry* frame_entry =
1104 new_entry->GetFrameEntry(rfh->frame_tree_node());
1105 frame_entry->set_item_sequence_number(params.item_sequence_number);
1106 frame_entry->set_document_sequence_number(params.document_sequence_number);
1108 // history.pushState() is classified as a navigation to a new page, but
1109 // sets was_within_same_page to true. In this case, we already have the
1110 // title and favicon available, so set them immediately.
1111 if (params.was_within_same_page && GetLastCommittedEntry()) {
1112 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
1113 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
1116 DCHECK(!params.history_list_was_cleared || !replace_entry);
1117 // The browser requested to clear the session history when it initiated the
1118 // navigation. Now we know that the renderer has updated its state accordingly
1119 // and it is safe to also clear the browser side history.
1120 if (params.history_list_was_cleared) {
1121 DiscardNonCommittedEntriesInternal();
1122 entries_.clear();
1123 last_committed_entry_index_ = -1;
1126 InsertOrReplaceEntry(new_entry.Pass(), replace_entry);
1129 void NavigationControllerImpl::RendererDidNavigateToExistingPage(
1130 RenderFrameHostImpl* rfh,
1131 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1132 // We should only get here for main frame navigations.
1133 DCHECK(!rfh->GetParent());
1135 NavigationEntryImpl* entry;
1136 if (params.intended_as_new_entry) {
1137 // This was intended as a new entry but the pending entry was lost in the
1138 // meanwhile and no new page was created. We are stuck at the last committed
1139 // entry.
1140 entry = GetLastCommittedEntry();
1141 } else if (params.nav_entry_id) {
1142 // This is a browser-initiated navigation (back/forward/reload).
1143 entry = GetEntryWithUniqueID(params.nav_entry_id);
1144 } else {
1145 // This is renderer-initiated. The only kinds of renderer-initated
1146 // navigations that are EXISTING_PAGE are reloads and location.replace,
1147 // which land us at the last committed entry.
1148 entry = GetLastCommittedEntry();
1150 DCHECK(entry);
1152 // The URL may have changed due to redirects.
1153 entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR
1154 : PAGE_TYPE_NORMAL);
1155 entry->SetURL(params.url);
1156 entry->SetReferrer(params.referrer);
1157 if (entry->update_virtual_url_with_url())
1158 UpdateVirtualURLToURL(entry, params.url);
1160 // The redirected to page should not inherit the favicon from the previous
1161 // page.
1162 if (ui::PageTransitionIsRedirect(params.transition))
1163 entry->GetFavicon() = FaviconStatus();
1165 // The site instance will normally be the same except during session restore,
1166 // when no site instance will be assigned.
1167 DCHECK(entry->site_instance() == NULL ||
1168 entry->site_instance() == rfh->GetSiteInstance());
1169 entry->set_site_instance(
1170 static_cast<SiteInstanceImpl*>(rfh->GetSiteInstance()));
1172 entry->SetHasPostData(params.is_post);
1173 entry->SetPostID(params.post_id);
1175 // The entry we found in the list might be pending if the user hit
1176 // back/forward/reload. This load should commit it (since it's already in the
1177 // list, we can just discard the pending pointer). We should also discard the
1178 // pending entry if it corresponds to a different navigation, since that one
1179 // is now likely canceled. If it is not canceled, we will treat it as a new
1180 // navigation when it arrives, which is also ok.
1182 // Note that we need to use the "internal" version since we don't want to
1183 // actually change any other state, just kill the pointer.
1184 DiscardNonCommittedEntriesInternal();
1186 // If a transient entry was removed, the indices might have changed, so we
1187 // have to query the entry index again.
1188 last_committed_entry_index_ = GetIndexOfEntry(entry);
1191 void NavigationControllerImpl::RendererDidNavigateToSamePage(
1192 RenderFrameHostImpl* rfh,
1193 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1194 // This classification says that we have a pending entry that's the same as
1195 // the last committed entry. This entry is guaranteed to exist by
1196 // ClassifyNavigation. All we need to do is update the existing entry.
1197 NavigationEntryImpl* existing_entry = GetLastCommittedEntry();
1199 // We assign the entry's unique ID to be that of the new one. Since this is
1200 // always the result of a user action, we want to dismiss infobars, etc. like
1201 // a regular user-initiated navigation.
1202 existing_entry->set_unique_id(pending_entry_->GetUniqueID());
1204 // The URL may have changed due to redirects.
1205 existing_entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR
1206 : PAGE_TYPE_NORMAL);
1207 if (existing_entry->update_virtual_url_with_url())
1208 UpdateVirtualURLToURL(existing_entry, params.url);
1209 existing_entry->SetURL(params.url);
1210 existing_entry->SetReferrer(params.referrer);
1212 // The page may have been requested with a different HTTP method.
1213 existing_entry->SetHasPostData(params.is_post);
1214 existing_entry->SetPostID(params.post_id);
1216 DiscardNonCommittedEntries();
1219 void NavigationControllerImpl::RendererDidNavigateNewSubframe(
1220 RenderFrameHostImpl* rfh,
1221 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1222 if (!ui::PageTransitionCoreTypeIs(params.transition,
1223 ui::PAGE_TRANSITION_MANUAL_SUBFRAME)) {
1224 // There was a comment here that said, "This is not user-initiated. Ignore."
1225 // But this makes no sense; non-user-initiated navigations should be
1226 // determined to be of type NAVIGATION_TYPE_AUTO_SUBFRAME and sent to
1227 // RendererDidNavigateAutoSubframe below.
1229 // This if clause dates back to https://codereview.chromium.org/115919 and
1230 // the handling of immediate redirects. TODO(avi): Is this still valid? I'm
1231 // pretty sure that's there's nothing left of that code and that we should
1232 // take this out.
1234 // Except for cross-process iframes; this doesn't work yet for them.
1235 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1236 switches::kSitePerProcess)) {
1237 NOTREACHED();
1240 DiscardNonCommittedEntriesInternal();
1241 return;
1244 // Manual subframe navigations just get the current entry cloned so the user
1245 // can go back or forward to it. The actual subframe information will be
1246 // stored in the page state for each of those entries. This happens out of
1247 // band with the actual navigations.
1248 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
1249 << "that a last committed entry exists.";
1251 scoped_ptr<NavigationEntryImpl> new_entry;
1252 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1253 switches::kSitePerProcess)) {
1254 // Make sure new_entry takes ownership of frame_entry in a scoped_refptr.
1255 FrameNavigationEntry* frame_entry = new FrameNavigationEntry(
1256 rfh->frame_tree_node()->frame_tree_node_id(),
1257 params.item_sequence_number, params.document_sequence_number,
1258 rfh->GetSiteInstance(), params.url, params.referrer);
1259 new_entry = GetLastCommittedEntry()->CloneAndReplace(rfh->frame_tree_node(),
1260 frame_entry);
1261 CHECK(frame_entry->HasOneRef());
1262 } else {
1263 new_entry = GetLastCommittedEntry()->Clone();
1266 new_entry->SetPageID(params.page_id);
1267 InsertOrReplaceEntry(new_entry.Pass(), false);
1270 bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
1271 RenderFrameHostImpl* rfh,
1272 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
1273 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
1274 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
1276 // We're guaranteed to have a previously committed entry, and we now need to
1277 // handle navigation inside of a subframe in it without creating a new entry.
1278 DCHECK(GetLastCommittedEntry());
1280 if (params.nav_entry_id) {
1281 int entry_index = GetEntryIndexWithUniqueID(params.nav_entry_id);
1283 // If the |nav_entry_id| is non-zero and matches an existing entry, this is
1284 // a history auto" navigation. Update the last committed index accordingly.
1285 // If we don't recognize the |nav_entry_id|, it might be either a pending
1286 // entry for a transfer or a recently pruned entry. We'll handle it below.
1287 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
1288 // Make sure that a subframe commit isn't changing the main frame's
1289 // origin. Otherwise the renderer process may be confused, leading to a
1290 // URL spoof. We can't check the path since that may change
1291 // (https://crbug.com/373041).
1292 if (GetLastCommittedEntry()->GetURL().GetOrigin() !=
1293 GetEntryAtIndex(entry_index)->GetURL().GetOrigin()) {
1294 // TODO(creis): This is unexpectedly being encountered in practice. If
1295 // you encounter this in practice, please post details to
1296 // https://crbug.com/486916. Once that's resolved, we'll change this to
1297 // kill the renderer process with bad_message::NC_AUTO_SUBFRAME.
1298 NOTREACHED() << "Unexpected main frame origin change on AUTO_SUBFRAME.";
1301 // TODO(creis): Update the FrameNavigationEntry in --site-per-process.
1302 last_committed_entry_index_ = entry_index;
1303 DiscardNonCommittedEntriesInternal();
1304 return true;
1308 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1309 switches::kSitePerProcess)) {
1310 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
1311 // it may be a "history auto" case where we update an existing one.
1312 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
1313 last_committed->AddOrUpdateFrameEntry(
1314 rfh->frame_tree_node(), params.item_sequence_number,
1315 params.document_sequence_number, rfh->GetSiteInstance(), params.url,
1316 params.referrer, params.page_state);
1318 // Cross-process subframe navigations may leave a pending entry around.
1319 // Clear it if it's actually for the subframe.
1320 // TODO(creis): Don't use pending entries for subframe navigations.
1321 // See https://crbug.com/495161.
1322 if (pending_entry_ &&
1323 pending_entry_->frame_tree_node_id() ==
1324 rfh->frame_tree_node()->frame_tree_node_id()) {
1325 DiscardPendingEntry(false);
1329 // We do not need to discard the pending entry in this case, since we will
1330 // not generate commit notifications for this auto-subframe navigation.
1331 return false;
1334 int NavigationControllerImpl::GetIndexOfEntry(
1335 const NavigationEntryImpl* entry) const {
1336 const NavigationEntries::const_iterator i(std::find(
1337 entries_.begin(),
1338 entries_.end(),
1339 entry));
1340 return (i == entries_.end()) ? -1 : static_cast<int>(i - entries_.begin());
1343 // There are two general cases where a navigation is "in page":
1344 // 1. A fragment navigation, in which the url is kept the same except for the
1345 // reference fragment.
1346 // 2. A history API navigation (pushState and replaceState). This case is
1347 // always in-page, but the urls are not guaranteed to match excluding the
1348 // fragment. The relevant spec allows pushState/replaceState to any URL on
1349 // the same origin.
1350 // However, due to reloads, even identical urls are *not* guaranteed to be
1351 // in-page navigations, we have to trust the renderer almost entirely.
1352 // The one thing we do know is that cross-origin navigations will *never* be
1353 // in-page. Therefore, trust the renderer if the URLs are on the same origin,
1354 // and assume the renderer is malicious if a cross-origin navigation claims to
1355 // be in-page.
1356 bool NavigationControllerImpl::IsURLInPageNavigation(
1357 const GURL& url,
1358 bool renderer_says_in_page,
1359 RenderFrameHost* rfh) const {
1360 GURL last_committed_url;
1361 if (rfh->GetParent()) {
1362 last_committed_url = rfh->GetLastCommittedURL();
1363 } else {
1364 NavigationEntry* last_committed = GetLastCommittedEntry();
1365 // There must be a last-committed entry to compare URLs to. TODO(avi): When
1366 // might Blink say that a navigation is in-page yet there be no last-
1367 // committed entry?
1368 if (!last_committed)
1369 return false;
1370 last_committed_url = last_committed->GetURL();
1373 WebPreferences prefs = rfh->GetRenderViewHost()->GetWebkitPreferences();
1374 bool is_same_origin = last_committed_url.is_empty() ||
1375 // TODO(japhet): We should only permit navigations
1376 // originating from about:blank to be in-page if the
1377 // about:blank is the first document that frame loaded.
1378 // We don't have sufficient information to identify
1379 // that case at the moment, so always allow about:blank
1380 // for now.
1381 last_committed_url == GURL(url::kAboutBlankURL) ||
1382 last_committed_url.GetOrigin() == url.GetOrigin() ||
1383 !prefs.web_security_enabled ||
1384 (prefs.allow_universal_access_from_file_urls &&
1385 last_committed_url.SchemeIs(url::kFileScheme));
1386 if (!is_same_origin && renderer_says_in_page) {
1387 bad_message::ReceivedBadMessage(rfh->GetProcess(),
1388 bad_message::NC_IN_PAGE_NAVIGATION);
1390 return is_same_origin && renderer_says_in_page;
1393 void NavigationControllerImpl::CopyStateFrom(
1394 const NavigationController& temp) {
1395 const NavigationControllerImpl& source =
1396 static_cast<const NavigationControllerImpl&>(temp);
1397 // Verify that we look new.
1398 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
1400 if (source.GetEntryCount() == 0)
1401 return; // Nothing new to do.
1403 needs_reload_ = true;
1404 InsertEntriesFrom(source, source.GetEntryCount());
1406 for (SessionStorageNamespaceMap::const_iterator it =
1407 source.session_storage_namespace_map_.begin();
1408 it != source.session_storage_namespace_map_.end();
1409 ++it) {
1410 SessionStorageNamespaceImpl* source_namespace =
1411 static_cast<SessionStorageNamespaceImpl*>(it->second.get());
1412 session_storage_namespace_map_[it->first] = source_namespace->Clone();
1415 FinishRestore(source.last_committed_entry_index_, RESTORE_CURRENT_SESSION);
1417 // Copy the max page id map from the old tab to the new tab. This ensures
1418 // that new and existing navigations in the tab's current SiteInstances
1419 // are identified properly.
1420 delegate_->CopyMaxPageIDsFrom(source.delegate()->GetWebContents());
1423 void NavigationControllerImpl::CopyStateFromAndPrune(
1424 NavigationController* temp,
1425 bool replace_entry) {
1426 // It is up to callers to check the invariants before calling this.
1427 CHECK(CanPruneAllButLastCommitted());
1429 NavigationControllerImpl* source =
1430 static_cast<NavigationControllerImpl*>(temp);
1432 // Remove all the entries leaving the last committed entry.
1433 PruneAllButLastCommittedInternal();
1435 // We now have one entry, possibly with a new pending entry. Ensure that
1436 // adding the entries from source won't put us over the limit.
1437 DCHECK_EQ(1, GetEntryCount());
1438 if (!replace_entry)
1439 source->PruneOldestEntryIfFull();
1441 // Insert the entries from source. Don't use source->GetCurrentEntryIndex as
1442 // we don't want to copy over the transient entry. Ignore any pending entry,
1443 // since it has not committed in source.
1444 int max_source_index = source->last_committed_entry_index_;
1445 if (max_source_index == -1)
1446 max_source_index = source->GetEntryCount();
1447 else
1448 max_source_index++;
1450 // Ignore the source's current entry if merging with replacement.
1451 // TODO(davidben): This should preserve entries forward of the current
1452 // too. http://crbug.com/317872
1453 if (replace_entry && max_source_index > 0)
1454 max_source_index--;
1456 InsertEntriesFrom(*source, max_source_index);
1458 // Adjust indices such that the last entry and pending are at the end now.
1459 last_committed_entry_index_ = GetEntryCount() - 1;
1461 delegate_->SetHistoryOffsetAndLength(last_committed_entry_index_,
1462 GetEntryCount());
1464 // Copy the max page id map from the old tab to the new tab. This ensures that
1465 // new and existing navigations in the tab's current SiteInstances are
1466 // identified properly.
1467 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
1468 int32 site_max_page_id =
1469 delegate_->GetMaxPageIDForSiteInstance(last_committed->site_instance());
1470 delegate_->CopyMaxPageIDsFrom(source->delegate()->GetWebContents());
1471 delegate_->UpdateMaxPageIDForSiteInstance(last_committed->site_instance(),
1472 site_max_page_id);
1473 max_restored_page_id_ = source->max_restored_page_id_;
1476 bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
1477 // If there is no last committed entry, we cannot prune. Even if there is a
1478 // pending entry, it may not commit, leaving this WebContents blank, despite
1479 // possibly giving it new entries via CopyStateFromAndPrune.
1480 if (last_committed_entry_index_ == -1)
1481 return false;
1483 // We cannot prune if there is a pending entry at an existing entry index.
1484 // It may not commit, so we have to keep the last committed entry, and thus
1485 // there is no sensible place to keep the pending entry. It is ok to have
1486 // a new pending entry, which can optionally commit as a new navigation.
1487 if (pending_entry_index_ != -1)
1488 return false;
1490 // We should not prune if we are currently showing a transient entry.
1491 if (transient_entry_index_ != -1)
1492 return false;
1494 return true;
1497 void NavigationControllerImpl::PruneAllButLastCommitted() {
1498 PruneAllButLastCommittedInternal();
1500 DCHECK_EQ(0, last_committed_entry_index_);
1501 DCHECK_EQ(1, GetEntryCount());
1503 delegate_->SetHistoryOffsetAndLength(last_committed_entry_index_,
1504 GetEntryCount());
1507 void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
1508 // It is up to callers to check the invariants before calling this.
1509 CHECK(CanPruneAllButLastCommitted());
1511 // Erase all entries but the last committed entry. There may still be a
1512 // new pending entry after this.
1513 entries_.erase(entries_.begin(),
1514 entries_.begin() + last_committed_entry_index_);
1515 entries_.erase(entries_.begin() + 1, entries_.end());
1516 last_committed_entry_index_ = 0;
1519 void NavigationControllerImpl::ClearAllScreenshots() {
1520 screenshot_manager_->ClearAllScreenshots();
1523 void NavigationControllerImpl::SetSessionStorageNamespace(
1524 const std::string& partition_id,
1525 SessionStorageNamespace* session_storage_namespace) {
1526 if (!session_storage_namespace)
1527 return;
1529 // We can't overwrite an existing SessionStorage without violating spec.
1530 // Attempts to do so may give a tab access to another tab's session storage
1531 // so die hard on an error.
1532 bool successful_insert = session_storage_namespace_map_.insert(
1533 make_pair(partition_id,
1534 static_cast<SessionStorageNamespaceImpl*>(
1535 session_storage_namespace)))
1536 .second;
1537 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
1540 void NavigationControllerImpl::SetMaxRestoredPageID(int32 max_id) {
1541 max_restored_page_id_ = max_id;
1544 int32 NavigationControllerImpl::GetMaxRestoredPageID() const {
1545 return max_restored_page_id_;
1548 bool NavigationControllerImpl::IsUnmodifiedBlankTab() const {
1549 return IsInitialNavigation() &&
1550 !GetLastCommittedEntry() &&
1551 !delegate_->HasAccessedInitialDocument();
1554 SessionStorageNamespace*
1555 NavigationControllerImpl::GetSessionStorageNamespace(SiteInstance* instance) {
1556 std::string partition_id;
1557 if (instance) {
1558 // TODO(ajwong): When GetDefaultSessionStorageNamespace() goes away, remove
1559 // this if statement so |instance| must not be NULL.
1560 partition_id =
1561 GetContentClient()->browser()->GetStoragePartitionIdForSite(
1562 browser_context_, instance->GetSiteURL());
1565 SessionStorageNamespaceMap::const_iterator it =
1566 session_storage_namespace_map_.find(partition_id);
1567 if (it != session_storage_namespace_map_.end())
1568 return it->second.get();
1570 // Create one if no one has accessed session storage for this partition yet.
1572 // TODO(ajwong): Should this use the |partition_id| directly rather than
1573 // re-lookup via |instance|? http://crbug.com/142685
1574 StoragePartition* partition =
1575 BrowserContext::GetStoragePartition(browser_context_, instance);
1576 SessionStorageNamespaceImpl* session_storage_namespace =
1577 new SessionStorageNamespaceImpl(
1578 static_cast<DOMStorageContextWrapper*>(
1579 partition->GetDOMStorageContext()));
1580 session_storage_namespace_map_[partition_id] = session_storage_namespace;
1582 return session_storage_namespace;
1585 SessionStorageNamespace*
1586 NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
1587 // TODO(ajwong): Remove if statement in GetSessionStorageNamespace().
1588 return GetSessionStorageNamespace(NULL);
1591 const SessionStorageNamespaceMap&
1592 NavigationControllerImpl::GetSessionStorageNamespaceMap() const {
1593 return session_storage_namespace_map_;
1596 bool NavigationControllerImpl::NeedsReload() const {
1597 return needs_reload_;
1600 void NavigationControllerImpl::SetNeedsReload() {
1601 needs_reload_ = true;
1603 if (last_committed_entry_index_ != -1) {
1604 entries_[last_committed_entry_index_]->SetTransitionType(
1605 ui::PAGE_TRANSITION_RELOAD);
1609 void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
1610 DCHECK(index < GetEntryCount());
1611 DCHECK(index != last_committed_entry_index_);
1613 DiscardNonCommittedEntries();
1615 entries_.erase(entries_.begin() + index);
1616 if (last_committed_entry_index_ > index)
1617 last_committed_entry_index_--;
1620 void NavigationControllerImpl::DiscardNonCommittedEntries() {
1621 bool transient = transient_entry_index_ != -1;
1622 DiscardNonCommittedEntriesInternal();
1624 // If there was a transient entry, invalidate everything so the new active
1625 // entry state is shown.
1626 if (transient) {
1627 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
1631 NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() const {
1632 return pending_entry_;
1635 int NavigationControllerImpl::GetPendingEntryIndex() const {
1636 return pending_entry_index_;
1639 void NavigationControllerImpl::InsertOrReplaceEntry(
1640 scoped_ptr<NavigationEntryImpl> entry, bool replace) {
1641 DCHECK(entry->GetTransitionType() != ui::PAGE_TRANSITION_AUTO_SUBFRAME);
1643 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
1644 // need to keep continuity with the pending entry, so copy the pending entry's
1645 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
1646 // then the renderer navigated on its own, independent of the pending entry,
1647 // so don't copy anything.
1648 if (pending_entry_ && pending_entry_index_ == -1)
1649 entry->set_unique_id(pending_entry_->GetUniqueID());
1651 DiscardNonCommittedEntriesInternal();
1653 int current_size = static_cast<int>(entries_.size());
1654 DCHECK_IMPLIES(replace, current_size > 0);
1656 if (current_size > 0) {
1657 // Prune any entries which are in front of the current entry.
1658 // Also prune the current entry if we are to replace the current entry.
1659 // last_committed_entry_index_ must be updated here since calls to
1660 // NotifyPrunedEntries() below may re-enter and we must make sure
1661 // last_committed_entry_index_ is not left in an invalid state.
1662 if (replace)
1663 --last_committed_entry_index_;
1665 int num_pruned = 0;
1666 while (last_committed_entry_index_ < (current_size - 1)) {
1667 num_pruned++;
1668 entries_.pop_back();
1669 current_size--;
1671 if (num_pruned > 0) // Only notify if we did prune something.
1672 NotifyPrunedEntries(this, false, num_pruned);
1675 PruneOldestEntryIfFull();
1677 int32 page_id = entry->GetPageID();
1678 entries_.push_back(entry.Pass());
1679 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
1681 // This is a new page ID, so we need everybody to know about it.
1682 delegate_->UpdateMaxPageID(page_id);
1685 void NavigationControllerImpl::PruneOldestEntryIfFull() {
1686 if (entries_.size() >= max_entry_count()) {
1687 DCHECK_EQ(max_entry_count(), entries_.size());
1688 DCHECK_GT(last_committed_entry_index_, 0);
1689 RemoveEntryAtIndex(0);
1690 NotifyPrunedEntries(this, true, 1);
1694 void NavigationControllerImpl::NavigateToPendingEntry(ReloadType reload_type) {
1695 needs_reload_ = false;
1697 // If we were navigating to a slow-to-commit page, and the user performs
1698 // a session history navigation to the last committed page, RenderViewHost
1699 // will force the throbber to start, but WebKit will essentially ignore the
1700 // navigation, and won't send a message to stop the throbber. To prevent this
1701 // from happening, we drop the navigation here and stop the slow-to-commit
1702 // page from loading (which would normally happen during the navigation).
1703 if (pending_entry_index_ != -1 &&
1704 pending_entry_index_ == last_committed_entry_index_ &&
1705 (entries_[pending_entry_index_]->restore_type() ==
1706 NavigationEntryImpl::RESTORE_NONE) &&
1707 (entries_[pending_entry_index_]->GetTransitionType() &
1708 ui::PAGE_TRANSITION_FORWARD_BACK)) {
1709 delegate_->Stop();
1711 // If an interstitial page is showing, we want to close it to get back
1712 // to what was showing before.
1713 if (delegate_->GetInterstitialPage())
1714 delegate_->GetInterstitialPage()->DontProceed();
1716 DiscardNonCommittedEntries();
1717 return;
1720 // If an interstitial page is showing, the previous renderer is blocked and
1721 // cannot make new requests. Unblock (and disable) it to allow this
1722 // navigation to succeed. The interstitial will stay visible until the
1723 // resulting DidNavigate.
1724 if (delegate_->GetInterstitialPage()) {
1725 static_cast<InterstitialPageImpl*>(delegate_->GetInterstitialPage())->
1726 CancelForNavigation();
1729 // For session history navigations only the pending_entry_index_ is set.
1730 if (!pending_entry_) {
1731 DCHECK_NE(pending_entry_index_, -1);
1732 pending_entry_ = entries_[pending_entry_index_];
1735 // This call does not support re-entrancy. See http://crbug.com/347742.
1736 CHECK(!in_navigate_to_pending_entry_);
1737 in_navigate_to_pending_entry_ = true;
1738 bool success = NavigateToPendingEntryInternal(reload_type);
1739 in_navigate_to_pending_entry_ = false;
1741 if (!success)
1742 DiscardNonCommittedEntries();
1744 // If the entry is being restored and doesn't have a SiteInstance yet, fill
1745 // it in now that we know. This allows us to find the entry when it commits.
1746 if (pending_entry_ && !pending_entry_->site_instance() &&
1747 pending_entry_->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
1748 pending_entry_->set_site_instance(static_cast<SiteInstanceImpl*>(
1749 delegate_->GetPendingSiteInstance()));
1750 pending_entry_->set_restore_type(NavigationEntryImpl::RESTORE_NONE);
1754 bool NavigationControllerImpl::NavigateToPendingEntryInternal(
1755 ReloadType reload_type) {
1756 DCHECK(pending_entry_);
1757 FrameTreeNode* root = delegate_->GetFrameTree()->root();
1759 // In default Chrome, there are no subframe FrameNavigationEntries. Either
1760 // navigate the main frame or use the main frame's FrameNavigationEntry to
1761 // tell the indicated frame where to go.
1762 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1763 switches::kSitePerProcess)) {
1764 FrameNavigationEntry* frame_entry = GetPendingEntry()->GetFrameEntry(root);
1765 FrameTreeNode* frame = root;
1766 int ftn_id = GetPendingEntry()->frame_tree_node_id();
1767 if (ftn_id != -1) {
1768 frame = delegate_->GetFrameTree()->FindByID(ftn_id);
1769 DCHECK(frame);
1771 return frame->navigator()->NavigateToPendingEntry(frame, *frame_entry,
1772 reload_type, false);
1775 // In --site-per-process, we compare FrameNavigationEntries to see which
1776 // frames in the tree need to be navigated.
1777 FrameLoadVector same_document_loads;
1778 FrameLoadVector different_document_loads;
1779 if (GetLastCommittedEntry()) {
1780 FindFramesToNavigate(root, &same_document_loads, &different_document_loads);
1783 if (same_document_loads.empty() && different_document_loads.empty()) {
1784 // If we don't have any frames to navigate at this point, either
1785 // (1) there is no previous history entry to compare against, or
1786 // (2) we were unable to match any frames by name. In the first case,
1787 // doing a different document navigation to the root item is the only valid
1788 // thing to do. In the second case, we should have been able to find a
1789 // frame to navigate based on names if this were a same document
1790 // navigation, so we can safely assume this is the different document case.
1791 different_document_loads.push_back(
1792 std::make_pair(root, pending_entry_->GetFrameEntry(root)));
1795 // If all the frame loads fail, we will discard the pending entry.
1796 bool success = false;
1798 // Send all the same document frame loads before the different document loads.
1799 for (const auto& item : same_document_loads) {
1800 FrameTreeNode* frame = item.first;
1801 success |= frame->navigator()->NavigateToPendingEntry(frame, *item.second,
1802 reload_type, true);
1804 for (const auto& item : different_document_loads) {
1805 FrameTreeNode* frame = item.first;
1806 success |= frame->navigator()->NavigateToPendingEntry(frame, *item.second,
1807 reload_type, false);
1809 return success;
1812 void NavigationControllerImpl::FindFramesToNavigate(
1813 FrameTreeNode* frame,
1814 FrameLoadVector* same_document_loads,
1815 FrameLoadVector* different_document_loads) {
1816 DCHECK(pending_entry_);
1817 DCHECK_GE(last_committed_entry_index_, 0);
1818 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
1819 FrameNavigationEntry* old_item =
1820 GetLastCommittedEntry()->GetFrameEntry(frame);
1821 if (!new_item)
1822 return;
1824 // Schedule a load in this frame if the new item isn't for the same item
1825 // sequence number in the same SiteInstance.
1826 if (!old_item ||
1827 new_item->item_sequence_number() != old_item->item_sequence_number() ||
1828 new_item->site_instance() != old_item->site_instance()) {
1829 if (old_item &&
1830 new_item->document_sequence_number() ==
1831 old_item->document_sequence_number()) {
1832 same_document_loads->push_back(std::make_pair(frame, new_item));
1833 } else {
1834 different_document_loads->push_back(std::make_pair(frame, new_item));
1836 return;
1839 for (size_t i = 0; i < frame->child_count(); i++) {
1840 FindFramesToNavigate(frame->child_at(i), same_document_loads,
1841 different_document_loads);
1845 void NavigationControllerImpl::NotifyNavigationEntryCommitted(
1846 LoadCommittedDetails* details) {
1847 details->entry = GetLastCommittedEntry();
1849 // We need to notify the ssl_manager_ before the web_contents_ so the
1850 // location bar will have up-to-date information about the security style
1851 // when it wants to draw. See http://crbug.com/11157
1852 ssl_manager_.DidCommitProvisionalLoad(*details);
1854 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
1855 delegate_->NotifyNavigationEntryCommitted(*details);
1857 // TODO(avi): Remove. http://crbug.com/170921
1858 NotificationDetails notification_details =
1859 Details<LoadCommittedDetails>(details);
1860 NotificationService::current()->Notify(
1861 NOTIFICATION_NAV_ENTRY_COMMITTED,
1862 Source<NavigationController>(this),
1863 notification_details);
1866 // static
1867 size_t NavigationControllerImpl::max_entry_count() {
1868 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
1869 return max_entry_count_for_testing_;
1870 return kMaxSessionHistoryEntries;
1873 void NavigationControllerImpl::SetActive(bool is_active) {
1874 if (is_active && needs_reload_)
1875 LoadIfNecessary();
1878 void NavigationControllerImpl::LoadIfNecessary() {
1879 if (!needs_reload_)
1880 return;
1882 // Calling Reload() results in ignoring state, and not loading.
1883 // Explicitly use NavigateToPendingEntry so that the renderer uses the
1884 // cached state.
1885 pending_entry_index_ = last_committed_entry_index_;
1886 NavigateToPendingEntry(NO_RELOAD);
1889 void NavigationControllerImpl::NotifyEntryChanged(
1890 const NavigationEntry* entry) {
1891 EntryChangedDetails det;
1892 det.changed_entry = entry;
1893 det.index = GetIndexOfEntry(
1894 NavigationEntryImpl::FromNavigationEntry(entry));
1895 NotificationService::current()->Notify(
1896 NOTIFICATION_NAV_ENTRY_CHANGED,
1897 Source<NavigationController>(this),
1898 Details<EntryChangedDetails>(&det));
1901 void NavigationControllerImpl::FinishRestore(int selected_index,
1902 RestoreType type) {
1903 DCHECK(selected_index >= 0 && selected_index < GetEntryCount());
1904 ConfigureEntriesForRestore(&entries_, type);
1906 SetMaxRestoredPageID(static_cast<int32>(GetEntryCount()));
1908 last_committed_entry_index_ = selected_index;
1911 void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
1912 DiscardPendingEntry(false);
1913 DiscardTransientEntry();
1916 void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
1917 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
1918 // progress, since this will cause a use-after-free. (We only allow this
1919 // when the tab is being destroyed for shutdown, since it won't return to
1920 // NavigateToEntry in that case.) http://crbug.com/347742.
1921 CHECK(!in_navigate_to_pending_entry_ || delegate_->IsBeingDestroyed());
1923 if (was_failure && pending_entry_) {
1924 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
1925 failed_pending_entry_should_replace_ =
1926 pending_entry_->should_replace_entry();
1927 } else {
1928 failed_pending_entry_id_ = 0;
1931 if (pending_entry_index_ == -1)
1932 delete pending_entry_;
1933 pending_entry_ = NULL;
1934 pending_entry_index_ = -1;
1937 void NavigationControllerImpl::DiscardTransientEntry() {
1938 if (transient_entry_index_ == -1)
1939 return;
1940 entries_.erase(entries_.begin() + transient_entry_index_);
1941 if (last_committed_entry_index_ > transient_entry_index_)
1942 last_committed_entry_index_--;
1943 transient_entry_index_ = -1;
1946 int NavigationControllerImpl::GetEntryIndexWithPageID(
1947 SiteInstance* instance, int32 page_id) const {
1948 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
1949 if ((entries_[i]->site_instance() == instance) &&
1950 (entries_[i]->GetPageID() == page_id))
1951 return i;
1953 return -1;
1956 int NavigationControllerImpl::GetEntryIndexWithUniqueID(
1957 int nav_entry_id) const {
1958 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
1959 if (entries_[i]->GetUniqueID() == nav_entry_id)
1960 return i;
1962 return -1;
1965 NavigationEntryImpl* NavigationControllerImpl::GetTransientEntry() const {
1966 if (transient_entry_index_ == -1)
1967 return NULL;
1968 return entries_[transient_entry_index_];
1971 void NavigationControllerImpl::SetTransientEntry(
1972 scoped_ptr<NavigationEntry> entry) {
1973 // Discard any current transient entry, we can only have one at a time.
1974 int index = 0;
1975 if (last_committed_entry_index_ != -1)
1976 index = last_committed_entry_index_ + 1;
1977 DiscardTransientEntry();
1978 entries_.insert(entries_.begin() + index,
1979 NavigationEntryImpl::FromNavigationEntry(entry.release()));
1980 transient_entry_index_ = index;
1981 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
1984 void NavigationControllerImpl::InsertEntriesFrom(
1985 const NavigationControllerImpl& source,
1986 int max_index) {
1987 DCHECK_LE(max_index, source.GetEntryCount());
1988 size_t insert_index = 0;
1989 for (int i = 0; i < max_index; i++) {
1990 // When cloning a tab, copy all entries except interstitial pages.
1991 if (source.entries_[i]->GetPageType() != PAGE_TYPE_INTERSTITIAL) {
1992 // TODO(creis): Once we start sharing FrameNavigationEntries between
1993 // NavigationEntries, it will not be safe to share them with another tab.
1994 // Must have a version of Clone that recreates them.
1995 entries_.insert(entries_.begin() + insert_index++,
1996 source.entries_[i]->Clone().Pass());
2001 void NavigationControllerImpl::SetGetTimestampCallbackForTest(
2002 const base::Callback<base::Time()>& get_timestamp_callback) {
2003 get_timestamp_callback_ = get_timestamp_callback;
2006 } // namespace content