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