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