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