blob: 1ee80fd346ab68abdf9ad39ceb5ac8292b4bad64 [file] [log] [blame]
Avi Drissman4e1b7bc32022-09-15 14:03:501// Copyright 2013 The Chromium Authors
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
creis4e2ecb72015-06-20 00:46:305/*
6 * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
8 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved.
9 * (http://www.torchmobile.com/)
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 *
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
21 * its contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
25 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
28 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35
danakjc492bf82020-09-09 20:02:4436#include "content/browser/renderer_host/navigation_controller_impl.h"
initial.commit09911bf2008-07-26 23:55:2937
Lei Zhang96031532019-10-10 19:05:4738#include <algorithm>
dcheng36b6aec92015-12-26 06:16:3639#include <utility>
40
[email protected]eabfe1912014-05-12 10:07:2841#include "base/command_line.h"
Ayu Ishii2f825852022-03-08 19:47:3842#include "base/containers/adapters.h"
Rakina Zata Amni627360d2022-02-24 00:53:4043#include "base/debug/dump_without_crashing.h"
Avi Drissmanadac21992023-01-11 23:46:3944#include "base/functional/bind.h"
initial.commit09911bf2008-07-26 23:55:2945#include "base/logging.h"
asvitkine30330812016-08-30 04:01:0846#include "base/metrics/histogram_macros.h"
Charlie Reis23c26da2022-01-29 00:57:4747#include "base/numerics/safe_conversions.h"
Ryan Hamilton7f3bd3d2022-04-23 00:07:3948#include "base/strings/escape.h"
Peter Kastingb53b81912021-04-28 19:23:3049#include "base/strings/string_piece.h"
[email protected]348fbaac2013-06-11 06:31:5150#include "base/strings/string_util.h"
[email protected]74ebfb12013-06-07 20:48:0051#include "base/strings/utf_string_conversions.h"
[email protected]a43858f2013-06-28 15:18:3752#include "base/time/time.h"
Carlos Caballero40b0efd2021-01-26 11:55:0053#include "base/trace_event/optional_trace_event.h"
Carlos Caballeroede6f8c2021-01-28 11:01:5054#include "base/trace_event/trace_conversion_helper.h"
ssid3e765612015-01-28 04:03:4255#include "base/trace_event/trace_event.h"
Daniel Chengabb006862022-09-09 22:39:0856#include "base/types/optional_util.h"
servolkf3955532015-05-16 00:01:5957#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2858#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1859#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3960#include "content/browser/blob_storage/chrome_blob_storage_context.h"
[email protected]825b1662012-03-12 19:07:3161#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4162#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0463#include "content/browser/dom_storage/session_storage_namespace_impl.h"
danakjc492bf82020-09-09 20:02:4464#include "content/browser/renderer_host/debug_urls.h"
65#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0066#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3367#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4468#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5769#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4470#include "content/browser/renderer_host/navigation_request.h"
71#include "content/browser/renderer_host/navigator.h"
72#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0073#include "content/browser/renderer_host/render_view_host_impl.h"
Sharon Yangd70a5392021-10-26 23:06:3274#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3375#include "content/browser/site_instance_impl.h"
Kunihiko Sakamoto346a74e2021-03-10 08:57:4876#include "content/browser/web_package/subresource_web_bundle_navigation_info.h"
Camille Lamy5193caa2018-10-12 11:59:4277#include "content/common/content_constants_internal.h"
Nate Chapind1fe3612021-04-16 20:45:5778#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5179#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1180#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1981#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1182#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4683#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0084#include "content/public/browser/navigation_details.h"
[email protected]7f6f44c2011-12-14 13:23:3885#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1686#include "content/public/browser/notification_types.h"
Lei Zhang96031532019-10-10 19:05:4787#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5888#include "content/public/browser/render_widget_host.h"
89#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1090#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3491#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1992#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3893#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1094#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:4795#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:4396#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:5997#include "media/base/mime_util.h"
Arthur Sonzogni620cec62018-12-13 13:08:5798#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:1899#include "services/metrics/public/cpp/ukm_builders.h"
100#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17101#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37102#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44103#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58104#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39105#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30106#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21107#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06108#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43109#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50110#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31111#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51112#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
sbinglera07ae732022-12-02 20:49:05113#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature_state.mojom.h"
[email protected]cca6f392014-05-28 21:32:26114#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29115
[email protected]8ff00d72012-10-23 19:12:21116namespace content {
[email protected]e9ba4472008-09-14 15:42:43117namespace {
118
119// Invoked when entries have been pruned, or removed. For example, if the
120// current entries are [google, digg, yahoo], with the current entry google,
121// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47122void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50123 int index,
[email protected]c12bf1a12008-09-17 16:28:49124 int count) {
[email protected]8ff00d72012-10-23 19:12:21125 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50126 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49127 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14128 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43129}
130
[email protected]e9ba4472008-09-14 15:42:43131// Configure all the NavigationEntries in entries for restore. This resets
132// the transition type to reload and makes sure the content state isn't empty.
133void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57134 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48135 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47136 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43137 // Use a transition type of reload so that we don't incorrectly increase
138 // the typed count.
Lei Zhang96031532019-10-10 19:05:47139 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
140 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43141 }
142}
143
[email protected]bf70edce2012-06-20 22:32:22144// Determines whether or not we should be carrying over a user agent override
145// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57146bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22147 return last_entry && last_entry->GetIsOverridingUserAgent();
148}
149
Camille Lamy5193caa2018-10-12 11:59:42150// Determines whether to override user agent for a navigation.
151bool ShouldOverrideUserAgent(
152 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57153 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42154 switch (override_user_agent) {
155 case NavigationController::UA_OVERRIDE_INHERIT:
156 return ShouldKeepOverride(last_committed_entry);
157 case NavigationController::UA_OVERRIDE_TRUE:
158 return true;
159 case NavigationController::UA_OVERRIDE_FALSE:
160 return false;
Camille Lamy5193caa2018-10-12 11:59:42161 }
162 NOTREACHED();
163 return false;
164}
165
Rakina Zata Amni312822d72021-06-04 16:13:37166// Returns true if this navigation should be treated as a reload. For e.g.
clamy0a656e42018-02-06 18:18:28167// navigating to the last committed url via the address bar or clicking on a
Rakina Zata Amni312822d72021-06-04 16:13:37168// link which results in a navigation to the last committed URL (but wasn't
169// converted to do a replacement navigation in the renderer), etc.
Fergal Daly766177d2020-07-07 07:54:04170// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
171// |base_url_for_data_url|, |transition_type| correspond to the new navigation
172// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
173// navigation that committed.
174bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
175 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57176 const GURL& virtual_url,
177 const GURL& base_url_for_data_url,
178 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57179 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37180 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57181 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37182 // Navigations intended to do a replacement shouldn't be converted to do a
183 // reload.
184 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28185 return false;
clamy0a656e42018-02-06 18:18:28186 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45187 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55188 return false;
189
arthursonzogni7a8243682017-12-14 16:41:42190 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28191 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42192 return false;
193
ananta3bdd8ae2016-12-22 17:11:55194 // We treat (PAGE_TRANSITION_RELOAD | PAGE_TRANSITION_FROM_ADDRESS_BAR),
195 // PAGE_TRANSITION_TYPED or PAGE_TRANSITION_LINK transitions as navigations
196 // which should be treated as reloads.
clamy0a656e42018-02-06 18:18:28197 bool transition_type_can_be_converted = false;
198 if (ui::PageTransitionCoreTypeIs(transition_type,
199 ui::PAGE_TRANSITION_RELOAD) &&
200 (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)) {
201 transition_type_can_be_converted = true;
ananta3bdd8ae2016-12-22 17:11:55202 }
clamy0a656e42018-02-06 18:18:28203 if (ui::PageTransitionCoreTypeIs(transition_type,
ananta3bdd8ae2016-12-22 17:11:55204 ui::PAGE_TRANSITION_TYPED)) {
clamy0a656e42018-02-06 18:18:28205 transition_type_can_be_converted = true;
206 }
207 if (ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_LINK))
208 transition_type_can_be_converted = true;
209 if (!transition_type_can_be_converted)
210 return false;
211
212 // This check is required for cases like view-source:, etc. Here the URL of
213 // the navigation entry would contain the url of the page, while the virtual
214 // URL contains the full URL including the view-source prefix.
215 if (virtual_url != last_committed_entry->GetVirtualURL())
216 return false;
217
Fergal Daly766177d2020-07-07 07:54:04218 // Check that the URLs match.
219 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
220 // If there's no frame entry then by definition the URLs don't match.
221 if (!frame_entry)
222 return false;
223
224 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28225 return false;
226
227 // This check is required for Android WebView loadDataWithBaseURL. Apps
228 // can pass in anything in the base URL and we need to ensure that these
229 // match before classifying it as a reload.
230 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
231 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
232 return false;
ananta3bdd8ae2016-12-22 17:11:55233 }
234
clamy0a656e42018-02-06 18:18:28235 // Skip entries with SSL errors.
236 if (last_committed_entry->ssl_error())
237 return false;
238
239 // Don't convert to a reload when the last navigation was a POST or the new
240 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04241 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28242 return false;
243
244 return true;
ananta3bdd8ae2016-12-22 17:11:55245}
246
Anton Bikineevf62d1bf2021-05-15 17:56:07247absl::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12248 const mojom::DidCommitProvisionalLoadParams& params,
249 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32250 // Error pages commit in an opaque origin, yet have the real URL that resulted
251 // in an error as the |params.url|. Since successful reload of an error page
252 // should commit in the correct origin, setting the opaque origin on the
253 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17254 if (request && request->DidEncounterError())
Anton Bikineevf62d1bf2021-05-15 17:56:07255 return absl::nullopt;
Nasko Oskov03912102019-01-11 00:21:32256
Anton Bikineevf62d1bf2021-05-15 17:56:07257 return absl::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32258}
259
Camille Lamy5193caa2018-10-12 11:59:42260bool IsValidURLForNavigation(bool is_main_frame,
261 const GURL& virtual_url,
262 const GURL& dest_url) {
263 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
264 if (is_main_frame && !virtual_url.is_valid() && !virtual_url.is_empty()) {
265 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
266 << virtual_url.possibly_invalid_spec();
267 return false;
268 }
269
270 // Don't attempt to navigate to non-empty invalid URLs.
271 if (!dest_url.is_valid() && !dest_url.is_empty()) {
272 LOG(WARNING) << "Refusing to load invalid URL: "
273 << dest_url.possibly_invalid_spec();
274 return false;
275 }
276
277 // The renderer will reject IPC messages with URLs longer than
278 // this limit, so don't attempt to navigate with a longer URL.
279 if (dest_url.spec().size() > url::kMaxURLChars) {
280 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
281 << " characters.";
282 return false;
283 }
284
Aaron Colwell33109c592020-04-21 21:31:19285 // Reject renderer debug URLs because they should have been handled before
286 // we get to this point. This check handles renderer debug URLs
287 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
288 // provides defense-in-depth if a renderer debug URL manages to get here via
289 // some other path. We want to reject the navigation here so it doesn't
290 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30291 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19292 LOG(WARNING) << "Refusing to load renderer debug URL: "
293 << dest_url.possibly_invalid_spec();
294 return false;
295 }
296
Camille Lamy5193caa2018-10-12 11:59:42297 return true;
298}
299
Mikel Astizba9cf2fd2017-12-17 10:38:10300// See replaced_navigation_entry_data.h for details: this information is meant
301// to ensure |*output_entry| keeps track of its original URL (landing page in
302// case of server redirects) as it gets replaced (e.g. history.replaceState()),
303// without overwriting it later, for main frames.
304void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57305 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10306 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17307 if (output_entry->GetReplacedEntryData().has_value() ||
308 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10309 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17310 }
Mikel Astizba9cf2fd2017-12-17 10:38:10311
312 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57313 data.first_committed_url = replaced_entry->GetURL();
314 data.first_timestamp = replaced_entry->GetTimestamp();
315 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29316 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10317}
318
Minggang Wangb9f3fa92021-07-01 15:30:31319blink::mojom::NavigationType GetNavigationType(
320 const GURL& old_url,
321 const GURL& new_url,
322 ReloadType reload_type,
323 NavigationEntryImpl* entry,
324 const FrameNavigationEntry& frame_entry,
325 bool has_pending_cross_document_commit,
326 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49327 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13328 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49329 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23330 // Reload navigations
331 switch (reload_type) {
332 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31333 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23334 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31335 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23336 case ReloadType::ORIGINAL_REQUEST_URL:
Minggang Wangb9f3fa92021-07-01 15:30:31337 return blink::mojom::NavigationType::RELOAD_ORIGINAL_REQUEST_URL;
clamyea99ea12018-05-28 13:54:23338 case ReloadType::NONE:
339 break; // Fall through to rest of function.
340 }
341
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08342 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31343 return entry->GetHasPostData()
344 ? blink::mojom::NavigationType::RESTORE_WITH_POST
345 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23346 }
347
danakjb952ef12021-01-14 19:58:49348 const bool can_be_same_document =
349 // A pending cross-document commit means this navigation will not occur in
350 // the current document, as that document would end up being replaced in
351 // the meantime.
352 !has_pending_cross_document_commit &&
353 // If the current document is an error page, we should always treat it as
354 // a different-document navigation so that we'll attempt to load the
355 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49356 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13357 // If the navigation is an embedder-initiated navigation of a fenced
358 // frame root (i.e. enters a fenced frame tree from outside),
359 // same-document navigations should be disabled because we don't want to
360 // allow information to be joined across multiple embedder-initiated
361 // fenced frame navigations (which may contain separate cross-site data).
362 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49363 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
364 // same-document navigations should be disabled because we want to force
365 // the creation of a new browsing context group.
366 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12367
clamyea99ea12018-05-28 13:54:23368 // History navigations.
369 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12370 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31371 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
372 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23373 }
374 DCHECK(!is_same_document_history_load);
375
376 // A same-document fragment-navigation happens when the only part of the url
377 // that is modified is after the '#' character.
378 //
379 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12380 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23381 //
382 // Note: this check is only valid for navigations that are not history
383 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
384 // history navigation from 'A#foo' to 'A#bar' is not a same-document
385 // navigation, but a different-document one. This is why history navigation
386 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47387 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
388 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12389
390 // The one case where we do the wrong thing here and incorrectly choose
391 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
392 // the renderer is a frameset. All frameset navigations should be
393 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
394 // navigation would do the right thing, as it would send it to the browser and
395 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
396 // into this method). But since we can't tell that case here for browser-
397 // initiated navigations, we have to get the renderer involved. In that case
398 // the navigation would be restarted due to the renderer spending a reply of
399 // mojom::CommitResult::RestartCrossDocument.
400
401 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31402 ? blink::mojom::NavigationType::SAME_DOCUMENT
403 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23404}
405
Camille Lamy5193caa2018-10-12 11:59:42406// Adjusts the original input URL if needed, to get the URL to actually load and
407// the virtual URL, which may differ.
408void RewriteUrlForNavigation(const GURL& original_url,
409 BrowserContext* browser_context,
410 GURL* url_to_load,
411 GURL* virtual_url,
412 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42413 // Allow the browser URL handler to rewrite the URL. This will, for example,
414 // remove "view-source:" from the beginning of the URL to get the URL that
415 // will actually be loaded. This real URL won't be shown to the user, just
416 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31417 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42418 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
419 url_to_load, browser_context, reverse_on_redirect);
420}
421
422#if DCHECK_IS_ON()
423// Helper sanity check function used in debug mode.
424void ValidateRequestMatchesEntry(NavigationRequest* request,
425 NavigationEntryImpl* entry) {
426 if (request->frame_tree_node()->IsMainFrame()) {
427 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
428 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31429 ui::PageTransitionFromInt(request->common_params().transition),
430 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42431 }
Nasko Oskovc36327d2019-01-03 23:23:04432 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42433 entry->should_clear_history_list());
434 DCHECK_EQ(request->common_params().has_user_gesture,
435 entry->has_user_gesture());
436 DCHECK_EQ(request->common_params().base_url_for_data_url,
437 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04438 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42439 entry->GetCanLoadLocalResources());
440 DCHECK_EQ(request->common_params().started_from_context_menu,
441 entry->has_started_from_context_menu());
442
443 FrameNavigationEntry* frame_entry =
444 entry->GetFrameEntry(request->frame_tree_node());
445 if (!frame_entry) {
446 NOTREACHED();
447 return;
448 }
449
Camille Lamy5193caa2018-10-12 11:59:42450 DCHECK_EQ(request->common_params().method, frame_entry->method());
451
Nasko Oskovc36327d2019-01-03 23:23:04452 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42453 if (redirect_size == frame_entry->redirect_chain().size()) {
454 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04455 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42456 frame_entry->redirect_chain()[i]);
457 }
458 } else {
459 NOTREACHED();
460 }
461}
462#endif // DCHECK_IS_ON()
463
Dave Tapuska8bfd84c2019-03-26 20:47:16464// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20465// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16466bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20467 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16468 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20469 DCHECK(sandboxed_initiator_rfh);
470 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
471 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16472 for (auto& item : navigations) {
473 bool within_subtree = false;
474 // Check whether this NavigationRequest affects a frame within the
475 // sandboxed frame's subtree by walking up the tree looking for the
476 // sandboxed frame.
477 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03478 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20479 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16480 within_subtree = true;
481 break;
482 }
483 }
484 if (!within_subtree)
485 return false;
486 }
487 return true;
488}
489
[email protected]e9ba4472008-09-14 15:42:43490} // namespace
491
arthursonzogni66f711c2019-10-08 14:40:36492// NavigationControllerImpl::PendingEntryRef------------------------------------
493
494NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
495 base::WeakPtr<NavigationControllerImpl> controller)
496 : controller_(controller) {}
497
498NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
499 if (!controller_) // Can be null with interstitials.
500 return;
501
502 controller_->PendingEntryRefDeleted(this);
503}
504
[email protected]d202a7c2012-01-04 07:53:47505// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29506
[email protected]23a918b2014-07-15 09:51:36507const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23508
[email protected]765b35502008-08-21 00:51:20509// static
[email protected]d202a7c2012-01-04 07:53:47510size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23511 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20512
[email protected]e6fec472013-05-14 05:29:02513// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20514// when testing.
515static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29516
[email protected]71fde352011-12-29 03:29:56517// static
dcheng9bfa5162016-04-09 01:00:57518std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
519 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10520 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07521 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21522 absl::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10523 ui::PageTransition transition,
524 bool is_renderer_initiated,
525 const std::string& extra_headers,
526 BrowserContext* browser_context,
527 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
528 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21529 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Lukasz Anforowicz641234d52019-11-07 21:07:10530 nullptr /* source_site_instance */, transition, is_renderer_initiated,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17531 extra_headers, browser_context, std::move(blob_url_loader_factory),
532 true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10533}
534
535// static
536std::unique_ptr<NavigationEntryImpl>
537NavigationControllerImpl::CreateNavigationEntry(
538 const GURL& url,
539 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07540 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21541 absl::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10542 SiteInstance* source_site_instance,
dcheng9bfa5162016-04-09 01:00:57543 ui::PageTransition transition,
544 bool is_renderer_initiated,
545 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09546 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17547 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
548 bool rewrite_virtual_urls) {
549 GURL url_to_load = url;
550 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56551 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17552 if (rewrite_virtual_urls) {
553 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
554 &reverse_on_redirect);
555 }
Lukasz Anforowicz641234d52019-11-07 21:07:10556 // Let the NTP override the navigation params and pretend that this is a
557 // browser-initiated, bookmark-like navigation.
558 GetContentClient()->browser()->OverrideNavigationParams(
Scott Violetcf6ea7e2021-06-09 21:09:21559 source_site_instance, &transition, &is_renderer_initiated, &referrer,
560 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10561
Patrick Monettef507e982019-06-19 20:18:06562 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28563 nullptr, // The site instance for tabs is sent on navigation
564 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21565 url_to_load, referrer, initiator_origin, initiator_base_url,
566 std::u16string(), transition, is_renderer_initiated,
567 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17568 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42569 entry->SetVirtualURL(virtual_url);
570 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56571 entry->set_update_virtual_url_with_url(reverse_on_redirect);
572 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06573 return entry;
[email protected]71fde352011-12-29 03:29:56574}
575
[email protected]cdcb1dee2012-01-04 00:46:20576// static
577void NavigationController::DisablePromptOnRepost() {
578 g_check_for_repost = false;
579}
580
[email protected]c5b88d82012-10-06 17:03:33581base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
582 base::Time t) {
583 // If |t| is between the water marks, we're in a run of duplicates
584 // or just getting out of it, so increase the high-water mark to get
585 // a time that probably hasn't been used before and return it.
586 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35587 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33588 return high_water_mark_;
589 }
590
591 // Otherwise, we're clear of the last duplicate run, so reset the
592 // water marks.
593 low_water_mark_ = high_water_mark_ = t;
594 return t;
595}
596
ckitagawa0faa5e42020-06-17 17:30:54597NavigationControllerImpl::ScopedShowRepostDialogForTesting::
598 ScopedShowRepostDialogForTesting()
599 : was_disallowed_(g_check_for_repost) {
600 g_check_for_repost = true;
601}
602
603NavigationControllerImpl::ScopedShowRepostDialogForTesting::
604 ~ScopedShowRepostDialogForTesting() {
605 g_check_for_repost = was_disallowed_;
606}
607
Nate Chapin9eb16be72022-09-23 22:54:31608NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
609 base::SafeRef<NavigationControllerImpl> controller)
610 : controller_(controller) {
611 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
612 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
613 frame_tree_node_id_to_keys_.insert(
614 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
615 if (auto* frame_entry = frame_tree_node->current_frame_host()
616 ->last_committed_frame_entry()) {
617 frame_tree_node_id_to_doc_seq_nos_.insert(
618 {frame_tree_node->frame_tree_node_id(),
619 frame_entry->document_sequence_number()});
620 }
621 }
622 PopulateKeySet(Direction::kBack);
623 PopulateKeySet(Direction::kForward);
624}
625
626void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
627 Direction direction) {
628 // Keep track of which FrameTreeNodes may still have relevant API keys in
629 // additional FrameNavigationEntries.
630 std::set<FrameTreeNode*> nodes_to_process;
631 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
632 nodes_to_process.insert(node);
633 }
634
635 const int offset = direction == Direction::kForward ? 1 : -1;
636 const int start = direction == Direction::kForward
637 ? controller_->GetLastCommittedEntryIndex()
638 : controller_->GetLastCommittedEntryIndex() - 1;
639 for (int i = start;
640 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
641 i += offset) {
642 std::set<FrameTreeNode*> nodes_to_continue_processing;
643
644 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
645 entry->ForEachFrameEntry([this, &nodes_to_process,
646 &nodes_to_continue_processing,
647 &entry](FrameNavigationEntry* frame_entry) {
648 // Find the |node| that matches |frame_entry|, if any.
649 FrameTreeNode* node = nullptr;
650 if (frame_entry == entry->root_node()->frame_entry) {
651 node = controller_->frame_tree().root();
652 } else {
653 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
654 if (it == names_to_nodes_.end())
655 return;
656 node = it->second;
657 }
658
659 // Skip this node if a previous step determine there are no longer
660 // relevant navigation API keys in this direction.
661 if (nodes_to_process.find(node) == nodes_to_process.end())
662 return;
663
664 // Stop processing |node| if we reach a point where it's cross-origin.
665 // See also PopulateSingleNavigationApiHistoryEntryVector().
666 url::Origin frame_entry_origin =
667 frame_entry->committed_origin().value_or(url::Origin::Resolve(
668 frame_entry->url(),
669 frame_entry->initiator_origin().value_or(url::Origin())));
670 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
671 return;
672
673 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
674 frame_entry->navigation_api_key());
675 // Mark |node| as needing more processing for the next entry.
676 nodes_to_continue_processing.insert(node);
677
678 // Check whether |node| went cross-document. If so, its children are
679 // no longer the same conceptual iframe as the current one, and
680 // should no longer be processed. This check is intentionally done
681 // after processing the current |node|, which may still have relevant
682 // discarded API keys.
683 if (frame_entry->document_sequence_number() !=
684 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50685 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31686 nodes_to_process.erase(descendant);
687 }
688 });
689
690 nodes_to_process.swap(nodes_to_continue_processing);
691 }
692}
693
694NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
695 std::set<std::string> all_keys;
696 // Find all remaining navigation API keys after some entries have been
697 // removed.
698 for (auto& entry : controller_->entries_) {
699 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
700 all_keys.insert(frame_entry->navigation_api_key());
701 });
702 }
703
704 // Notify each frame in the renderer of any disposed navigation API keys.
705 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
706 std::vector<std::string> disposed_keys;
707 for (const auto& key : id_to_keys.second) {
708 if (all_keys.find(key) == all_keys.end())
709 disposed_keys.push_back(key);
710 }
711 if (disposed_keys.empty())
712 continue;
713
714 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
715 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
716 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
717 }
718}
719
[email protected]d202a7c2012-01-04 07:53:47720NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00721 BrowserContext* browser_context,
722 FrameTree& frame_tree,
723 NavigationControllerDelegate* delegate)
724 : frame_tree_(frame_tree),
725 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57726 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22727 ssl_manager_(this),
Lei Zhang96031532019-10-10 19:05:47728 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)) {
[email protected]3d7474ff2011-07-27 17:47:37729 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29730}
731
[email protected]d202a7c2012-01-04 07:53:47732NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00733 // The NavigationControllerImpl might be called inside its delegate
734 // destructor. Calling it is not valid anymore.
735 delegate_ = nullptr;
736 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29737}
738
Matt Falkenhagen548ed1562021-07-06 01:38:26739WebContents* NavigationControllerImpl::DeprecatedGetWebContents() {
740 return delegate_->DeprecatedGetWebContents();
[email protected]fbc5e5f92012-01-02 06:08:32741}
742
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57743BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55744 return browser_context_;
745}
746
[email protected]d202a7c2012-01-04 07:53:47747void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30748 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36749 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57750 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47751 // Note that it's possible for `entries_` to contain multiple entries at this
752 // point, as Restore() might be called on a NavigationController that is
753 // already used (e.g. due to WebView's restoreState() API), not only for fresh
754 // NavigationControllers. These entries are not cleared to preserve legacy
755 // behavior and also because `pending_entry_` might point to one of the
756 // pre-existing entries. An exception for this is when `entries_` contains
757 // only the initial NavigationEntry, which must be removed.
758
759 // Do not proceed if selected_navigation will be out of bounds for the updated
760 // entries_ list, since it will be assigned to last_committed_entry_index_ and
761 // used to index entries_.
762 // TODO(https://crbug.com/1287624): Consider also returning early if entries
763 // is empty, since there should be no work to do (rather than marking the
764 // existing entries as needing reload). Also consider returning early if the
765 // selected index is -1, which represents a no-committed-entry state.
766 if (selected_navigation < -1 ||
767 selected_navigation >=
768 base::checked_cast<int>(entries->size() + entries_.size())) {
769 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24770 }
Charlie Reis23c26da2022-01-29 00:57:47771
Rakina Zata Amni46087a12022-11-11 08:28:38772 // There will always be at least one entry (new NavigationControllers will
773 // have the initial NavigationEntry).
774 if (selected_navigation == -1)
775 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47776
Rakina Zata Amni46087a12022-11-11 08:28:38777 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
778 // If we are on the initial NavigationEntry, it must be the only entry in
779 // the list. Since it's impossible to do a history navigation to the
780 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
781 // `pending_entry` might be set for a new non-history navigation).
782 // Note that we should not clear `entries_` if `entries` is empty (when
783 // InitialNavigationEntry mode is enabled), since that would leave us
784 // without any NavigationEntry.
785 CHECK_EQ(1, GetEntryCount());
786 CHECK_EQ(-1, pending_entry_index_);
787 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47788 }
[email protected]ce3fa3c2009-04-20 19:55:57789
[email protected]ce3fa3c2009-04-20 19:55:57790 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44791 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03792 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47793 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43794 if (entry->GetURL().is_empty()) {
795 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01796 // persisting the initial NavigationEntry [which is no longer possible but
797 // some old persisted sessions might still contain it] or when the
798 // serializer failed to write the URL because it's too long). Trying to
799 // restore and navigate to an entry with an empty URL will result in
800 // crashes, so change the URL to about:blank. See also
801 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43802 entry->SetURL(GURL(url::kAboutBlankURL));
803 }
dcheng36b6aec92015-12-26 06:16:36804 entries_.push_back(
805 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47806 }
avif16f85a72015-11-13 18:25:03807
808 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
809 // cleared out safely.
810 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57811
812 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36813 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57814}
815
toyoshim6142d96f2016-12-19 09:07:25816void NavigationControllerImpl::Reload(ReloadType reload_type,
817 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03818 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
819 (int)reload_type);
820 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
821 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28822 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28823 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32824 int current_index = -1;
825
Carlos IL42b416592019-10-07 23:10:36826 if (entry_replaced_by_post_commit_error_) {
827 // If there is an entry that was replaced by a currently active post-commit
828 // error navigation, this can't be the initial navigation.
829 DCHECK(!IsInitialNavigation());
830 // If the current entry is a post commit error, we reload the entry it
831 // replaced instead. We leave the error entry in place until a commit
832 // replaces it, but the pending entry points to the original entry in the
833 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
834 // case that pending_entry_ != entries_[pending_entry_index_].
835 entry = entry_replaced_by_post_commit_error_.get();
836 current_index = GetCurrentEntryIndex();
837 } else if (IsInitialNavigation() && pending_entry_) {
838 // If we are reloading the initial navigation, just use the current
839 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32840 entry = pending_entry_;
841 // The pending entry might be in entries_ (e.g., after a Clone), so we
842 // should also update the current_index.
843 current_index = pending_entry_index_;
844 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00845 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32846 current_index = GetCurrentEntryIndex();
847 if (current_index != -1) {
creis3da03872015-02-20 21:12:32848 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32849 }
[email protected]979a4bc2013-04-24 01:27:15850 }
[email protected]241db352013-04-22 18:04:05851
[email protected]59167c22013-06-03 18:07:32852 // If we are no where, then we can't reload. TODO(darin): We should add a
853 // CanReload method.
854 if (!entry)
855 return;
856
Rakina Zata Amnif297a802022-01-18 03:53:43857 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
858 // We should never navigate to an existing initial NavigationEntry that is
859 // the initial NavigationEntry for the initial empty document that hasn't
860 // been overridden by the synchronous about:blank commit, to preserve
861 // legacy behavior where trying to reload when the main frame is on the
862 // initial empty document won't result in a navigation. See also
863 // https://crbug.com/1277414.
864 return;
865 }
866
Aran Gilman37d11632019-10-08 23:07:15867 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30868 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07869 // they really want to do this. If they do, the dialog will call us back
870 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57871 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02872
[email protected]106a0812010-03-18 00:15:12873 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57874 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47875 return;
initial.commit09911bf2008-07-26 23:55:29876 }
Lei Zhang96031532019-10-10 19:05:47877
Wang Huia25efabc2022-09-24 17:27:22878 // Set ReloadType for |entry|.
879 entry->set_reload_type(reload_type);
880
Lei Zhang96031532019-10-10 19:05:47881 if (!IsInitialNavigation())
882 DiscardNonCommittedEntries();
883
884 pending_entry_ = entry;
885 pending_entry_index_ = current_index;
886 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
887
Nate Chapin45f620582021-09-30 17:45:43888 // location.reload() goes through BeginNavigation, so all reloads triggered
889 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13890 NavigateToExistingPendingEntry(
891 reload_type,
892 /*initiator_rfh=*/nullptr,
893 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
894 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29895}
896
[email protected]d202a7c2012-01-04 07:53:47897void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48898 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12899}
900
[email protected]d202a7c2012-01-04 07:53:47901void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49902 // If the pending reload type has been cleared by another navigation
903 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48904 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49905 return;
[email protected]106a0812010-03-18 00:15:12906 }
Wang Hui96ab1012022-10-11 02:05:49907 Reload(pending_reload_, false);
908 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12909}
910
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57911bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09912 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11913}
914
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57915bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38916 // Check that we're on the initial NavigationEntry and that this is not a
917 // cloned tab.
918 return IsInitialNavigation() && GetEntryCount() == 1 &&
919 GetLastCommittedEntry()->IsInitialEntry() &&
920 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40921}
922
Aran Gilman37d11632019-10-08 23:07:15923NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
924 int nav_entry_id) const {
avi254eff02015-07-01 08:27:58925 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:03926 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:58927}
928
Adithya Srinivasan9b0c99c2021-08-10 15:19:45929NavigationEntryImpl*
930NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
931 int nav_entry_id) const {
932 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
933 if (entry)
934 return entry;
935 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:52936 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:45937 : nullptr;
938}
939
W. James MacLeanc07dc41b2022-07-25 18:52:16940void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:57941 const url::Origin& origin) {
942 for (int i = 0; i < GetEntryCount(); i++) {
943 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:16944 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57945 }
946 if (entry_replaced_by_post_commit_error_) {
947 // It's possible we could come back to this entry if the error
948 // page/interstitial goes away.
949 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:16950 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57951 }
W. James MacLean1c40862c2020-04-27 21:05:57952}
953
avi25764702015-06-23 15:43:37954void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:57955 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:00956 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:37957 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:27958 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:20959}
960
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57961NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:47962 if (pending_entry_)
963 return pending_entry_;
964 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:20965}
966
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57967NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:32968 // The pending entry is safe to return for new (non-history), browser-
969 // initiated navigations. Most renderer-initiated navigations should not
970 // show the pending entry, to prevent URL spoof attacks.
971 //
972 // We make an exception for renderer-initiated navigations in new tabs, as
973 // long as no other page has tried to access the initial empty document in
974 // the new tab. If another page modifies this blank page, a URL spoof is
975 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:32976 bool safe_to_show_pending =
977 pending_entry_ &&
978 // Require a new navigation.
avi0dca04d2015-01-26 20:21:09979 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:32980 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:46981 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:32982
983 // Also allow showing the pending entry for history navigations in a new tab,
984 // such as Ctrl+Back. In this case, no existing page is visible and no one
985 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:15986 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
987 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:32988 safe_to_show_pending = true;
989
990 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:19991 return pending_entry_;
992 return GetLastCommittedEntry();
993}
994
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57995int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:20996 if (pending_entry_index_ != -1)
997 return pending_entry_index_;
998 return last_committed_entry_index_;
999}
1000
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571001NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381002 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031003 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201004}
1005
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571006bool NavigationControllerImpl::CanViewSource() {
Jeremy Roman2d8dfe132021-07-06 20:51:261007 const std::string& mime_type =
Ali Hijazid87307d2022-11-07 20:15:031008 frame_tree_->root()->current_frame_host()->GetPage().contents_mime_type();
Kinuko Yasuda74702f92017-07-31 03:27:531009 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1010 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271011 NavigationEntry* visible_entry = GetVisibleEntry();
1012 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391013 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161014}
1015
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571016int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271017 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451018 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271019 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551020 return last_committed_entry_index_;
1021}
1022
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571023int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451024 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291025 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551026 return static_cast<int>(entries_.size());
1027}
1028
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571029NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371030 if (index < 0 || index >= GetEntryCount())
1031 return nullptr;
1032
avif16f85a72015-11-13 18:25:031033 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251034}
1035
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571036NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471037 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201038}
1039
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571040int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461041 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031042}
1043
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571044bool NavigationControllerImpl::CanGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031045 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
1046 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1047 return true;
1048 }
1049 return false;
[email protected]765b35502008-08-21 00:51:201050}
1051
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571052bool NavigationControllerImpl::CanGoForward() {
WangHui74286d52021-03-31 16:17:151053 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1054 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1055 return true;
1056 }
1057 return false;
[email protected]765b35502008-08-21 00:51:201058}
1059
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571060bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031061 int index = GetIndexForOffset(offset);
1062 return index >= 0 && index < GetEntryCount();
1063}
1064
Xiaohan Wang7f8052e02022-01-14 18:44:281065#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151066bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151067 if (offset == 0)
1068 return true;
1069 int increment = offset > 0 ? 1 : -1;
1070 int non_skippable_entries = 0;
1071 for (int index = GetIndexForOffset(increment);
1072 index >= 0 && index < GetEntryCount(); index += increment) {
1073 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1074 non_skippable_entries++;
1075
1076 if (non_skippable_entries == std::abs(offset))
1077 return true;
1078 }
1079 return false;
1080}
1081#endif
1082
[email protected]d202a7c2012-01-04 07:53:471083void NavigationControllerImpl::GoBack() {
shivanisha55201872018-12-13 04:29:061084 int target_index = GetIndexForOffset(-1);
1085
Elly Fong-Jones40ee8112021-06-23 19:10:521086 // Move the target index past the skippable entries.
Shivani Sharma298d12852019-01-22 20:04:031087 bool all_skippable_entries = true;
Elly Fong-Jones40ee8112021-06-23 19:10:521088 while (target_index >= 0) {
1089 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui()) {
Shivani Sharma298d12852019-01-22 20:04:031090 all_skippable_entries = false;
shivanisha55201872018-12-13 04:29:061091 break;
Shivani Sharma2d5b4b6b2019-01-08 16:07:161092 }
Elly Fong-Jones40ee8112021-06-23 19:10:521093 target_index--;
shivanisha55201872018-12-13 04:29:061094 }
Miyoung Shin1c565c912021-03-17 12:11:211095
Shivani Sharma298d12852019-01-22 20:04:031096 // Do nothing if all entries are skippable. Normally this path would not
1097 // happen as consumers would have already checked it in CanGoBack but a lot of
1098 // tests do not do that.
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421099 if (all_skippable_entries)
Shivani Sharma298d12852019-01-22 20:04:031100 return;
shivanisha55201872018-12-13 04:29:061101
shivanisha55201872018-12-13 04:29:061102 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201103}
1104
[email protected]d202a7c2012-01-04 07:53:471105void NavigationControllerImpl::GoForward() {
shivanisha55201872018-12-13 04:29:061106 int target_index = GetIndexForOffset(1);
1107
Shivani Sharma2d5b4b6b2019-01-08 16:07:161108 // Note that at least one entry (the last one) will be non-skippable since
1109 // entries are marked skippable only when they add another entry because of
1110 // redirect or pushState.
Elly Fong-Jones40ee8112021-06-23 19:10:521111 while (target_index < static_cast<int>(entries_.size())) {
1112 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui())
shivanisha55201872018-12-13 04:29:061113 break;
Elly Fong-Jones40ee8112021-06-23 19:10:521114 target_index++;
shivanisha55201872018-12-13 04:29:061115 }
shivanisha55201872018-12-13 04:29:061116 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201117}
1118
[email protected]d202a7c2012-01-04 07:53:471119void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131120 GoToIndex(index, /*initiator_rfh=*/nullptr,
1121 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
1122 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161123}
1124
Nate Chapinbf682fa32022-09-26 22:41:201125void NavigationControllerImpl::GoToIndex(
1126 int index,
1127 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131128 absl::optional<blink::scheduler::TaskAttributionId>
1129 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201130 const std::string* navigation_api_key) {
Rakina Zata Amnid605d462022-06-01 10:17:031131 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
sunjian30574a62017-03-21 21:39:441132 TRACE_EVENT0("browser,navigation,benchmark",
1133 "NavigationControllerImpl::GoToIndex");
[email protected]765b35502008-08-21 00:51:201134 if (index < 0 || index >= static_cast<int>(entries_.size())) {
Rakina Zata Amni4595c36a2023-02-01 03:51:181135 // We've seen reports of this NOTREACHED being hit on Android WebView, where
1136 // we won't get the log message below. The following code ensures that
1137 // `index` and `entries_size` will show up on the minidump for that case.
1138 base::debug::Alias(&index);
1139 const size_t entries_size = entries_.size();
1140 base::debug::Alias(&entries_size);
1141 NOTREACHED() << "Index " << index
1142 << " is out of bounds, entries_.size() is " << entries_size;
[email protected]765b35502008-08-21 00:51:201143 return;
1144 }
1145
Rakina Zata Amnif297a802022-01-18 03:53:431146 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1147 // We should never navigate to an existing initial NavigationEntry that is
1148 // the initial NavigationEntry for the initial empty document that hasn't
1149 // been overridden by the synchronous about:blank commit, to preserve
1150 // legacy behavior where trying to reload when the main frame is on the
1151 // initial empty document won't result in a navigation. See also
1152 // https://crbug.com/1277414.
1153 return;
1154 }
1155
[email protected]cbab76d2008-10-13 22:42:471156 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201157
arthursonzogni5c4c202d2017-04-25 23:41:271158 DCHECK_EQ(nullptr, pending_entry_);
1159 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431160
arthursonzogni5c4c202d2017-04-25 23:41:271161 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201162 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271163 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1164 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201165 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131166 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201167 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201168}
1169
[email protected]d202a7c2012-01-04 07:53:471170void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121171 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031172 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201173 return;
1174
[email protected]9ba14052012-06-22 23:50:031175 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201176}
1177
Nate Chapinbf682fa32022-09-26 22:41:201178void NavigationControllerImpl::GoToOffsetFromRenderer(
1179 int offset,
Yoav Weiss8c573952022-11-17 17:35:131180 RenderFrameHostImpl* initiator_rfh,
1181 absl::optional<blink::scheduler::TaskAttributionId>
1182 soft_navigation_heuristics_task_id) {
Nate Chapin45f620582021-09-30 17:45:431183 // Note: This is actually reached in unit tests.
1184 if (!CanGoToOffset(offset))
1185 return;
1186
Nate Chapinbf682fa32022-09-26 22:41:201187 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131188 soft_navigation_heuristics_task_id,
1189 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431190}
1191
Xiaohan Wang7f8052e02022-01-14 18:44:281192#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151193void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1194 // Note: This is actually reached in unit tests.
1195 if (!CanGoToOffsetWithSkipping(offset))
1196 return;
1197
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421198 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151199 GoToIndex(GetIndexForOffset(offset));
1200 return;
1201 }
1202 int increment = offset > 0 ? 1 : -1;
1203 // Find the offset without counting skippable entries.
1204 int target_index = GetIndexForOffset(increment);
1205 int non_skippable_entries = 0;
1206 for (int index = target_index; index >= 0 && index < GetEntryCount();
1207 index += increment) {
1208 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1209 non_skippable_entries++;
1210
1211 if (non_skippable_entries == std::abs(offset)) {
1212 target_index = index;
1213 break;
1214 }
1215 }
1216
1217 GoToIndex(target_index);
1218}
1219#endif
1220
[email protected]41374f12013-07-24 02:49:281221bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151222 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281223 return false;
[email protected]6a13a6c2011-12-20 21:47:121224
[email protected]43032342011-03-21 14:10:311225 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281226 return true;
[email protected]cbab76d2008-10-13 22:42:471227}
1228
Michael Thiessen9b14d512019-09-23 21:19:471229void NavigationControllerImpl::PruneForwardEntries() {
1230 DiscardNonCommittedEntries();
1231 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471232 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471233 if (num_removed <= 0)
1234 return;
Nate Chapin9eb16be72022-09-23 22:54:311235 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471236 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1237 NotifyPrunedEntries(this, remove_start_index /* start index */,
1238 num_removed /* count */);
1239}
1240
Aran Gilman37d11632019-10-08 23:07:151241void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1242 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321243 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311244 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511245 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1246 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321247 }
1248}
1249
Harkiran Bolariaba823e42021-05-21 18:30:361250base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1251 const GURL& url,
1252 const Referrer& referrer,
1253 ui::PageTransition transition,
1254 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471255 LoadURLParams params(url);
1256 params.referrer = referrer;
1257 params.transition_type = transition;
1258 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361259 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471260}
1261
Harkiran Bolariaba823e42021-05-21 18:30:361262base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1263 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061264 if (params.is_renderer_initiated)
1265 DCHECK(params.initiator_origin.has_value());
1266
naskob8744d22014-08-28 17:07:431267 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151268 "NavigationControllerImpl::LoadURLWithParams", "url",
1269 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291270 bool is_explicit_navigation =
1271 GetContentClient()->browser()->IsExplicitNavigation(
1272 params.transition_type);
1273 if (HandleDebugURL(params.url, params.transition_type,
1274 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431275 // If Telemetry is running, allow the URL load to proceed as if it's
1276 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491277 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431278 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361279 return nullptr;
[email protected]47752982014-07-29 08:01:431280 }
[email protected]8bf1048012012-02-08 01:22:181281
[email protected]cf002332012-08-14 19:17:471282 // Checks based on params.load_type.
1283 switch (params.load_type) {
1284 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431285 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471286 break;
1287 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261288 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471289 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361290 return nullptr;
[email protected]cf002332012-08-14 19:17:471291 }
1292 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461293 }
[email protected]e47ae9472011-10-13 19:48:341294
[email protected]e47ae9472011-10-13 19:48:341295 // The user initiated a load, we don't need to reload anymore.
1296 needs_reload_ = false;
1297
Harkiran Bolariaba823e42021-05-21 18:30:361298 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441299}
1300
Mohamed Abdelhalim833de902019-09-16 17:41:451301bool NavigationControllerImpl::PendingEntryMatchesRequest(
1302 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191303 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451304 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191305}
1306
[email protected]d202a7c2012-01-04 07:53:471307bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321308 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071309 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331310 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441311 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251312 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471313 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131314 NavigationRequest* navigation_request) {
1315 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331316
1317 // Note: validation checks and renderer kills due to invalid commit messages
1318 // must happen before getting here, in
1319 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1320 // effects of the navigation have already occurred.
1321
[email protected]cd2e15742013-03-08 04:08:311322 is_initial_navigation_ = false;
1323
Wang Hui96ab1012022-10-11 02:05:491324 // Any pending request to repost a form submission is no longer valid, since a
1325 // different NavigationEntry is committing.
1326 pending_reload_ = ReloadType::NONE;
1327
[email protected]0e8db942008-09-24 21:21:481328 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431329 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451330 if (entry_replaced_by_post_commit_error_) {
1331 // Same document navigation events with a post-commit error should already
1332 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1333 // reaching here.
1334 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331335
Rakina Zata Amnie2d31312022-11-18 03:38:451336 // Any commit while a post-commit error page is showing should put the
1337 // original entry back, replacing the error page's entry. This includes
1338 // reloads, where the original entry was used as the pending entry and
1339 // should now be at the correct index at commit time.
1340 entries_[last_committed_entry_index_] =
1341 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481342 }
Rakina Zata Amnie2d31312022-11-18 03:38:451343 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1344 details->previous_entry_index = GetLastCommittedEntryIndex();
1345 if (PendingEntryMatchesRequest(navigation_request) &&
1346 pending_entry_->GetIsOverridingUserAgent() !=
1347 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1348 overriding_user_agent_changed = true;
1349 }
1350#if BUILDFLAG(IS_ANDROID)
1351 // TODO(crbug.com/1266277): Clean up the logic of setting
1352 // |overriding_user_agent_changed| post-launch.
1353 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1354 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
1355 // Must honor user agent overrides in the |navigation_request|, such as
1356 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1357 // result, besides comparing |pending_entry_|'s user agent against
1358 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1359 // agent against LastCommittedEntry's.
1360 if (navigation_request->is_overriding_user_agent() !=
1361 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1362 overriding_user_agent_changed = true;
1363 }
1364 }
1365#endif // BUILDFLAG(IS_ANDROID)
[email protected]ecd9d8702008-08-28 22:10:171366
Dave Tapuskaa2ab4f252021-07-08 21:31:281367 bool is_main_frame_navigation = !rfh->GetParent();
1368
Alexander Timind2f2e4f22019-04-02 20:04:531369 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1370 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281371 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141372 // BackForwardCacheMetrics to be associated with the new navigation's
1373 // NavigationEntry, by either creating a new object or reusing the previous
1374 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281375 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Arthur Sonzognif6785ec2022-12-05 10:11:501376 if (navigation_request->frame_tree_node()->frame_tree().type() ==
Dave Tapuskaa2ab4f252021-07-08 21:31:281377 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141378 back_forward_cache_metrics = BackForwardCacheMetrics::
1379 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281380 GetLastCommittedEntry(), is_main_frame_navigation,
1381 params.document_sequence_number);
1382 }
Yuzu Saijo29f96ca92022-12-08 04:54:121383
Alexander Timind2f2e4f22019-04-02 20:04:531384 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281385 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451386 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1387 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531388 }
1389 }
1390
Rakina Zata Amnifd8370b2022-11-14 13:32:251391 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1392 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091393 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251394 details->did_replace_entry =
1395 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091396
fdegans9caf66a2015-07-30 21:10:421397 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111398 // except for restored entries. This should be true even if the current commit
1399 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291400 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481401 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081402 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111403
1404 // Only make changes based on the pending entry if the NavigationRequest
1405 // matches it. Otherwise, the pending entry may be for a different request
1406 // (e.g., if a slow history navigation is pending while an auto-subframe
1407 // commit occurs).
1408 if (PendingEntryMatchesRequest(navigation_request)) {
1409 // It is no longer necessary to consider the pending entry as restored.
1410 if (pending_entry_->IsRestored()) {
1411 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1412 was_restored = true;
1413 }
[email protected]e9ba4472008-09-14 15:42:431414
Charlie Reisf8cde712022-10-20 16:25:091415 // If the SiteInstance has changed from the matching pending entry, this
1416 // must be treated as a new navigation with replacement. Set the replacement
1417 // bit here and ClassifyNavigation will identify this case and return
1418 // NEW_ENTRY.
1419 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1420 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1421 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251422 // TODO(nasko,creis,rakina): Move this to happen before committing the
1423 // navigation. This is a bit complicated because we don't currently
1424 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091425 details->did_replace_entry = true;
1426 }
Nasko Oskovaee2f862018-06-15 00:05:521427 }
[email protected]bcd904482012-02-01 01:54:221428
[email protected]e9ba4472008-09-14 15:42:431429 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101430 NavigationType navigation_type =
1431 ClassifyNavigation(rfh, params, navigation_request);
1432 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451433
Rakina Zata Amnie2d31312022-11-18 03:38:451434 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451435 // Ensure that this navigation does not add a navigation entry, since
1436 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1437 // beyond the last committed one. Therefore, `should_replace_current_entry`
1438 // should be set, which replaces the current entry, or this should be a
1439 // reload, which does not create a new entry.
1440 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1441 // navigation that is restored will not be creating a new entry anyways, so
1442 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1443 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1444 // pointed out in the issue.
Rakina Zata Amnifd8370b2022-11-14 13:32:251445 DCHECK(navigation_request->common_params().should_replace_current_entry ||
shivanigithub189833f2022-04-27 18:08:451446 navigation_request->GetReloadType() != ReloadType::NONE ||
Miyoung Shin3299cbf2022-11-22 01:41:101447 navigation_type == NAVIGATION_TYPE_AUTO_SUBFRAME);
shivanigithub189833f2022-04-27 18:08:451448 }
1449
Rakina Zata Amnie2d31312022-11-18 03:38:451450 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551451 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241452 // This is a subframe navigation on the initial empty document, which used
1453 // to not have a NavigationEntry to attach to. Now it can attach to the
1454 // initial NavigationEntry, and we must ensure that its NavigationEntry
1455 // will keep the "initial NavigationEntry" status and won't append a new
1456 // NavigationEntry (it should always do replacement instead).
1457 // See also https://crbug.com/1277414.
1458 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551459 // Subframe navigation on initial NavigationEntry must not append a new
1460 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1461 // means every subframe navigation that happens while we're on the initial
1462 // NavigationEntry will always reuse the existing NavigationEntry and
1463 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101464 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1465 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551466 // This is a navigation that modifies the initial NavigationEntry, either
1467 // for a replacement or a reload. The initial NavigationEntry should
1468 // retain its "initial NavigationEntry" status in this case.
1469 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241470 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251471 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1472 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241473 // This is a synchronous about:blank navigation on the main frame, which
1474 // used to not create a NavigationEntry when we have no NavigationEntry on
1475 // FrameTree creation. We now have the initial NavigationEntry and are on
1476 // the initial NavigationEntry. To preserve old behavior, we should still
1477 // keep the "initial" status for the new NavigationEntry that we will
1478 // create for this navigation, so that subframe navigations under the
1479 // synchronously committed about:blank document will never append new
1480 // NavigationEntry, and instead will just reuse the initial
1481 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1482 // See also https://crbug.com/1277414.
1483 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551484 }
1485 }
1486 DCHECK(!details->should_stay_as_initial_entry ||
1487 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201488
eugenebutee08663a2017-04-27 17:43:121489 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441490 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121491
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071492 details->is_prerender_activation =
1493 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241494 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1495 ->GetOutermostMainFrame()
1496 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071497
Peter Boströmd7592132019-01-30 04:50:311498 // Make sure we do not discard the pending entry for a different ongoing
1499 // navigation when a same document commit comes in unexpectedly from the
1500 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1501 // other navigation types. See https://crbug.com/900036.
1502 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061503 bool keep_pending_entry =
1504 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101505 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061506 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311507
Miyoung Shin3299cbf2022-11-22 01:41:101508 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061509 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491510 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051511 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001512 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431513 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061514 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491515 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1516 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001517 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431518 break;
[email protected]8ff00d72012-10-23 19:12:211519 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471520 RendererDidNavigateNewSubframe(
1521 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001522 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431523 break;
[email protected]8ff00d72012-10-23 19:12:211524 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391525 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251526 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001527 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081528 // We don't send a notification about auto-subframe PageState during
1529 // UpdateStateForFrame, since it looks like nothing has changed. Send
1530 // it here at commit time instead.
1531 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431532 return false;
creis59d5a47cb2016-08-24 23:57:191533 }
[email protected]e9ba4472008-09-14 15:42:431534 break;
Aran Gilman37d11632019-10-08 23:07:151535 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431536 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151537 break;
[email protected]765b35502008-08-21 00:51:201538 }
1539
[email protected]688aa65c62012-09-28 04:32:221540 // At this point, we know that the navigation has just completed, so
1541 // record the time.
1542 //
1543 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261544 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331545 base::Time timestamp =
1546 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1547 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131548 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221549
Peter Boströmd7592132019-01-30 04:50:311550 // If we aren't keeping the pending entry, there shouldn't be one at this
1551 // point. Clear it again in case any error cases above forgot to do so.
1552 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1553 // been cleared instead of protecting against it.
1554 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551555 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141556
[email protected]e9ba4472008-09-14 15:42:431557 // All committed entries should have nonempty content state so WebKit doesn't
1558 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471559 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321560 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221561 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441562 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141563
Alexander Timind2f2e4f22019-04-02 20:04:531564 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1565 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281566 if (back_forward_cache_metrics &&
1567 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531568 active_entry->set_back_forward_cache_metrics(
1569 std::move(back_forward_cache_metrics));
1570 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281571
1572 // `back_forward_cache_metrics()` may return null as we do not record
1573 // back-forward cache metrics for navigations in non-primary frame trees.
1574 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141575 // TODO(https://crbug.com/1338089): Remove this.
1576 // These are both only available from details at this point, so we capture
1577 // them here.
1578 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101579 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141580 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1581 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281582 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1583 navigation_request,
1584 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1585 }
naskoc7533512016-05-06 17:01:121586
Charles Reisc0507202017-09-21 00:40:021587 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1588 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1589 // A mismatch can occur if the renderer lies or due to a unique name collision
1590 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121591 FrameNavigationEntry* frame_entry =
1592 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021593 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1594 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031595 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081596 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1597 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031598 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201599
1600 // Remember the bindings the renderer process has at this point, so that
1601 // we do not grant this entry additional bindings if we come back to it.
1602 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301603 }
[email protected]132e281a2012-07-31 18:32:441604
[email protected]97d8f0d2013-10-29 16:49:211605 // Once it is committed, we no longer need to track several pieces of state on
1606 // the entry.
naskoc7533512016-05-06 17:01:121607 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131608
[email protected]49bd30e62011-03-22 20:12:591609 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221610 // TODO(creis): This check won't pass for subframes until we create entries
1611 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001612 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421613 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591614
[email protected]e9ba4472008-09-14 15:42:431615 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001616 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001617 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311618 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531619
arthursonzogni7ddc6542021-04-09 09:16:501620 active_entry->SetIsOverridingUserAgent(
1621 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031622
[email protected]93f230e02011-06-01 14:40:001623 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291624
aelias100c9192017-01-13 00:01:431625 if (overriding_user_agent_changed)
1626 delegate_->UpdateOverridingUserAgent();
1627
creis03b48002015-11-04 00:54:561628 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1629 // one knows the latest NavigationEntry it is showing (whether it has
1630 // committed anything in this navigation or not). This allows things like
1631 // state and title updates from RenderFrames to apply to the latest relevant
1632 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381633 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031634 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381635 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431636
1637 if (navigation_request->IsPrerenderedPageActivation()) {
1638 BroadcastHistoryOffsetAndLength();
1639 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1640 // is activated. As a result, a "prerenderingchange" event listener sees the
1641 // history.length which is not updated yet. We should guarantee that
1642 // history's length and offset should be updated before a
1643 // "prerenderingchange" event listener runs. One possible approach is to use
1644 // the same IPC which "prerenderingchange" uses, and propagate history's
1645 // length and offset together with that.
1646 }
1647
[email protected]e9ba4472008-09-14 15:42:431648 return true;
initial.commit09911bf2008-07-26 23:55:291649}
1650
[email protected]8ff00d72012-10-23 19:12:211651NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321652 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101653 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241654 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591655 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511656 "ClassifyNavigation");
1657
avi7c6f35e2015-05-08 17:52:381658 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241659 // A new entry. We may or may not have a corresponding pending entry, and
1660 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001661 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491662 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061663 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381664 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241665 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511666 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381667 return NAVIGATION_TYPE_NEW_SUBFRAME;
1668 }
1669
Charlie Reisc0f17d2d2021-01-12 18:52:491670 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381671 DCHECK(!params.history_list_was_cleared);
1672
avi39c1edd32015-06-04 20:06:001673 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381674 // All manual subframes would be did_create_new_entry and handled above, so
1675 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081676 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1677 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381678 }
1679
Rakina Zata Amnif6950d552020-11-24 03:26:101680 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1681 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381682 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1683 // create a new page.
1684
Hayato Ito2ae49442021-07-02 02:59:251685 // This main frame navigation is not a history navigation (since
1686 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1687 // reload or a replacement navigation, which will modify the existing entry.
1688 //
Nasko Oskov332593c2018-08-16 17:21:341689 // TODO(nasko): With error page isolation, reloading an existing session
1690 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491691 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341692 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511693 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491694 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061695 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381696 }
1697
Charlie Reisf8cde712022-10-20 16:25:091698 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521699 // If the SiteInstance of the |pending_entry_| does not match the
1700 // SiteInstance that got committed, treat this as a new navigation with
1701 // replacement. This can happen if back/forward/reload encounters a server
1702 // redirect to a different site or an isolated error page gets successfully
1703 // reloaded into a different SiteInstance.
1704 if (pending_entry_->site_instance() &&
1705 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491706 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061707 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521708 }
creis77c9aa32015-09-25 19:59:421709
Nasko Oskovaee2f862018-06-15 00:05:521710 if (pending_entry_index_ == -1) {
1711 // In this case, we have a pending entry for a load of a new URL but Blink
1712 // didn't do a new navigation (params.did_create_new_entry). First check
1713 // to make sure Blink didn't treat a new cross-process navigation as
1714 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161715 // we must treat it as NEW rather than the converted reload case below,
1716 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451717 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161718 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061719 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521720 }
1721
1722 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161723 // We will create a pending entry, but NavigateWithoutEntry will convert
1724 // it to a reload since it's the same page and not create a new entry for
1725 // it. (The user doesn't want to have a new back/forward entry when they
1726 // do this.) Therefore we want to just ignore the pending entry and go
1727 // back to where we were (the "existing entry").
1728 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061729 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521730 }
avi7c6f35e2015-05-08 17:52:381731 }
1732
Rakina Zata Amni153d5702021-09-13 22:48:001733 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381734 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491735 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1736 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161737 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061738 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381739 }
1740
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121741 if (navigation_request->DidEncounterError() &&
1742 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101743 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381744 // If the renderer was going to a new pending entry that got cleared because
1745 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491746 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381747 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511748 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491749 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061750 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381751 }
1752
Charlie Reisc0f17d2d2021-01-12 18:52:491753 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101754 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511755 trace_return.traced_value()->SetInteger("existing_entry_index",
1756 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381757 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441758 // The renderer has committed a navigation to an entry that no longer
1759 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491760 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061761 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381762 }
1763
avi7c6f35e2015-05-08 17:52:381764 // Since we weeded out "new" navigations above, we know this is an existing
1765 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491766 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061767 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381768}
1769
Rakina Zata Amni3460d382021-10-29 00:43:371770void NavigationControllerImpl::UpdateNavigationEntryDetails(
1771 NavigationEntryImpl* entry,
1772 RenderFrameHostImpl* rfh,
1773 const mojom::DidCommitProvisionalLoadParams& params,
1774 NavigationRequest* request,
1775 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001776 bool is_new_entry,
1777 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371778 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171779 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371780 entry->AddOrUpdateFrameEntry(
1781 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571782 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371783 rfh->GetSiteInstance(), nullptr, params.url,
1784 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171785 Referrer(*params.referrer),
1786 request ? request->common_params().initiator_origin : params.origin,
W. James MacLean23e90a12022-12-21 04:38:211787 request ? request->common_params().initiator_base_url : absl::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171788 request ? request->GetRedirectChain() : redirects, params.page_state,
1789 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amniafd3c6582021-11-30 06:19:171790 (request ? request->GetSubresourceWebBundleNavigationInfo() : nullptr),
Rakina Zata Amni3460d382021-10-29 00:43:371791 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171792 rfh, request && request->IsSameDocument(),
1793 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371794
1795 if (rfh->GetParent()) {
1796 // Only modify the NavigationEntry for main frame navigations.
1797 return;
1798 }
1799 if (entry->update_virtual_url_with_url())
1800 UpdateVirtualURLToURL(entry, params.url);
1801 // Don't use the page type from the pending entry. Some interstitial page
1802 // may have set the type to interstitial. Once we commit, however, the page
1803 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171804 entry->set_page_type((request && request->DidEncounterError())
1805 ? PAGE_TYPE_ERROR
1806 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431807 if (commit_details && commit_details->should_stay_as_initial_entry) {
1808 // Retain the "initial NavigationEntry" status.
1809 if (request->IsSameDocument()) {
1810 // If this is for a same-document navigation, the NavigationEntry must be
1811 // reused and should already be marked as the initial NavigationEntry.
1812 DCHECK(entry->IsInitialEntry());
1813 } else {
1814 // If this is for a cross-document navigation, it can be caused by a
1815 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1816 // "for synchronous about:blank" in the latter case, and also when it is
1817 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1818 // is not for a synchronous about:blank commit.
1819 NavigationEntryImpl::InitialNavigationEntryState new_state =
1820 NavigationEntryImpl::InitialNavigationEntryState::
1821 kInitialNotForSynchronousAboutBlank;
1822 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1823 request->is_synchronous_renderer_commit()) {
1824 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1825 kInitialForSynchronousAboutBlank;
1826 }
1827 entry->set_initial_navigation_entry_state(new_state);
1828 }
1829 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1830 // Remove the "initial NavigationEntry" status.
1831 entry->set_initial_navigation_entry_state(
1832 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001833 }
Rakina Zata Amniddf10502022-01-15 02:56:551834
Rakina Zata Amni3460d382021-10-29 00:43:371835 if (is_new_entry) {
1836 // Some properties of the NavigationEntry are only set when the entry is
1837 // new (we aren't reusing it).
1838 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171839 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1840 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371841 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1842 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1843 } else {
1844 // We are reusing the NavigationEntry. The site instance will normally be
1845 // the same except for a few cases:
1846 // 1) session restore, when no site instance will be assigned or
1847 // 2) redirect, when the site instance is reset.
1848 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1849 entry->site_instance() == rfh->GetSiteInstance());
1850 }
1851}
1852
Rakina Zata Amniafd3c6582021-11-30 06:19:171853void NavigationControllerImpl::CreateInitialEntry() {
1854 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031855 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171856 auto params = mojom::DidCommitProvisionalLoadParams::New();
1857 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1858 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1859 // before we have initial NavigationEntries.
1860 params->url = GURL::EmptyGURL();
1861 params->http_status_code = 0;
1862 params->url_is_unreachable = false;
1863 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171864 params->post_id = -1;
1865 params->embedding_token = base::UnguessableToken::Create();
1866 params->navigation_token = base::UnguessableToken::Create();
1867 params->did_create_new_entry = true;
1868 params->origin = rfh->GetLastCommittedOrigin();
1869 params->should_update_history = true;
1870 params->item_sequence_number = 0;
1871 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151872 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171873 params->transition = is_in_fenced_frame_tree
1874 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1875 : ui::PAGE_TRANSITION_LINK;
1876 params->referrer = blink::mojom::Referrer::New();
1877
1878 // Create and insert the initial NavigationEntry.
1879 auto new_entry = std::make_unique<NavigationEntryImpl>(
1880 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381881 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211882 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1883 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1884 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171885 UpdateNavigationEntryDetails(
1886 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001887 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1888 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171889
1890 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1891 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001892 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171893}
1894
Charlie Reisc0f17d2d2021-01-12 18:52:491895void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321896 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071897 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361898 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441899 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471900 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001901 NavigationRequest* request,
1902 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571903 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071904 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451905 request->common_params().initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:211906 const absl::optional<GURL>& initiator_base_url =
1907 request->common_params().initiator_base_url;
Lukasz Anforowicz435bcb582019-07-12 20:50:061908
creisf49dfc92016-07-26 17:05:181909 // First check if this is an in-page navigation. If so, clone the current
1910 // entry instead of looking at the pending entry, because the pending entry
1911 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451912 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301913 FrameNavigationEntry* previous_frame_entry =
1914 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451915 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481916 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571917 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:081918 rfh->GetSiteInstance(), nullptr, params.url,
1919 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:211920 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:091921 request->GetRedirectChain(), params.page_state, params.method,
1922 params.post_id, nullptr /* blob_url_loader_factory */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:481923 request->GetSubresourceWebBundleNavigationInfo(),
Antonio Sartori78a749f2020-11-30 12:03:391924 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301925 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:571926 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:301927 // FrameNavigationEntry.
1928 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:571929 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:031930
creisf49dfc92016-07-26 17:05:181931 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:031932 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:521933 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1934 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571935 // TODO(jam): we had one report of this with a URL that was redirecting to
1936 // only tildes. Until we understand that better, don't copy the cert in
1937 // this case.
1938 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571939 }
creisf49dfc92016-07-26 17:05:181940
Patrick Monette50e8bd82019-06-13 22:40:451941 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1942 // that |frame_entry| should now have a reference count of exactly 2: one
1943 // due to the local variable |frame_entry|, and another due to |new_entry|
1944 // also retaining one. This should never fail, because it's the main frame.
1945 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181946 }
1947
Harkiran Bolaria59290d62021-03-17 01:53:011948 // If this is an activation navigation from a prerendered page, transfer the
1949 // new entry from an entry already created and stored in the
1950 // NavigationRequest. |new_entry| will not have been set prior to this as
1951 // |is_same_document| is mutually exclusive with
1952 // |IsPrerenderedPageActivation|.
1953 if (request->IsPrerenderedPageActivation()) {
1954 DCHECK(!is_same_document);
1955 DCHECK(!new_entry);
1956 new_entry = request->TakePrerenderNavigationEntry();
1957 DCHECK(new_entry);
1958 }
1959
Charlie Reisc0f17d2d2021-01-12 18:52:491960 // Only make a copy of the pending entry if it is appropriate for the new
1961 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451962 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041963 // 1. The SiteInstance hasn't been assigned to something else.
1964 // 2. The pending entry was intended as a new entry, rather than being a
1965 // history navigation that was interrupted by an unrelated,
1966 // renderer-initiated navigation.
1967 // TODO(csharrison): Investigate whether we can remove some of the coarser
1968 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451969 if (!new_entry && PendingEntryMatchesRequest(request) &&
1970 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:341971 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:431972 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:351973 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:431974
Camille Lamy62b826012019-02-26 09:15:471975 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451976 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:181977 }
1978
Charlie Reisc0f17d2d2021-01-12 18:52:491979 // For cross-document commits with no matching pending entry, create a new
1980 // entry.
creisf49dfc92016-07-26 17:05:181981 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061982 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:071983 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:211984 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:581985 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:451986 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:171987 nullptr, // blob_url_loader_factory
1988 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:241989
1990 // Find out whether the new entry needs to update its virtual URL on URL
1991 // change and set up the entry accordingly. This is needed to correctly
1992 // update the virtual URL when replaceState is called after a pushState.
1993 GURL url = params.url;
1994 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:491995 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:411996 // update the virtual URL based on the new URL. For example, this is needed
1997 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1998 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:371999 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2000 &url, browser_context_, &needs_update);
2001 new_entry->set_update_virtual_url_with_url(needs_update);
2002
Camille Lamy62b826012019-02-26 09:15:472003 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452004 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432005 }
2006
Harkiran Bolaria59290d62021-03-17 01:53:012007 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
2008 // for prerendered contents, if any. This is because prerendering/activation
2009 // technically won't be creating a new document. Unlike BFCache, prerendering
2010 // creates a new NavigationEntry rather than using an existing one.
2011 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372012 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2013 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002014 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082015
Harkiran Bolaria59290d62021-03-17 01:53:012016 // history.pushState() is classified as a navigation to a new page, but sets
2017 // is_same_document to true. In this case, we already have the title and
2018 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452019 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012020 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2021 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2022 }
[email protected]3a868f212014-08-09 10:41:192023 }
[email protected]ff64b3e2014-05-31 04:07:332024
[email protected]60d6cca2013-04-30 08:47:132025 DCHECK(!params.history_list_was_cleared || !replace_entry);
2026 // The browser requested to clear the session history when it initiated the
2027 // navigation. Now we know that the renderer has updated its state accordingly
2028 // and it is safe to also clear the browser side history.
2029 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552030 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132031 entries_.clear();
2032 last_committed_entry_index_ = -1;
2033 }
2034
Nasko Oskovaee2f862018-06-15 00:05:522035 // If this is a new navigation with replacement and there is a
2036 // pending_entry_ which matches the navigation reported by the renderer
2037 // process, then it should be the one replaced, so update the
2038 // last_committed_entry_index_ to use it.
2039 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092040 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522041 last_committed_entry_index_ = pending_entry_index_;
2042 }
2043
Alexander Timine3ec4192020-04-20 16:39:402044 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412045 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402046 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052047
Yuzu Saijoa725585f2022-11-28 04:14:032048 // If this is a history navigation and the old entry has an existing
2049 // back/forward cache metrics object, keep using the old one so that the
2050 // reasons logged from the last time the page navigated gets preserved.
2051 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2052 request)) {
2053 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2054 // because some tests do not have a pending entry.
2055 NavigationEntryImpl* entry =
2056 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2057 if (entry && entry->back_forward_cache_metrics()) {
2058 scoped_refptr<BackForwardCacheMetrics> metrics =
2059 entry->TakeBackForwardCacheMetrics();
2060 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2061 }
2062 }
2063
Carlos IL42b416592019-10-07 23:10:362064 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312065 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152066 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432067}
2068
Charlie Reisc0f17d2d2021-01-12 18:52:492069void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322070 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072071 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362072 bool is_same_document,
jam48cea9082017-02-15 06:13:292073 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452074 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002075 bool keep_pending_entry,
2076 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562077 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2078 << "that a last committed entry exists.";
2079
[email protected]e9ba4472008-09-14 15:42:432080 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002081 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432082
Charlie Reis7e2cb6d2021-01-26 01:27:162083 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002084 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162085 // We're guaranteed to have a last committed entry if intended_as_new_entry
2086 // is true.
avicbdc4c12015-07-01 16:07:112087 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162088
2089 // If the NavigationRequest matches a new pending entry and is classified as
2090 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2091 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092092 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162093 // Note: The pending entry will usually have a real ReloadType here, but
2094 // it can still be ReloadType::NONE in cases that
2095 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2096
2097 // If we classified this correctly, the SiteInstance should not have
2098 // changed.
2099 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2100
2101 // For converted reloads, we assign the entry's unique ID to be that of
2102 // the new one. Since this is always the result of a user action, we want
2103 // to dismiss infobars, etc. like a regular user-initiated navigation.
2104 entry->set_unique_id(pending_entry_->GetUniqueID());
2105
2106 // The extra headers may have changed due to reloading with different
2107 // headers.
2108 entry->set_extra_headers(pending_entry_->extra_headers());
2109 }
2110 // Otherwise, this was intended as a new entry but the pending entry was
2111 // lost in the meantime and no new entry was created. We are stuck at the
2112 // last committed entry.
2113
2114 // Even if this is a converted reload from pressing enter in the omnibox,
2115 // the server could redirect, requiring an update to the SSL status. If this
2116 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452117 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162118 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472119 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452120 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162121 }
Rakina Zata Amnif6950d552020-11-24 03:26:102122 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112123 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102124 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b90ce2016-09-01 16:58:162125
eugenebut604866f2017-05-10 21:35:362126 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452127 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362128 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2129 // this was a restored same document navigation entry, then it won't have
2130 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2131 // navigated it.
jam48cea9082017-02-15 06:13:292132 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522133 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2134 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292135 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2136 was_restored) {
2137 entry->GetSSL() = last_entry->GetSSL();
2138 }
2139 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452140 // In rapid back/forward navigations |request| sometimes won't have a cert
2141 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192142 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452143 if (request->GetSSLInfo().has_value() &&
2144 request->GetSSLInfo()->is_valid()) {
2145 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522146 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2147 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192148 entry->GetSSL() = SSLStatus();
2149 }
jam48cea9082017-02-15 06:13:292150 }
avicbdc4c12015-07-01 16:07:112151 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272152 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572153 // navigations that are EXISTING_ENTRY are same-document navigations that
2154 // result in replacement (e.g. history.replaceState(), location.replace(),
2155 // forced replacements for trivial session history contexts). For these
2156 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112157 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102158
Mikel Astizba9cf2fd2017-12-17 10:38:102159 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2160 // to avoid misleading interpretations (e.g. URLs paired with
2161 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2162 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2163 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2164
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572165 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102166
eugenebut604866f2017-05-10 21:35:362167 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452168 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362169 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472170 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452171 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112172 }
2173 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432174
Rakina Zata Amni3460d382021-10-29 00:43:372175 UpdateNavigationEntryDetails(entry, rfh, params, request,
2176 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002177 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302178
[email protected]5ccd4dc2012-10-24 02:28:142179 // The redirected to page should not inherit the favicon from the previous
2180 // page.
eugenebut604866f2017-05-10 21:35:362181 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482182 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142183
Peter Boströmd7592132019-01-30 04:50:312184 // We should also usually discard the pending entry if it corresponds to a
2185 // different navigation, since that one is now likely canceled. In rare
2186 // cases, we leave the pending entry for another navigation in place when we
2187 // know it is still ongoing, to avoid a flicker in the omnibox (see
2188 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432189 //
2190 // Note that we need to use the "internal" version since we don't want to
2191 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312192 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002193 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392194
Carlos IL4dea8902020-05-26 15:14:292195 // Update the last committed index to reflect the committed entry.
avicbdc4c12015-07-01 16:07:112196 last_committed_entry_index_ = GetIndexOfEntry(entry);
[email protected]e9ba4472008-09-14 15:42:432197}
2198
[email protected]d202a7c2012-01-04 07:53:472199void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322200 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072201 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362202 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472203 bool replace_entry,
2204 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002205 NavigationRequest* request,
2206 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262207 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2208 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552209 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2210 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112211
[email protected]e9ba4472008-09-14 15:42:432212 // Manual subframe navigations just get the current entry cloned so the user
2213 // can go back or forward to it. The actual subframe information will be
2214 // stored in the page state for each of those entries. This happens out of
2215 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092216 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2217 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382218
Mikel Astizba9cf2fd2017-12-17 10:38:102219 // The DCHECK below documents the fact that we don't know of any situation
2220 // where |replace_entry| is true for subframe navigations. This simplifies
2221 // reasoning about the replacement struct for subframes (see
2222 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2223 DCHECK(!replace_entry);
2224
Patrick Monette50e8bd82019-06-13 22:40:452225 // This FrameNavigationEntry might not end up being used in the
2226 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072227 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452228 request->common_params().initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212229 const absl::optional<GURL>& initiator_base_url =
2230 request->common_params().initiator_base_url;
Nate Chapin63db0d12022-01-20 22:03:302231 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2232 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2233 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572234 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302235 if (is_same_document) {
2236 FrameNavigationEntry* previous_frame_entry =
2237 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572238 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302239 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572240 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302241 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572242 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302243 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572244 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302245 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572246 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302247 policy_container_policies->referrer_policy);
2248 }
2249
Patrick Monette50e8bd82019-06-13 22:40:452250 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482251 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572252 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082253 rfh->GetSiteInstance(), nullptr, params.url,
2254 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212255 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2256 request->GetRedirectChain(), params.page_state, params.method,
2257 params.post_id, nullptr /* blob_url_loader_factory */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482258 request->GetSubresourceWebBundleNavigationInfo(),
Domenic Denicolacc094fb2022-03-16 23:40:572259 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032260
creisce0ef3572017-01-26 17:53:082261 std::unique_ptr<NavigationEntryImpl> new_entry =
2262 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452263 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032264 frame_tree_->root());
creise062d542015-08-25 02:01:552265
Alexander Timine3ec4192020-04-20 16:39:402266 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412267 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402268 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472269
creisce0ef3572017-01-26 17:53:082270 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452271 // to replace, which can happen due to a unique name change. See
2272 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2273 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382274
Dave Tapuska87696ae2021-11-18 18:48:312275 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152276 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432277}
2278
[email protected]d202a7c2012-01-04 07:53:472279bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322280 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072281 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392282 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252283 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002284 NavigationRequest* request,
2285 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292286 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2287 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2288
[email protected]e9ba4472008-09-14 15:42:432289 // We're guaranteed to have a previously committed entry, and we now need to
2290 // handle navigation inside of a subframe in it without creating a new entry.
2291 DCHECK(GetLastCommittedEntry());
2292
creis913c63ce2016-07-16 19:52:522293 // For newly created subframes, we don't need to send a commit notification.
2294 // This is only necessary for history navigations in subframes.
2295 bool send_commit_notification = false;
2296
Rakina Zata Amnif6950d552020-11-24 03:26:102297 // If |nav_entry_id| is non-zero and matches an existing entry, this
2298 // is a history navigation. Update the last committed index accordingly. If
2299 // we don't recognize the |nav_entry_id|, it might be a recently
2300 // pruned entry. We'll handle it below.
2301 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2302 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472303 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062304 // Make sure that a subframe commit isn't changing the main frame's
2305 // origin. Otherwise the renderer process may be confused, leading to a
2306 // URL spoof. We can't check the path since that may change
2307 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572308 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2309 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242310 // We should use checks similar to RenderFrameHostImpl's
2311 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2312 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572313 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2314 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2315 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2316 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522317 current_top_url.DeprecatedGetOriginAsURL() !=
2318 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442319 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512320 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062321 }
creis3cdc3b02015-05-29 23:00:472322
creis913c63ce2016-07-16 19:52:522323 // We only need to discard the pending entry in this history navigation
2324 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062325 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002326 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522327
2328 // History navigations should send a commit notification.
2329 send_commit_notification = true;
avi98405c22015-05-21 20:47:062330 }
[email protected]e9ba4472008-09-14 15:42:432331 }
[email protected]f233e4232013-02-23 00:55:142332
creisce0ef3572017-01-26 17:53:082333 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2334 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372335 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2336 // exists), or we may want to clobber it and create a new one. We update in
2337 // cases where the corresponding FrameNavigationEntry is conceptually similar
2338 // to the document described by the commit params: same-document
2339 // navigations, history traversal to an existing entry, and reloads (including
2340 // a "soft reload" where we navigate to the same url without flagging it as a
2341 // reload). But in the case of a different document that is not logically
2342 // related to the committed FrameNavigationEntry's document (cross-document,
2343 // not same url, not a reload, not a history traversal), we replace rather
2344 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252345 //
Nate Chapin9f169072021-06-09 19:32:372346 // In the case where we update, the FrameNavigationEntry will potentially be
2347 // shared across multiple NavigationEntries, and any updates will be reflected
2348 // in all of those NavigationEntries. In the replace case, any existing
2349 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252350 //
2351 // When navigating away from the initial empty document, we also update rather
2352 // than replace. Either update or replace will overwrite the initial empty
2353 // document state for |last_committed|, but if the FrameNavigationEntry for
2354 // the initial empty document is shared across multiple NavigationEntries (due
2355 // to a navigation in another frame), we want to make sure we overwrite the
2356 // initial empty document state everywhere this FrameNavigationEntry is used,
2357 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452358 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372359 FrameNavigationEntry* last_committed_frame_entry =
2360 last_committed->GetFrameEntry(rfh->frame_tree_node());
2361 NavigationEntryImpl::UpdatePolicy update_policy =
2362 NavigationEntryImpl::UpdatePolicy::kUpdate;
2363 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312364 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372365 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252366 last_committed_frame_entry->url() != params.url &&
2367 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372368 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2369 }
2370
Rakina Zata Amni3460d382021-10-29 00:43:372371 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002372 update_policy, false /* is_new_entry */,
2373 commit_details);
creis625a0c7d2015-03-24 23:17:122374
creis913c63ce2016-07-16 19:52:522375 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432376}
2377
[email protected]d202a7c2012-01-04 07:53:472378int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232379 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032380 for (size_t i = 0; i < entries_.size(); ++i) {
2381 if (entries_[i].get() == entry)
2382 return i;
2383 }
2384 return -1;
[email protected]765b35502008-08-21 00:51:202385}
2386
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572387void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242388 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572389 NavigationControllerImpl* source =
2390 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572391 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382392 DCHECK_EQ(1, GetEntryCount());
2393 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472394 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172395 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572396
Francois Dorayeaace782017-06-21 16:37:242397 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442398 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572399 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572400
Fergal Dalya1d569972021-03-16 03:24:532401 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302402 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532403 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2404 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302405 }
[email protected]4e6419c2010-01-15 04:50:342406
Lukasz Anforowicz0de0f452020-12-02 19:57:152407 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572408}
2409
Aran Gilman37d11632019-10-08 23:07:152410void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2411 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162412 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012413 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162414
[email protected]d202a7c2012-01-04 07:53:472415 NavigationControllerImpl* source =
2416 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252417
avi2b177592014-12-10 02:08:022418 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012419 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252420
[email protected]474f8512013-05-31 22:31:162421 // We now have one entry, possibly with a new pending entry. Ensure that
2422 // adding the entries from source won't put us over the limit.
2423 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572424 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572425 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252426
Carlos IL4dea8902020-05-26 15:14:292427 // Insert the entries from source. Ignore any pending entry, since it has not
2428 // committed in source.
[email protected]474f8512013-05-31 22:31:162429 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172430 DCHECK_NE(max_source_index, -1);
2431 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572432
2433 // Ignore the source's current entry if merging with replacement.
2434 // TODO(davidben): This should preserve entries forward of the current
2435 // too. http://crbug.com/317872
2436 if (replace_entry && max_source_index > 0)
2437 max_source_index--;
2438
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572439 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252440
2441 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552442 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142443
Hayato Ito2c8c08d02021-06-23 03:38:432444 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252445}
2446
[email protected]79368982013-11-13 01:11:012447bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162448 // If there is no last committed entry, we cannot prune. Even if there is a
2449 // pending entry, it may not commit, leaving this WebContents blank, despite
2450 // possibly giving it new entries via CopyStateFromAndPrune.
2451 if (last_committed_entry_index_ == -1)
2452 return false;
[email protected]9350602e2013-02-26 23:27:442453
[email protected]474f8512013-05-31 22:31:162454 // We cannot prune if there is a pending entry at an existing entry index.
2455 // It may not commit, so we have to keep the last committed entry, and thus
2456 // there is no sensible place to keep the pending entry. It is ok to have
2457 // a new pending entry, which can optionally commit as a new navigation.
2458 if (pending_entry_index_ != -1)
2459 return false;
2460
[email protected]474f8512013-05-31 22:31:162461 return true;
2462}
2463
[email protected]79368982013-11-13 01:11:012464void NavigationControllerImpl::PruneAllButLastCommitted() {
2465 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162466
avi2b177592014-12-10 02:08:022467 DCHECK_EQ(0, last_committed_entry_index_);
2468 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442469
Hayato Ito2c8c08d02021-06-23 03:38:432470 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442471}
2472
[email protected]79368982013-11-13 01:11:012473void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162474 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012475 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262476
Nate Chapin9eb16be72022-09-23 22:54:312477 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2478
[email protected]474f8512013-05-31 22:31:162479 // Erase all entries but the last committed entry. There may still be a
2480 // new pending entry after this.
2481 entries_.erase(entries_.begin(),
2482 entries_.begin() + last_committed_entry_index_);
2483 entries_.erase(entries_.begin() + 1, entries_.end());
2484 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262485}
2486
Christian Dullweber1af31e62018-02-22 11:49:482487void NavigationControllerImpl::DeleteNavigationEntries(
2488 const DeletionPredicate& deletionPredicate) {
2489 // It is up to callers to check the invariants before calling this.
2490 CHECK(CanPruneAllButLastCommitted());
2491 std::vector<int> delete_indices;
2492 for (size_t i = 0; i < entries_.size(); i++) {
2493 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572494 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482495 delete_indices.push_back(i);
2496 }
2497 }
2498 if (delete_indices.empty())
2499 return;
2500
2501 if (delete_indices.size() == GetEntryCount() - 1U) {
2502 PruneAllButLastCommitted();
2503 } else {
2504 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382505 for (const auto& index : base::Reversed(delete_indices)) {
2506 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482507 }
Hayato Ito2c8c08d02021-06-23 03:38:432508 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482509 }
2510 delegate()->NotifyNavigationEntriesDeleted();
2511}
2512
Shivani Sharma883f5f32019-02-12 18:20:012513bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2514 auto* entry = GetEntryAtIndex(index);
2515 return entry && entry->should_skip_on_back_forward_ui();
2516}
2517
Carlos Caballero35ce710c2019-09-19 10:59:452518BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2519 return back_forward_cache_;
2520}
2521
clamy987a3752018-05-03 17:36:262522void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2523 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2524 // progress, since this will cause a use-after-free. (We only allow this
2525 // when the tab is being destroyed for shutdown, since it won't return to
2526 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032527 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262528
2529 if (was_failure && pending_entry_) {
2530 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2531 } else {
2532 failed_pending_entry_id_ = 0;
2533 }
2534
2535 if (pending_entry_) {
2536 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332537 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262538 pending_entry_index_ = -1;
2539 pending_entry_ = nullptr;
2540 }
arthursonzogni66f711c2019-10-08 14:40:362541
2542 // Ensure any refs to the current pending entry are ignored if they get
2543 // deleted, by clearing the set of known refs. All future pending entries will
2544 // only be affected by new refs.
2545 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262546}
2547
2548void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2549 if (pending_entry_)
2550 pending_entry_->set_ssl_error(error);
2551}
2552
Xiaohan Wang7f8052e02022-01-14 18:44:282553#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422554// static
2555bool NavigationControllerImpl::ValidateDataURLAsString(
2556 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2557 if (!data_url_as_string)
2558 return false;
2559
2560 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2561 return false;
2562
2563 // The number of characters that is enough for validating a data: URI.
2564 // From the GURL's POV, the only important part here is scheme, it doesn't
2565 // check the actual content. Thus we can take only the prefix of the url, to
2566 // avoid unneeded copying of a potentially long string.
2567 const size_t kDataUriPrefixMaxLen = 64;
2568 GURL data_url(
2569 std::string(data_url_as_string->front_as<char>(),
2570 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2571 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2572 return false;
2573
2574 return true;
2575}
2576#endif
2577
Shivani Sharma194877032019-03-07 17:52:472578void NavigationControllerImpl::NotifyUserActivation() {
2579 // When a user activation occurs, ensure that all adjacent entries for the
2580 // same document clear their skippable bit, so that the history manipulation
2581 // intervention does not apply to them.
shivanigithub99368382021-06-16 18:33:372582 if (base::FeatureList::IsEnabled(
2583 features::kDebugHistoryInterventionNoUserActivation)) {
2584 return;
2585 }
2586
Shivani Sharmac4cc8922019-04-18 03:11:172587 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472588}
2589
clamy987a3752018-05-03 17:36:262590bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2591 RenderFrameHostImpl* render_frame_host,
Julie Jeongeun Kimed2e5ba72019-09-12 10:14:172592 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client) {
clamy987a3752018-05-03 17:36:262593 NavigationEntryImpl* entry =
2594 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2595 if (!entry)
2596 return false;
2597
2598 FrameNavigationEntry* frame_entry =
2599 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2600 if (!frame_entry)
2601 return false;
2602
Nate Chapin45f620582021-09-30 17:45:432603 // |is_browser_initiated| is false here because a navigation in a new subframe
2604 // always begins with renderer action (i.e., an HTML element being inserted
2605 // into the DOM), so it is always renderer-initiated.
Camille Lamy5193caa2018-10-12 11:59:422606 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572607 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232608 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432609 true /* is_history_navigation_in_new_child */,
2610 false /* is_browser_initiated */);
clamyea99ea12018-05-28 13:54:232611
2612 if (!request)
2613 return false;
2614
arthursonzognif046d4a2019-12-12 19:08:102615 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412616
Rakina Zata Amni1c83b082023-02-08 01:09:002617 SCOPED_CRASH_KEY_STRING256(
2618 "Bug1400009", "req_url",
2619 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2620 SCOPED_CRASH_KEY_NUMBER(
2621 "Bug1400009", "nav_entry_si",
2622 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2623 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2624 frame_entry->site_instance()
2625 ? ((int)frame_entry->site_instance()->GetId())
2626 : -1);
2627 bool has_sig =
2628 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2629 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2630 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2631 has_sig ? (!!frame_tree_->GetRenderViewHost(
2632 frame_entry->site_instance()->group()))
2633 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052634 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2635 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232636
2637 return true;
clamy987a3752018-05-03 17:36:262638}
2639
Tsuyoshi Horo52fd08e2020-07-07 07:03:452640bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2641 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2642 if (!entry)
2643 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432644
2645 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2646 // We should never navigate to an existing initial NavigationEntry that is
2647 // the initial NavigationEntry for the initial empty document that hasn't
2648 // been overridden by the synchronous about:blank commit, to preserve
2649 // legacy behavior where trying to reload when the main frame is on the
2650 // initial empty document won't result in a navigation. See also
2651 // https://crbug.com/1277414.
2652 return false;
2653 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452654 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2655 if (!frame_entry)
2656 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142657 ReloadType reload_type = ReloadType::NORMAL;
2658 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452659 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142660 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452661 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432662 false /* is_history_navigation_in_new_child */,
2663 true /* is_browser_initiated */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452664 if (!request)
2665 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052666 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452667 return true;
2668}
2669
clamy987a3752018-05-03 17:36:262670void NavigationControllerImpl::NavigateFromFrameProxy(
2671 RenderFrameHostImpl* render_frame_host,
2672 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022673 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452674 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072675 const absl::optional<url::Origin>& initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212676 const absl::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262677 bool is_renderer_initiated,
2678 SiteInstance* source_site_instance,
2679 const Referrer& referrer,
2680 ui::PageTransition page_transition,
2681 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252682 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262683 const std::string& method,
2684 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092685 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142686 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212687 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502688 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392689 const absl::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292690 blink::mojom::NavigationInitiatorActivationAndAdStatus
2691 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222692 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492693 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462694 bool is_unfenced_top_navigation,
2695 bool force_new_browsing_instance) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582696 if (is_renderer_initiated)
2697 DCHECK(initiator_origin.has_value());
2698
clamy987a3752018-05-03 17:36:262699 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582700
Rakina Zata Amni2322f4f82022-01-24 13:24:242701 // Don't allow an entry replacement if there is no entry to replace.
2702 // http://crbug.com/457149
2703 if (GetEntryCount() == 0)
2704 should_replace_current_entry = false;
2705
clamy987a3752018-05-03 17:36:262706 // Create a NavigationEntry for the transfer, without making it the pending
2707 // entry. Subframe transfers should have a clone of the last committed entry
2708 // with a FrameNavigationEntry for the target frame. Main frame transfers
2709 // should have a new NavigationEntry.
2710 // TODO(creis): Make this unnecessary by creating (and validating) the params
2711 // directly, passing them to the destination RenderFrameHost. See
2712 // https://crbug.com/536906.
2713 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262714 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262715 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452716 DCHECK(GetLastCommittedEntry());
2717 entry = GetLastCommittedEntry()->Clone();
2718 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172719 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2720 // Renderer-initiated navigation that target a remote frame are currently
2721 // classified as browser-initiated when this one has already navigated.
2722 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372723 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2724 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2725 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2726 // same-document navigation), they will still be present in the
2727 // committed NavigationEntry that will be referenced to construct the new
2728 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262729 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082730 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582731 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072732 absl::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212733 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto22a27b142023-02-10 06:42:492734 blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482735 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori79d549d2021-02-18 12:59:542736 nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262737 } else {
2738 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172739 // If `node` is the outermost main frame, it rewrites a virtual url in order
2740 // to adjust the original input url if needed. For inner frames such as
2741 // fenced frames or subframes, they don't rewrite urls as the urls are not
2742 // input urls by users.
2743 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy987a3752018-05-03 17:36:262744 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212745 url, referrer, initiator_origin, initiator_base_url,
2746 source_site_instance, page_transition, is_renderer_initiated,
2747 extra_headers, browser_context_, blob_url_loader_factory,
2748 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262749 entry->root_node()->frame_entry->set_source_site_instance(
2750 static_cast<SiteInstanceImpl*>(source_site_instance));
2751 entry->root_node()->frame_entry->set_method(method);
2752 }
clamy987a3752018-05-03 17:36:262753
Camille Lamy5193caa2018-10-12 11:59:422754 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452755 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262756 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422757 override_user_agent = true;
clamy987a3752018-05-03 17:36:262758 }
2759 // TODO(creis): Set user gesture and intent received timestamp on Android.
2760
2761 // We may not have successfully added the FrameNavigationEntry to |entry|
2762 // above (per https://crbug.com/608402), in which case we create it from
2763 // scratch. This works because we do not depend on |frame_entry| being inside
2764 // |entry| during NavigateToEntry. This will go away when we shortcut this
2765 // further in https://crbug.com/536906.
2766 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2767 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452768 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082769 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582770 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072771 absl::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212772 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto22a27b142023-02-10 06:42:492773 blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482774 nullptr /* subresource_web_bundle_navigation_info */,
Nate Chapin63db0d12022-01-20 22:03:302775 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572776 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262777 }
2778
Camille Lamy5193caa2018-10-12 11:59:422779 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022780 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452781 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292782 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212783 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422784 params.source_site_instance = source_site_instance;
2785 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2786 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032787 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422788 params.referrer = referrer;
2789 /* params.redirect_chain: skip */
2790 params.extra_headers = extra_headers;
2791 params.is_renderer_initiated = is_renderer_initiated;
2792 params.override_user_agent = UA_OVERRIDE_INHERIT;
2793 /* params.base_url_for_data_url: skip */
2794 /* params.virtual_url_for_data_url: skip */
2795 /* params.data_url_as_string: skip */
2796 params.post_data = post_body;
2797 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582798 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422799 /* params.frame_name: skip */
2800 // TODO(clamy): See if user gesture should be propagated to this function.
2801 params.has_user_gesture = false;
2802 params.should_clear_history_list = false;
2803 params.started_from_context_menu = false;
2804 /* params.navigation_ui_data: skip */
2805 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222806 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542807 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212808 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412809 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502810 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292811 params.initiator_activation_and_ad_status =
2812 initiator_activation_and_ad_status;
Camille Lamy5193caa2018-10-12 11:59:422813
2814 std::unique_ptr<NavigationRequest> request =
2815 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032816 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142817 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392818 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492819 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
2820 is_unfenced_top_navigation);
clamyea99ea12018-05-28 13:54:232821
2822 if (!request)
2823 return;
2824
Garrett Tanzerbb8db412022-09-27 21:59:462825 // Force the navigation to take place in a new browsing instance.
2826 // This is used by _unfencedTop in fenced frames to ensure that navigations
2827 // leaving the fenced context create a new browsing instance.
2828 if (force_new_browsing_instance) {
2829 request->coop_status().ForceBrowsingInstanceSwap();
2830 }
2831
Arthur Hemery948742762019-09-18 10:06:242832 // At this stage we are proceeding with this navigation. If this was renderer
2833 // initiated with user gesture, we need to make sure we clear up potential
2834 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2835 DiscardNonCommittedEntries();
2836
Lukasz Anforowicz9ee83c272020-12-01 20:14:052837 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262838}
2839
[email protected]d1198fd2012-08-13 22:50:192840void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252841 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212842 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192843 if (!session_storage_namespace)
2844 return;
2845
2846 // We can't overwrite an existing SessionStorage without violating spec.
2847 // Attempts to do so may give a tab access to another tab's session storage
2848 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152849 bool successful_insert =
2850 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252851 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052852 static_cast<SessionStorageNamespaceImpl*>(
2853 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302854 .second;
2855 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192856}
2857
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572858bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452859 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032860 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462861}
2862
Aran Gilman37d11632019-10-08 23:07:152863SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252864 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302865 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252866 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032867 DOMStorageContextWrapper* context_wrapper =
2868 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2869
2870 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252871 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032872 if (it != session_storage_namespace_map_.end()) {
2873 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152874 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2875 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472876
michaelnbacbcbd2016-02-09 00:32:032877 return it->second.get();
2878 }
2879
2880 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102881 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2882 SessionStorageNamespaceImpl::Create(context_wrapper);
2883 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2884 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252885 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102886 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302887
Daniel Murphy31bbb8b12018-02-07 21:44:102888 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302889}
2890
2891SessionStorageNamespace*
2892NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252893 return GetSessionStorageNamespace(
2894 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302895}
2896
2897const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572898NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302899 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552900}
[email protected]d202a7c2012-01-04 07:53:472901
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572902bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562903 return needs_reload_;
2904}
[email protected]a26023822011-12-29 00:23:552905
[email protected]46bb5e9c2013-10-03 22:16:472906void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412907 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2908}
2909
2910void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472911 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412912 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542913
2914 if (last_committed_entry_index_ != -1) {
2915 entries_[last_committed_entry_index_]->SetTransitionType(
2916 ui::PAGE_TRANSITION_RELOAD);
2917 }
[email protected]46bb5e9c2013-10-03 22:16:472918}
2919
[email protected]d202a7c2012-01-04 07:53:472920void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572921 DCHECK_LT(index, GetEntryCount());
2922 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312923 DiscardNonCommittedEntries();
2924
Nate Chapin9eb16be72022-09-23 22:54:312925 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:312926 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122927 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312928 last_committed_entry_index_--;
2929}
2930
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572931NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272932 // If there is no pending_entry_, there should be no pending_entry_index_.
2933 DCHECK(pending_entry_ || pending_entry_index_ == -1);
2934
2935 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:362936 // at that index. An exception is while a reload of a post commit error page
2937 // is ongoing; in that case pending entry will point to the entry replaced
2938 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:272939 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:362940 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
2941 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:272942
[email protected]022af742011-12-28 18:37:252943 return pending_entry_;
2944}
2945
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572946int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:272947 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:272948 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:552949 return pending_entry_index_;
2950}
2951
avi25764702015-06-23 15:43:372952void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:572953 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:362954 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:312955 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:002956 bool in_fenced_frame_tree,
2957 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:312958 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
2959 // set because:
2960 // 1) They don't influence the history of the outer page.
2961 // 2) They are always replace only navigation (there is always only one entry
2962 // in their history stack).
2963 // 3) Are not top level navigations and appear similar to iframes.
2964 // Navigations of the fenced frame might create a new NavigationEntry, which
2965 // will call this function. Non fenced frame navigations will never have
2966 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
2967 // InsertOrReplaceEntry.
2968 DCHECK_EQ(in_fenced_frame_tree,
2969 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
2970 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:202971
avi5cad4912015-06-19 05:25:442972 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
2973 // need to keep continuity with the pending entry, so copy the pending entry's
2974 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
2975 // then the renderer navigated on its own, independent of the pending entry,
2976 // so don't copy anything.
2977 if (pending_entry_ && pending_entry_index_ == -1)
2978 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:202979
Rakina Zata Amnia4e27222021-12-22 01:05:002980 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:202981
creisee17e932015-07-17 17:56:222982 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:452983 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:102984 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572985 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:362986 // If the new entry is a post-commit error page, we store the current last
2987 // committed entry to the side so that we can put it back when navigating
2988 // away from the error.
2989 if (was_post_commit_error) {
2990 DCHECK(!entry_replaced_by_post_commit_error_);
2991 entry_replaced_by_post_commit_error_ =
2992 std::move(entries_[last_committed_entry_index_]);
2993 }
dcheng36b6aec92015-12-26 06:16:362994 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:222995 return;
2996 }
[email protected]765b35502008-08-21 00:51:202997
creis37979a62015-08-04 19:48:182998 // We shouldn't see replace == true when there's no committed entries.
2999 DCHECK(!replace);
3000
Michael Thiessen9b14d512019-09-23 21:19:473001 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203002
Shivani Sharmad8c8d652019-02-13 17:27:573003 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203004
dcheng36b6aec92015-12-26 06:16:363005 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203006 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293007}
3008
Shivani Sharmad8c8d652019-02-13 17:27:573009void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163010 if (entries_.size() < max_entry_count())
3011 return;
3012
3013 DCHECK_EQ(max_entry_count(), entries_.size());
3014 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573015 CHECK_EQ(pending_entry_index_, -1);
3016
3017 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423018 // Retrieve the oldest skippable entry.
3019 for (; index < GetEntryCount(); index++) {
3020 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3021 break;
Shivani Sharmad8c8d652019-02-13 17:27:573022 }
3023
3024 // If there is no skippable entry or if it is the last committed entry then
3025 // fall back to pruning the oldest entry. It is not safe to prune the last
3026 // committed entry.
3027 if (index == GetEntryCount() || index == last_committed_entry_index_)
3028 index = 0;
3029
3030 bool should_succeed = RemoveEntryAtIndex(index);
3031 DCHECK_EQ(true, should_succeed);
3032
3033 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253034}
3035
clamy3cb9bea92018-07-10 12:42:023036void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163037 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203038 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:133039 absl::optional<blink::scheduler::TaskAttributionId>
3040 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203041 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503042 TRACE_EVENT0("navigation",
3043 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273044 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023045 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363046 if (pending_entry_index_ != -1) {
3047 // The pending entry may not be in entries_ if a post-commit error page is
3048 // showing.
3049 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3050 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3051 }
Gyuyoung Kim107c2a02021-04-13 01:49:303052 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573053 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013054 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033055 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573056 int nav_entry_id = pending_entry_->GetUniqueID();
Nate Chapinbf682fa32022-09-26 22:41:203057 bool is_browser_initiated = !initiator_rfh;
Yoav Weiss8c573952022-11-17 17:35:133058 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3059 // the same as the top level frame being navigated.
3060 if (root->current_frame_host() != initiator_rfh) {
3061 soft_navigation_heuristics_task_id = absl::nullopt;
3062 }
Arthur Sonzogni620cec62018-12-13 13:08:573063
[email protected]83c2e232011-10-07 21:36:463064 // If we were navigating to a slow-to-commit page, and the user performs
3065 // a session history navigation to the last committed page, RenderViewHost
3066 // will force the throbber to start, but WebKit will essentially ignore the
3067 // navigation, and won't send a message to stop the throbber. To prevent this
3068 // from happening, we drop the navigation here and stop the slow-to-commit
3069 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023070 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083071 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273072 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033073 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123074
[email protected]83c2e232011-10-07 21:36:463075 DiscardNonCommittedEntries();
3076 return;
3077 }
3078
creisce0ef3572017-01-26 17:53:083079 // Compare FrameNavigationEntries to see which frames in the tree need to be
3080 // navigated.
clamy3cb9bea92018-07-10 12:42:023081 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3082 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Nate Chapin45f620582021-09-30 17:45:433083 FindFramesToNavigate(root, reload_type, is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133084 soft_navigation_heuristics_task_id, &same_document_loads,
3085 &different_document_loads);
creis4e2ecb72015-06-20 00:46:303086
3087 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573088 // We were unable to match any frames to navigate. This can happen if a
3089 // history navigation targets a subframe that no longer exists
3090 // (https://crbug.com/705550). In this case, we need to update the current
3091 // history entry to the pending one but keep the main document loaded. We
3092 // also need to ensure that observers are informed about the updated
3093 // current history entry (e.g., for greying out back/forward buttons), and
3094 // that renderer processes update their history offsets. The easiest way
3095 // to do all that is to schedule a "redundant" same-document navigation in
3096 // the main frame.
3097 //
3098 // Note that we don't want to remove this history entry, as it might still
3099 // be valid later, since a frame that it's targeting may be recreated.
3100 //
3101 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3102 // need to repeat history navigations until finding the one that works.
3103 // Consider changing this behavior to keep looking for the first valid
3104 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023105 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423106 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573107 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573108 ReloadType::NONE /* reload_type */,
3109 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433110 false /* is_history_navigation_in_new_child */,
3111 is_browser_initiated);
clamy3cb9bea92018-07-10 12:42:023112 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573113 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023114 DiscardPendingEntry(false);
3115 return;
3116 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573117 same_document_loads.push_back(std::move(navigation_request));
3118
3119 // Sanity check that we never take this branch for any kinds of reloads,
3120 // as those should've queued a different-document load in the main frame.
3121 DCHECK(!is_forced_reload);
3122 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303123 }
3124
Nate Chapinbf682fa32022-09-26 22:41:203125 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163126 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203127 if (initiator_rfh && initiator_rfh->IsSandboxed(
3128 network::mojom::WebSandboxFlags::kTopNavigation)) {
3129 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3130 initiator_rfh, same_document_loads) &&
3131 DoesSandboxNavigationStayWithinSubtree(
3132 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503133 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163134 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203135 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3136 initiator_rfh,
3137 navigates_inside_tree
3138 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3139 : blink::mojom::WebFeature::
3140 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523141
3142 // If the navigation occurred outside the tree discard it because
3143 // the sandboxed frame didn't have permission to navigate outside
3144 // its tree. If it is possible that the navigation is both inside and
3145 // outside the frame tree and we discard it entirely because we don't
3146 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143147 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203148 // If a |navigation_api_key| was provided, this navigation originated from
3149 // the navigation API. Notify the renderer that the navigation was
3150 // cancelled so the navigation API can fire an error event and reject the
3151 // relevant promise.
3152 if (navigation_api_key) {
3153 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3154 *navigation_api_key,
3155 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3156 }
Dave Tapuska855c1e12019-08-23 20:45:523157 DiscardPendingEntry(false);
3158 return;
3159 }
Dave Tapuska8bfd84c2019-03-26 20:47:163160 }
3161
Nate Chapin6c43c022023-02-13 23:32:423162 // If it is possible that this traverse may involve a same-document navigation
3163 // in the initiator and there is a Navigation API key involved, then we may
3164 // need to notify the initiator if it fails. (The early returns above either
3165 // do not involve these cases or already notify the initiator.)
3166 // The event only needs to fire for the initiator, and only if the initiator
3167 // itself is performing a same-document navigation (because the event will not
3168 // fire if it navigates cross-document).
3169 if (navigation_api_key) {
3170 for (auto& item : same_document_loads) {
3171 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3172 item->set_pending_navigation_api_key(*navigation_api_key);
3173 break;
3174 }
3175 }
3176 }
3177
Carlos Caballero539a421c2020-07-06 10:25:573178 // BackForwardCache:
3179 // Navigate immediately if the document is in the BackForwardCache.
3180 if (back_forward_cache_.GetEntry(nav_entry_id)) {
3181 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3182 DCHECK_EQ(reload_type, ReloadType::NONE);
3183 auto navigation_request = CreateNavigationRequestFromEntry(
3184 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3185 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433186 false /* is_history_navigation_in_new_child */, is_browser_initiated);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053187 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573188
3189 return;
3190 }
3191
3192 // History navigation might try to reuse a specific BrowsingInstance, already
3193 // used by a page in the cache. To avoid having two different main frames that
3194 // live in the same BrowsingInstance, evict the all pages with this
3195 // BrowsingInstance from the cache.
3196 //
3197 // For example, take the following scenario:
3198 //
3199 // A1 = Some page on a.com
3200 // A2 = Some other page on a.com
3201 // B3 = An uncacheable page on b.com
3202 //
3203 // Then the following navigations occur:
3204 // A1->A2->B3->A1
3205 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3206 // take its place) and A1 will be created in the same BrowsingInstance (and
3207 // SiteInstance), as A2.
3208 //
3209 // If we didn't do anything, both A1 and A2 would remain alive in the same
3210 // BrowsingInstance/SiteInstance, which is unsupported by
3211 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3212 // A2 from the cache.
3213 if (pending_entry_->site_instance()) {
3214 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3215 pending_entry_->site_instance());
3216 }
3217
Rakina Zata Amnid605d462022-06-01 10:17:033218 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3219 pending_entry_ && pending_entry_->IsRestored());
3220 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3221 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3222 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3223 pending_entry_index_);
3224 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3225 last_committed_entry_index_);
3226 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3227 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3228 pending_entry_ && pending_entry_->IsInitialEntry());
3229 SCOPED_CRASH_KEY_BOOL(
3230 "nav_reentrancy", "pending_entry_initial2",
3231 pending_entry_ &&
3232 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3233 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3234 IsInitialNavigation());
3235 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3236 IsInitialBlankNavigation());
3237 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3238 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3239 (int)pending_reload_);
3240
clamy3cb9bea92018-07-10 12:42:023241 // This call does not support re-entrancy. See http://crbug.com/347742.
3242 CHECK(!in_navigate_to_pending_entry_);
3243 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303244
Rakina Zata Amnid605d462022-06-01 10:17:033245 // If the navigation-reentrancy is caused by calling
3246 // NavigateToExistingPendingEntry twice, this will note the previous call's
3247 // pending entry's ID.
3248 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3249 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3250
arthursonzogni66f711c2019-10-08 14:40:363251 // It is not possible to delete the pending NavigationEntry while navigating
3252 // to it. Grab a reference to delay potential deletion until the end of this
3253 // function.
3254 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3255
creis4e2ecb72015-06-20 00:46:303256 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023257 for (auto& item : same_document_loads) {
3258 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053259 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303260 }
clamy3cb9bea92018-07-10 12:42:023261 for (auto& item : different_document_loads) {
3262 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053263 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303264 }
clamy3cb9bea92018-07-10 12:42:023265
3266 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303267}
3268
Alex Moshchuk3a4e77a2020-05-29 21:32:573269NavigationControllerImpl::HistoryNavigationAction
3270NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303271 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573272 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423273 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583274 // Only active and prerendered documents are allowed to navigate in their
3275 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423276 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013277 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583278 // - If the document is in pending deletion, the browser already committed
3279 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3280 // - If the document is in back-forward cache, it's not allowed to navigate
3281 // as it should remain frozen. Ignore the request and evict the document
3282 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423283 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583284 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423285 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113286 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3287 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423288 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113289 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423290 }
arthursonzogni03f76152019-02-12 10:35:203291
Alex Moshchuk3a4e77a2020-05-29 21:32:573292 // Reloads should result in a different-document load. Note that reloads may
3293 // also happen via the |needs_reload_| mechanism where the reload_type is
3294 // NONE, so detect this by comparing whether we're going to the same
3295 // entry that we're currently on. Similarly to above, only main frames
3296 // should reach this. Note that subframes support reloads, but that's done
3297 // via a different path that doesn't involve FindFramesToNavigate (see
3298 // RenderFrameHost::Reload()).
3299 if (reload_type != ReloadType::NONE ||
3300 pending_entry_index_ == last_committed_entry_index_) {
3301 DCHECK(frame->IsMainFrame());
3302 return HistoryNavigationAction::kDifferentDocument;
3303 }
3304
Alex Moshchuk47d1a4bd2020-06-01 22:15:343305 // If there is no new FrameNavigationEntry for the frame, ignore the
3306 // load. For example, this may happen when going back to an entry before a
3307 // frame was created. Suppose we commit a same-document navigation that also
3308 // results in adding a new subframe somewhere in the tree. If we go back,
3309 // the new subframe will be missing a FrameNavigationEntry in the previous
3310 // NavigationEntry, but we shouldn't delete or change what's loaded in
3311 // it.
3312 //
Alex Moshchuke65c39272020-06-03 17:55:373313 // Note that in this case, there is no need to keep looking for navigations
3314 // in subframes, which would be missing FrameNavigationEntries as well.
3315 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343316 // It's important to check this before checking |old_item| below, since both
3317 // might be null, and in that case we still shouldn't change what's loaded in
3318 // this frame. Note that scheduling any loads assumes that |new_item| is
3319 // non-null. See https://crbug.com/1088354.
3320 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3321 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373322 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343323
Charlie Reisa474fb62022-03-17 02:31:363324 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3325 // which history item it is currently on, since this may be different than the
3326 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3327 // (e.g., if a history navigation is targeting multiple frames and only some
3328 // have committed so far).
creis4e2ecb72015-06-20 00:46:303329 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363330 frame->current_frame_host()->last_committed_frame_entry();
3331 if (!old_item) {
3332 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3333 // fall back to the last committed NavigationEntry's record for this frame.
3334 // This may happen in cases like the initial state of the RenderFrameHost.
3335 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3336 // accurate FrameNavigationEntry and eliminate this case.
3337 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3338 }
3339 // If neither approach finds a FrameNavigationEntry, schedule a
3340 // different-document load.
3341 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573342 if (!old_item)
3343 return HistoryNavigationAction::kDifferentDocument;
3344
Alex Moshchuk3a4e77a2020-05-29 21:32:573345 // If the new item is not in the same SiteInstance, schedule a
3346 // different-document load. Newly restored items may not have a SiteInstance
3347 // yet, in which case it will be assigned on first commit.
3348 if (new_item->site_instance() &&
3349 new_item->site_instance() != old_item->site_instance())
3350 return HistoryNavigationAction::kDifferentDocument;
3351
3352 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313353 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3354 // that we do this even if the history navigation would not be modifying this
3355 // frame were it live.
3356 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573357 return HistoryNavigationAction::kDifferentDocument;
3358
3359 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313360 // Starting a navigation after a crash early-promotes the speculative
3361 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3362 // committed yet, so we can not possibly perform a same-document history
3363 // navigation. The frame would need to be reloaded with a cross-document
3364 // navigation.
3365 if (!frame->current_frame_host()->has_committed_any_navigation())
3366 return HistoryNavigationAction::kDifferentDocument;
3367
creis54131692016-08-12 18:32:253368 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493369 // sequence number but different item sequence number.
3370 if (new_item->document_sequence_number() ==
3371 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573372 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493373 }
avib48cb312016-05-05 21:35:003374
Alex Moshchuk3a4e77a2020-05-29 21:32:573375 // Otherwise, if both item and document sequence numbers differ, this
3376 // should be a different document load.
3377 return HistoryNavigationAction::kDifferentDocument;
3378 }
3379
3380 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373381 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573382 DCHECK_EQ(new_item->document_sequence_number(),
3383 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373384 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573385}
3386
3387void NavigationControllerImpl::FindFramesToNavigate(
3388 FrameTreeNode* frame,
3389 ReloadType reload_type,
Nate Chapin45f620582021-09-30 17:45:433390 bool is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133391 absl::optional<blink::scheduler::TaskAttributionId>
3392 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573393 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3394 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3395 DCHECK(pending_entry_);
3396 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3397
3398 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3399
3400 if (action == HistoryNavigationAction::kSameDocument) {
3401 std::unique_ptr<NavigationRequest> navigation_request =
3402 CreateNavigationRequestFromEntry(
3403 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133404 /*is_same_document_history_load=*/true,
3405 /*is_history_navigation_in_new_child_frame=*/false,
3406 is_browser_initiated, soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573407 if (navigation_request) {
3408 // Only add the request if was properly created. It's possible for the
3409 // creation to fail in certain cases, e.g. when the URL is invalid.
3410 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303411 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573412 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473413 std::unique_ptr<NavigationRequest> navigation_request =
3414 CreateNavigationRequestFromEntry(
3415 frame, pending_entry_, new_item, reload_type,
3416 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433417 false /* is_history_navigation_in_new_child */,
3418 is_browser_initiated);
Lei Zhang96031532019-10-10 19:05:473419 if (navigation_request) {
3420 // Only add the request if was properly created. It's possible for the
3421 // creation to fail in certain cases, e.g. when the URL is invalid.
3422 different_document_loads->push_back(std::move(navigation_request));
3423 }
3424 // For a different document, the subframes will be destroyed, so there's
3425 // no need to consider them.
3426 return;
Alex Moshchuke65c39272020-06-03 17:55:373427 } else if (action == HistoryNavigationAction::kStopLooking) {
3428 return;
creis4e2ecb72015-06-20 00:46:303429 }
3430
Yoav Weiss8c573952022-11-17 17:35:133431 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3432 // we currently only support soft navigation heuristics for the top level
3433 // frame.
creis4e2ecb72015-06-20 00:46:303434 for (size_t i = 0; i < frame->child_count(); i++) {
Nate Chapin45f620582021-09-30 17:45:433435 FindFramesToNavigate(frame->child_at(i), reload_type, is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133436 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
Nate Chapin45f620582021-09-30 17:45:433437 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303438 }
3439}
3440
Harkiran Bolariaba823e42021-05-21 18:30:363441base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243442 const LoadURLParams& params) {
3443 // Find the appropriate FrameTreeNode.
3444 FrameTreeNode* node = nullptr;
3445 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3446 !params.frame_name.empty()) {
3447 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033448 ? frame_tree_->FindByID(params.frame_tree_node_id)
3449 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503450 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243451 }
3452
3453 // If no FrameTreeNode was specified, navigate the main frame.
3454 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033455 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243456
Camille Lamy5193caa2018-10-12 11:59:423457 // Compute overrides to the LoadURLParams for |override_user_agent|,
3458 // |should_replace_current_entry| and |has_user_gesture| that will be used
3459 // both in the creation of the NavigationEntry and the NavigationRequest.
3460 // Ideally, the LoadURLParams themselves would be updated, but since they are
3461 // passed as a const reference, this is not possible.
3462 // TODO(clamy): When we only create a NavigationRequest, move this to
3463 // CreateNavigationRequestFromLoadURLParams.
3464 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3465 GetLastCommittedEntry());
3466
Rakina Zata Amnie2d31312022-11-18 03:38:453467 // An entry replacement must happen if the current browsing context should
3468 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333469 bool should_replace_current_entry =
3470 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453471 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423472
clamy21718cc22018-06-13 13:34:243473 // Javascript URLs should not create NavigationEntries. All other navigations
3474 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243475 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373476 std::unique_ptr<NavigationEntryImpl> entry =
3477 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3478 should_replace_current_entry,
3479 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243480 DiscardPendingEntry(false);
3481 SetPendingEntry(std::move(entry));
3482 }
3483
3484 // Renderer-debug URLs are sent to the renderer process immediately for
3485 // processing and don't need to create a NavigationRequest.
3486 // Note: this includes navigations to JavaScript URLs, which are considered
3487 // renderer-debug URLs.
3488 // Note: we intentionally leave the pending entry in place for renderer debug
3489 // URLs, unlike the cases below where we clear it if the navigation doesn't
3490 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303491 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483492 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3493 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153494 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Oleg Davydov2cc0167b2019-02-05 14:32:483495 params.url, browser_context_)) {
3496 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363497 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483498 }
3499
clamy21718cc22018-06-13 13:34:243500 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363501 return nullptr;
clamy21718cc22018-06-13 13:34:243502 }
3503
Antonio Sartori78a749f2020-11-30 12:03:393504 DCHECK(pending_entry_);
3505
clamy21718cc22018-06-13 13:34:243506 // Convert navigations to the current URL to a reload.
3507 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3508 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3509 // DevTools sometimes issues navigations to main frames that they do not
3510 // expect to see treated as reload, and it only works because they pass a
3511 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3512 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543513 ReloadType reload_type = params.reload_type;
3514 if (reload_type == ReloadType::NONE &&
3515 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043516 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243517 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243518 params.load_type ==
3519 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543520 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243521 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473522 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393523
3524 // If this is a reload of an existing FrameNavigationEntry and we had a
3525 // policy container for it, then we should copy it into the pending entry,
3526 // so that it is copied to the navigation request in
3527 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453528 FrameNavigationEntry* previous_frame_entry =
3529 GetLastCommittedEntry()->GetFrameEntry(node);
3530 if (previous_frame_entry &&
3531 previous_frame_entry->policy_container_policies()) {
3532 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3533 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393534 }
3535 }
3536
3537 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173538 // document, then we should copy the document polices from RenderFrameHost's
3539 // PolicyContainerHost. The NavigationRequest will create a new
3540 // PolicyContainerHost with the document policies from the |pending_entry_|,
3541 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3542 // the navigation. This way, we ensure that we keep enforcing the right
3543 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453544 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393545 if (node->current_frame_host() &&
3546 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193547 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163548 node->current_frame_host()
3549 ->policy_container_host()
3550 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233551 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393552 }
clamy21718cc22018-06-13 13:34:243553 }
3554
3555 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263556 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243557
Tsuyoshi Horo167ca6432022-03-09 05:16:393558 // This will be used to set the Navigation Timing API navigationStart
3559 // parameter for browser navigations in new tabs (intents, tabs opened through
3560 // "Open link in new tab"). If the navigation must wait on the current
3561 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3562 // will be updated when the BeforeUnload ack is received.
3563 const auto navigation_start_time = base::TimeTicks::Now();
3564
Camille Lamy5193caa2018-10-12 11:59:423565 std::unique_ptr<NavigationRequest> request =
3566 CreateNavigationRequestFromLoadParams(
3567 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143568 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393569 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3570 navigation_start_time);
clamy21718cc22018-06-13 13:34:243571
3572 // If the navigation couldn't start, return immediately and discard the
3573 // pending NavigationEntry.
3574 if (!request) {
3575 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363576 return nullptr;
clamy21718cc22018-06-13 13:34:243577 }
3578
Camille Lamy5193caa2018-10-12 11:59:423579#if DCHECK_IS_ON()
3580 // Safety check that NavigationRequest and NavigationEntry match.
3581 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3582#endif
3583
clamy21718cc22018-06-13 13:34:243584 // This call does not support re-entrancy. See http://crbug.com/347742.
3585 CHECK(!in_navigate_to_pending_entry_);
3586 in_navigate_to_pending_entry_ = true;
3587
arthursonzogni66f711c2019-10-08 14:40:363588 // It is not possible to delete the pending NavigationEntry while navigating
3589 // to it. Grab a reference to delay potential deletion until the end of this
3590 // function.
3591 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3592
Harkiran Bolariaba823e42021-05-21 18:30:363593 base::WeakPtr<NavigationHandle> created_navigation_handle(
3594 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053595 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243596
3597 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363598 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243599}
3600
clamyea99ea12018-05-28 13:54:233601void NavigationControllerImpl::HandleRendererDebugURL(
3602 FrameTreeNode* frame_tree_node,
3603 const GURL& url) {
3604 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243605 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3606 // the renderer process is not live, unless it is the initial navigation
3607 // of the tab.
clamyea99ea12018-05-28 13:54:233608 if (!IsInitialNavigation()) {
3609 DiscardNonCommittedEntries();
3610 return;
3611 }
Fergal Dalyecd3b0202020-06-25 01:57:373612 // The current frame is always a main frame. If IsInitialNavigation() is
3613 // true then there have been no navigations and any frames of this tab must
3614 // be in the same renderer process. If that has crashed then the only frame
3615 // that can be revived is the main frame.
3616 frame_tree_node->render_manager()
3617 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233618 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223619
3620 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3621 // notification, so set is loading to true here to properly surface it when
3622 // the renderer process is done handling the URL.
3623 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3624 if (!url.SchemeIs(url::kJavaScriptScheme)) {
3625 bool was_loading = frame_tree_node->frame_tree()
Arthur Sonzognif6785ec2022-12-05 10:11:503626 .LoadingTree()
Julie Jeongeun Kim50d124c2022-10-21 13:51:223627 ->IsLoadingIncludingInnerFrameTrees();
3628 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
3629 frame_tree_node->DidStartLoading(true /* should_show_loading_ui */,
3630 was_loading);
3631 }
clamyea99ea12018-05-28 13:54:233632 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3633}
3634
clamy21718cc22018-06-13 13:34:243635std::unique_ptr<NavigationEntryImpl>
3636NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3637 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423638 const LoadURLParams& params,
3639 bool override_user_agent,
3640 bool should_replace_current_entry,
3641 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393642 // Browser initiated navigations might not have a blob_url_loader_factory set
3643 // in params even if the navigation is to a blob URL. If that happens, lookup
3644 // the correct url loader factory to use here.
3645 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483646 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473647 // Resolve the blob URL in the storage partition associated with the target
3648 // frame. This is the storage partition the URL will be loaded in, and only
3649 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393650 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473651 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393652 }
3653
clamy21718cc22018-06-13 13:34:243654 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443655 // extra_headers in params are \n separated; navigation entries want \r\n.
3656 std::string extra_headers_crlf;
3657 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243658
3659 // For subframes, create a pending entry with a corresponding frame entry.
3660 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453661 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243662 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083663 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243664 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073665 params.url, absl::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213666 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3667 "GET", -1, blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:483668 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori78a749f2020-11-30 12:03:393669 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163670 // a conversion of a new navigation into a reload, we will set the right
3671 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193672 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243673 } else {
3674 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173675 // If `node` is the outermost main frame, it rewrites a virtual url in order
3676 // to adjust the original input url if needed. For inner frames such as
3677 // fenced frames or subframes, they don't rewrite urls as the urls are not
3678 // input urls by users.
3679 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy21718cc22018-06-13 13:34:243680 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063681 params.url, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213682 params.initiator_base_url, params.source_site_instance.get(),
3683 params.transition_type, params.is_renderer_initiated,
3684 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3685 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243686 entry->set_source_site_instance(
3687 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3688 entry->SetRedirectChain(params.redirect_chain);
3689 }
3690
3691 // Set the FTN ID (only used in non-site-per-process, for tests).
3692 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243693 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423694 entry->SetIsOverridingUserAgent(override_user_agent);
3695 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543696 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243697
clamy21718cc22018-06-13 13:34:243698 switch (params.load_type) {
3699 case LOAD_TYPE_DEFAULT:
3700 break;
3701 case LOAD_TYPE_HTTP_POST:
3702 entry->SetHasPostData(true);
3703 entry->SetPostData(params.post_data);
3704 break;
3705 case LOAD_TYPE_DATA:
3706 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3707 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283708#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243709 entry->SetDataURLAsString(params.data_url_as_string);
3710#endif
3711 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3712 break;
clamy21718cc22018-06-13 13:34:243713 }
3714
3715 // TODO(clamy): NavigationEntry is meant for information that will be kept
3716 // after the navigation ended and therefore is not appropriate for
3717 // started_from_context_menu. Move started_from_context_menu to
3718 // NavigationUIData.
3719 entry->set_started_from_context_menu(params.started_from_context_menu);
3720
3721 return entry;
3722}
3723
clamyea99ea12018-05-28 13:54:233724std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423725NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3726 FrameTreeNode* node,
3727 const LoadURLParams& params,
3728 bool override_user_agent,
3729 bool should_replace_current_entry,
3730 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143731 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423732 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573733 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393734 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223735 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493736 bool is_embedder_initiated_fenced_frame_navigation,
3737 bool is_unfenced_top_navigation) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573738 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283739 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533740 // All renderer-initiated navigations must have an initiator_origin.
3741 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513742
Camille Lamy5193caa2018-10-12 11:59:423743 GURL url_to_load;
3744 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323745
Camille Lamy2baa8022018-10-19 16:43:173746 // For main frames, rewrite the URL if necessary and compute the virtual URL
3747 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263748 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423749 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173750 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423751 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423752
Camille Lamy2baa8022018-10-19 16:43:173753 // For DATA loads, override the virtual URL.
3754 if (params.load_type == LOAD_TYPE_DATA)
3755 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423756
Camille Lamy2baa8022018-10-19 16:43:173757 if (virtual_url.is_empty())
3758 virtual_url = url_to_load;
3759
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573760 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283761
Aran Gilman249eb122019-12-02 23:32:463762 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3763 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3764 // return different results, leading to a different URL in the
3765 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3766 // pending NavigationEntry, as we'll only make one call to
3767 // RewriteUrlForNavigation.
3768 VLOG_IF(1, (url_to_load != frame_entry->url()))
3769 << "NavigationRequest and FrameEntry have different URLs: "
3770 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283771
Camille Lamy2baa8022018-10-19 16:43:173772 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423773 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173774 // NavigationRequest.
3775 } else {
3776 url_to_load = params.url;
3777 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243778 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173779 }
Camille Lamy5193caa2018-10-12 11:59:423780
Ehsan Karamad44fc72112019-02-26 18:15:473781 if (node->render_manager()->is_attaching_inner_delegate()) {
3782 // Avoid starting any new navigations since this node is now preparing for
3783 // attaching an inner delegate.
3784 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203785 }
Camille Lamy5193caa2018-10-12 11:59:423786
Ian Vollick1c6dd3e2022-04-13 02:06:263787 if (!IsValidURLForNavigation(node->IsOutermostMainFrame(), virtual_url,
3788 url_to_load))
Camille Lamy5193caa2018-10-12 11:59:423789 return nullptr;
3790
danakjd83d706d2020-11-25 22:11:123791 // Look for a pending commit that is to another document in this
3792 // FrameTreeNode. If one exists, then the last committed URL will not be the
3793 // current URL by the time this navigation commits.
3794 bool has_pending_cross_document_commit =
3795 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213796 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123797
Minggang Wangb9f3fa92021-07-01 15:30:313798 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493799 /*old_url=*/node->current_url(),
3800 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3801 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133802 /*is_same_document_history_load=*/false,
3803 is_embedder_initiated_fenced_frame_navigation,
3804 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423805
3806 // Create the NavigationParams based on |params|.
3807
Hiroki Nakagawa4ed61282021-06-18 05:37:233808 bool is_view_source_mode = entry->IsViewSourceMode();
3809 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293810
Antonio Sartori6984c742021-08-26 08:03:413811 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:293812
Hiroki Nakagawa4ed61282021-06-18 05:37:233813 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293814 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253815 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293816
Minggang Wangb9f3fa92021-07-01 15:30:313817 blink::mojom::CommonNavigationParamsPtr common_params =
3818 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:213819 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513820 blink::mojom::Referrer::New(params.referrer.url,
3821 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213822 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513823 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393824 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513825 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143826 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413827 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273828 false /* has_text_fragment_token */,
3829 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3830 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513831 false /* is_history_navigation_in_new_child_frame */,
Nan Lind91c8152021-10-21 16:22:373832 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423833
Minggang Wangb9f3fa92021-07-01 15:30:313834 blink::mojom::CommitNavigationParamsPtr commit_params =
3835 blink::mojom::CommitNavigationParams::New(
Rakina Zata Amnic7367852022-11-07 17:10:403836 absl::nullopt,
Ari Chivukula43d2cf82023-01-24 03:16:073837 // The correct storage key and session storage key will be computed
3838 // before committing the navigation.
3839 blink::StorageKey(), blink::StorageKey(), override_user_agent,
3840 params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323841 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503842 std::vector<net::RedirectInfo>(), params.post_content_type,
3843 common_params->url, common_params->method,
3844 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313845 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133846 entry->GetSubframeUniqueNames(node),
3847 /*intended_as_new_entry=*/true,
3848 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143849 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3850 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:133851 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313852 params.should_clear_history_list,
3853 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223854 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:133855 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:513856 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283857#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:133858 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143859#endif
Yoav Weiss8c573952022-11-17 17:35:133860 /*is_browser_initiated=*/!params.is_renderer_initiated,
Yoav Weiss8c573952022-11-17 17:35:133861 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:073862 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133863 /*force_enabled_origin_trials=*/std::vector<std::string>(),
3864 /*origin_agent_cluster=*/false,
3865 /*origin_agent_cluster_left_as_default=*/true,
3866 /*enabled_client_hints=*/
3867 std::vector<network::mojom::WebClientHintsType>(),
3868 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
3869 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:013870 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:133871 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:583872 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:133873 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:133874 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:283875 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:133876 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:443877 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:423878 network::mojom::NavigationDeliveryType::kDefault,
Yoav Weiss8c573952022-11-17 17:35:133879 /*view_transition_state=*/absl::nullopt,
sbinglera07ae732022-12-02 20:49:053880 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
3881 /*modified_runtime_features=*/
Garrett Tanzer29de7112022-12-06 21:26:323882 base::flat_map<::blink::mojom::RuntimeFeatureState, bool>(),
Yuzu Saijo29f96ca92022-12-08 04:54:123883 /*fenced_frame_properties=*/absl::nullopt,
3884 /*not_restored_reasons=*/nullptr);
Xiaohan Wang7f8052e02022-01-14 18:44:283885#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423886 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143887 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423888 }
3889#endif
3890
Lucas Furukawa Gadania9c45682019-07-31 22:05:143891 commit_params->was_activated = params.was_activated;
Camille Lamy5193caa2018-10-12 11:59:423892
Camille Lamy5193caa2018-10-12 11:59:423893 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3894 std::string extra_headers_crlf;
3895 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:093896
Alex Moshchuk9321e6a2022-12-07 21:58:313897 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143898 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:083899 !params.is_renderer_initiated, params.was_opener_suppressed,
Antonio Sartori9a82f6f32020-12-14 09:22:453900 params.initiator_frame_token.has_value()
3901 ? &(params.initiator_frame_token.value())
3902 : nullptr,
3903 params.initiator_process_id, extra_headers_crlf, frame_entry, entry,
jongdeok.kim5de823b32022-06-14 04:37:503904 params.is_form_submission,
John Delaney50425f82020-04-07 16:26:213905 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:293906 params.impression, params.initiator_activation_and_ad_status,
3907 params.is_pdf, is_embedder_initiated_fenced_frame_navigation);
Yao Xiaodc5ed102019-06-04 19:19:093908 navigation_request->set_from_download_cross_origin_redirect(
3909 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:553910 navigation_request->set_force_new_browsing_instance(
3911 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:093912 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:423913}
3914
3915std::unique_ptr<NavigationRequest>
3916NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:233917 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573918 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:233919 FrameNavigationEntry* frame_entry,
3920 ReloadType reload_type,
3921 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:433922 bool is_history_navigation_in_new_child_frame,
Yoav Weiss8c573952022-11-17 17:35:133923 bool is_browser_initiated,
3924 absl::optional<blink::scheduler::TaskAttributionId>
3925 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:343926 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:233927 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:433928 // We should never navigate to an existing initial NavigationEntry that is the
3929 // initial NavigationEntry for the initial empty document that hasn't been
3930 // overridden by the synchronous about:blank commit, to preserve previous
3931 // behavior where trying to reload when the main frame is on the initial empty
3932 // document won't result in a navigation.
3933 // See also https://crbug.com/1277414.
3934 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:323935
clamyea99ea12018-05-28 13:54:233936 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:013937 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573938 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:233939 // We may have been redirected when navigating to the current URL.
3940 // Use the URL the user originally intended to visit as signaled by the
3941 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:013942 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573943 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:233944 dest_referrer = Referrer();
clamyea99ea12018-05-28 13:54:233945 }
3946
Ehsan Karamad44fc72112019-02-26 18:15:473947 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
3948 // Avoid starting any new navigations since this node is now preparing for
3949 // attaching an inner delegate.
3950 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203951 }
3952
Ian Vollick1c6dd3e2022-04-13 02:06:263953 if (!IsValidURLForNavigation(frame_tree_node->IsOutermostMainFrame(),
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573954 entry->GetVirtualURL(), dest_url)) {
clamyea99ea12018-05-28 13:54:233955 return nullptr;
3956 }
3957
clamyea99ea12018-05-28 13:54:233958 // This will be used to set the Navigation Timing API navigationStart
3959 // parameter for browser navigations in new tabs (intents, tabs opened through
3960 // "Open link in new tab"). If the navigation must wait on the current
3961 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3962 // will be updated when the BeforeUnload ack is received.
3963 base::TimeTicks navigation_start = base::TimeTicks::Now();
clamyea99ea12018-05-28 13:54:233964
danakjd83d706d2020-11-25 22:11:123965 // Look for a pending commit that is to another document in this
3966 // FrameTreeNode. If one exists, then the last committed URL will not be the
3967 // current URL by the time this navigation commits.
3968 bool has_pending_cross_document_commit =
3969 frame_tree_node->render_manager()
3970 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:493971 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:213972 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123973
Minggang Wangb9f3fa92021-07-01 15:30:313974 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:123975 /*old_url=*/frame_tree_node->current_url(),
3976 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:493977 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:493978 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:133979 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:493980 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:423981
3982 // A form submission may happen here if the navigation is a
3983 // back/forward/reload navigation that does a form resubmission.
3984 scoped_refptr<network::ResourceRequestBody> request_body;
3985 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:503986 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
3987 // entry. This way, it could be directly retrieved here. Right now, it is only
3988 // partially recovered when request.method == "POST" and request.body exists.
3989 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:423990 if (frame_entry->method() == "POST") {
3991 request_body = frame_entry->GetPostData(&post_content_type);
3992 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:303993 post_content_type = std::string(
3994 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:503995 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:423996 }
3997
3998 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:313999 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514000 entry->ConstructCommonNavigationParams(
4001 *frame_entry, request_body, dest_url,
4002 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384003 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534004 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514005 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554006 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424007
4008 // TODO(clamy): |intended_as_new_entry| below should always be false once
4009 // Reload no longer leads to this being called for a pending NavigationEntry
4010 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314011 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144012 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404013 *frame_entry, common_params->url, common_params->method,
4014 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144015 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534016 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484017 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134018 frame_tree_node->AncestorOrSelfHasCSPEE(),
4019 soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144020 commit_params->post_content_type = post_content_type;
Camille Lamy5193caa2018-10-12 11:59:424021
W. James MacLeanb7d6092682022-10-05 15:23:264022 if (common_params->url.IsAboutSrcdoc()) {
4023 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4024 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594025 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264026 }
Alex Moshchuk9321e6a2022-12-07 21:58:314027 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144028 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434029 is_browser_initiated, false /* was_opener_suppressed */,
Takashi Toyoshimae87b7be2021-01-22 11:51:084030 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:454031 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
jongdeok.kim5de823b32022-06-14 04:37:504032 entry->extra_headers(), frame_entry, entry, is_form_submission,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474033 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294034 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4035 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474036 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234037}
4038
[email protected]d202a7c2012-01-04 07:53:474039void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214040 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274041 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404042
Takashi Toyoshimaea534ef22021-07-21 03:27:594043 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404044 // location bar will have up-to-date information about the security style
4045 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134046 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404047
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374048 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574049 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:464050
[email protected]b0f724c2013-09-05 04:21:134051 // TODO(avi): Remove. http://crbug.com/170921
4052 NotificationDetails notification_details =
4053 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154054 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4055 Source<NavigationController>(this),
4056 notification_details);
initial.commit09911bf2008-07-26 23:55:294057}
4058
initial.commit09911bf2008-07-26 23:55:294059// static
[email protected]d202a7c2012-01-04 07:53:474060size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234061 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154062 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214063 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234064}
4065
[email protected]d202a7c2012-01-04 07:53:474066void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224067 if (is_active && needs_reload_)
4068 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294069}
4070
[email protected]d202a7c2012-01-04 07:53:474071void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034072 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4073 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294074 if (!needs_reload_)
4075 return;
4076
Bo Liucdfa4b12018-11-06 00:21:444077 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4078 needs_reload_type_);
4079
initial.commit09911bf2008-07-26 23:55:294080 // Calling Reload() results in ignoring state, and not loading.
4081 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4082 // cached state.
avicc872d7242015-08-19 21:26:344083 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134084 NavigateToExistingPendingEntry(
4085 ReloadType::NONE,
4086 /*initiator_rfh=*/nullptr,
4087 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4088 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454089 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434090 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274091 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344092 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134093 NavigateToExistingPendingEntry(
4094 ReloadType::NONE,
4095 /*initiator_rfh=*/nullptr,
4096 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4097 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344098 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434099 // We should never navigate to an existing initial NavigationEntry that is
4100 // the initial NavigationEntry for the initial empty document that hasn't
4101 // been overridden by the synchronous about:blank commit, to preserve
4102 // legacy behavior where trying to reload when the main frame is on the
4103 // initial empty document won't result in a navigation. See also
4104 // https://crbug.com/1277414. If there is something to reload, the
4105 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4106 // it here.
avicc872d7242015-08-19 21:26:344107 needs_reload_ = false;
4108 }
initial.commit09911bf2008-07-26 23:55:294109}
4110
Kevin McNeeccca6172021-10-19 17:11:144111base::WeakPtr<NavigationHandle>
4112NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364113 RenderFrameHost* render_frame_host,
4114 const GURL& url,
4115 const std::string& error_page_html,
4116 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134117 RenderFrameHostImpl* rfhi =
4118 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584119
4120 // Only active documents can load post-commit error pages:
4121 // - If the document is in pending deletion, the browser already committed to
4122 // destroying this RenderFrameHost so ignore loading the error page.
4123 // - If the document is in back-forward cache, it's not allowed to navigate as
4124 // it should remain frozen. Ignore the request and evict the document from
4125 // back-forward cache.
4126 // - If the document is prerendering, it can navigate but when loading error
4127 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114128 if (rfhi->IsInactiveAndDisallowActivation(
4129 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144130 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114131 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584132
Rakina Zata Amni919b7922020-12-11 09:03:134133 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414134
Minggang Wangb9f3fa92021-07-01 15:30:314135 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434136 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594137 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4138 // the frame actually committed (e.g. iframe with "src" set to a
4139 // slow-responding URL). We should rewrite the URL to about:blank in this
4140 // case, as the renderer will only think a page is an error page if it has a
4141 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134142 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314143 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434144 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334145 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414146
arthursonzogni70ac7302020-05-28 08:49:054147 // Error pages have a fully permissive FramePolicy.
4148 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4149 // error pages.
4150 commit_params->frame_policy = blink::FramePolicy();
4151
John Delaney131ad362019-08-08 21:57:414152 std::unique_ptr<NavigationRequest> navigation_request =
4153 NavigationRequest::CreateBrowserInitiated(
4154 node, std::move(common_params), std::move(commit_params),
Alex Moshchuk9321e6a2022-12-07 21:58:314155 false /* was_opener_suppressed */,
Lingqi Chi82efa95e2020-12-29 05:31:194156 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:454157 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
John Delaneyf43556d2020-05-04 23:19:064158 "" /* extra_headers */, nullptr /* frame_entry */,
jongdeok.kim5de823b32022-06-14 04:37:504159 nullptr /* entry */, false /* is_form_submission */,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474160 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
4161 false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364162 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414163 navigation_request->set_net_error(error);
Charlie Reis09952ee2022-12-08 16:35:074164 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414165 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144166
4167 // Calling BeginNavigation may destroy the NavigationRequest.
4168 base::WeakPtr<NavigationRequest> created_navigation_request(
4169 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414170 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144171 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414172}
4173
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574174void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214175 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094176 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154177 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144178 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294179}
4180
[email protected]d202a7c2012-01-04 07:53:474181void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364182 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474183 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4184 // represent a no-committed-entry state.
4185 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364186 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474187 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4188 // if `entries_` contains pre-existing entries from the NavigationController
4189 // before restore, which would not be removed and will be at the front of the
4190 // entries list, causing the index to be off by the amount of pre-existing
4191 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294192 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294193}
[email protected]765b35502008-08-21 00:51:204194
arthursonzogni69a6a1b2019-09-17 09:23:004195void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004196 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4197}
4198
4199void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4200 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474201 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104202 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4203 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294204 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474205 return;
Michael Thiessenc5676d22019-09-25 22:32:104206 }
avi45a72532015-04-07 21:01:454207 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314208
4209 if (!delegate_)
4210 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374211 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484212}
4213
avi7c6f35e2015-05-08 17:52:384214int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4215 int nav_entry_id) const {
4216 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4217 if (entries_[i]->GetUniqueID() == nav_entry_id)
4218 return i;
4219 }
4220 return -1;
4221}
4222
[email protected]d202a7c2012-01-04 07:53:474223void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574224 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254225 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574226 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574227 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4228 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254229 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374230 // Normally, cloning a NavigationEntryImpl results in sharing
4231 // FrameNavigationEntries between the original and the clone. However, when
4232 // cloning from a different NavigationControllerImpl, we want to fork the
4233 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374234 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574235 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254236 }
Rakina Zata Amnie2d31312022-11-18 03:38:454237 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274238 DCHECK(pending_entry_index_ == -1 ||
4239 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254240}
[email protected]c5b88d82012-10-06 17:03:334241
4242void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184243 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334244 get_timestamp_callback_ = get_timestamp_callback;
4245}
[email protected]8ff00d72012-10-23 19:12:214246
Shivani Sharmaffb32b82019-04-09 16:58:474247// History manipulation intervention:
4248void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474249 bool replace_entry,
4250 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404251 bool is_renderer_initiated,
4252 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454253 // Note that for a subframe, previous_document_was_activated is true if the
4254 // gesture happened in any subframe (propagated to main frame) or in the main
4255 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474256 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274257 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474258 return;
4259 }
4260 if (last_committed_entry_index_ == -1)
4261 return;
4262
Shivani Sharmac4cc8922019-04-18 03:11:174263 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474264
Alexander Timine3ec4192020-04-20 16:39:404265 // Log UKM with the URL we are navigating away from.
4266 ukm::builders::HistoryManipulationIntervention(
4267 previous_page_load_ukm_source_id)
4268 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474269}
4270
Shivani Sharmac4cc8922019-04-18 03:11:174271void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4272 int reference_index,
4273 bool skippable) {
4274 auto* reference_entry = GetEntryAtIndex(reference_index);
4275 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4276
4277 int64_t document_sequence_number =
4278 reference_entry->root_node()->frame_entry->document_sequence_number();
4279 for (int index = 0; index < GetEntryCount(); index++) {
4280 auto* entry = GetEntryAtIndex(index);
4281 if (entry->root_node()->frame_entry->document_sequence_number() ==
4282 document_sequence_number) {
4283 entry->set_should_skip_on_back_forward_ui(skippable);
4284 }
4285 }
4286}
4287
arthursonzogni66f711c2019-10-08 14:40:364288std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4289NavigationControllerImpl::ReferencePendingEntry() {
4290 DCHECK(pending_entry_);
4291 auto pending_entry_ref =
4292 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4293 pending_entry_refs_.insert(pending_entry_ref.get());
4294 return pending_entry_ref;
4295}
4296
4297void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4298 // Ignore refs that don't correspond to the current pending entry.
4299 auto it = pending_entry_refs_.find(ref);
4300 if (it == pending_entry_refs_.end())
4301 return;
4302 pending_entry_refs_.erase(it);
4303
4304 if (!pending_entry_refs_.empty())
4305 return;
4306
4307 // The pending entry may be deleted before the last PendingEntryRef.
4308 if (!pending_entry_)
4309 return;
4310
4311 // We usually clear the pending entry when the matching NavigationRequest
4312 // fails, so that an arbitrary URL isn't left visible above a committed page.
4313 //
4314 // However, we do preserve the pending entry in some cases, such as on the
4315 // initial navigation of an unmodified blank tab. We also allow the delegate
4316 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4317 // user edit the URL and try again. This may be useful in cases that the
4318 // committed page cannot be attacker-controlled. In these cases, we still
4319 // allow the view to clear the pending entry and typed URL if the user
4320 // requests (e.g., hitting Escape with focus in the address bar).
4321 //
4322 // Do not leave the pending entry visible if it has an invalid URL, since this
4323 // might be formatted in an unexpected or unsafe way.
4324 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364325 bool should_preserve_entry =
4326 (pending_entry_ == GetVisibleEntry()) &&
4327 pending_entry_->GetURL().is_valid() &&
4328 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4329 if (should_preserve_entry)
4330 return;
4331
4332 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374333 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364334}
4335
Titouan Rigoudy6ec70402021-02-02 15:42:194336std::unique_ptr<PolicyContainerPolicies>
4337NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394338 RenderFrameHostImpl* rfh,
4339 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174340 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394341 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454342 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394343 FrameNavigationEntry* previous_frame_entry =
4344 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4345
4346 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4347 // ensure we always have a FrameNavigationEntry here.
4348 if (!previous_frame_entry)
4349 return nullptr;
4350
Titouan Rigoudy6ec70402021-02-02 15:42:194351 const PolicyContainerPolicies* previous_policies =
4352 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394353
Titouan Rigoudy6ec70402021-02-02 15:42:194354 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394355 return nullptr;
4356
4357 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234358 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394359 }
4360
Titouan Rigoudy72f892d2022-05-02 18:21:234361 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394362}
4363
Hayato Ito2c8c08d02021-06-23 03:38:434364void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504365 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434366 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4367 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4368 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504369
4370 auto callback = base::BindRepeating(
4371 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4372 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4373 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4374 }
4375 },
Hayato Ito2c8c08d02021-06-23 03:38:434376 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034377 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504378}
4379
4380void NavigationControllerImpl::DidAccessInitialMainDocument() {
4381 // We may have left a failed browser-initiated navigation in the address bar
4382 // to let the user edit it and try again. Clear it now that content might
4383 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034384 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504385 DiscardPendingEntry(false);
4386
4387 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374388 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504389}
4390
4391void NavigationControllerImpl::UpdateStateForFrame(
4392 RenderFrameHostImpl* rfhi,
4393 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564394 OPTIONAL_TRACE_EVENT1("content",
4395 "NavigationControllerImpl::UpdateStateForFrame",
4396 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504397 // The state update affects the last NavigationEntry associated with the given
4398 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4399 // in the case of an UpdateState from a frame being swapped out). We track
4400 // which entry this is in the RenderFrameHost's nav_entry_id.
4401 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4402 if (!entry)
4403 return;
4404
4405 FrameNavigationEntry* frame_entry =
4406 entry->GetFrameEntry(rfhi->frame_tree_node());
4407 if (!frame_entry)
4408 return;
4409
4410 // The SiteInstance might not match if we do a cross-process navigation with
4411 // replacement (e.g., auto-subframe), in which case the swap out of the old
4412 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4413 // has already been replaced and destroyed.
4414 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4415 return;
4416
4417 if (page_state == frame_entry->page_state())
4418 return; // Nothing to update.
4419
4420 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4421
4422 // The document_sequence_number and item_sequence_number recorded in the
4423 // FrameNavigationEntry should not differ from the one coming with the update,
4424 // since it must come from the same document. Do not update it if a difference
4425 // is detected, as this indicates that |frame_entry| is not the correct one.
4426 blink::ExplodedPageState exploded_state;
4427 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4428 return;
4429
4430 if (exploded_state.top.document_sequence_number !=
4431 frame_entry->document_sequence_number() ||
4432 exploded_state.top.item_sequence_number !=
4433 frame_entry->item_sequence_number()) {
4434 return;
4435 }
4436
4437 frame_entry->SetPageState(page_state);
4438 NotifyEntryChanged(entry);
4439}
4440
Domenic Denicolacd30f5f82022-03-16 21:48:014441std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4442NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574443 Direction direction,
4444 int entry_index,
4445 const url::Origin& pending_origin,
4446 FrameTreeNode* node,
4447 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304448 int64_t pending_item_sequence_number,
4449 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014450 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454451 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174452 // Don't process the initial entry.
4453 DCHECK_EQ(GetEntryCount(), 1);
4454 return entries;
4455 }
Nate Chapind1fe3612021-04-16 20:45:574456 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304457 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574458 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4459 i += offset) {
4460 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414461 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574462 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014463 // An entry should only appear in the navigation API entries if it is for
4464 // the same origin as the document being committed. Check the committed
4465 // origin, or if that is not available (during restore), check against the
4466 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414467 url::Origin frame_entry_origin =
4468 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4469 frame_entry->url(),
4470 frame_entry->initiator_origin().value_or(url::Origin())));
4471 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574472 break;
4473 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4474 continue;
4475 blink::ExplodedPageState exploded_page_state;
4476 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4477 &exploded_page_state)) {
4478 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304479
4480 // If the document represented by this FNE hid its full url from appearing
4481 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014482 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304483 // document).
4484 std::u16string url;
4485 if (pending_document_sequence_number ==
4486 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574487 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304488 url = frame_state.url_string.value_or(std::u16string());
4489 }
4490
Domenic Denicolacd30f5f82022-03-16 21:48:014491 blink::mojom::NavigationApiHistoryEntryPtr entry =
4492 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574493 frame_state.navigation_api_key.value_or(std::u16string()),
4494 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094495 frame_state.item_sequence_number,
4496 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304497 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174498
Nate Chapin63db0d12022-01-20 22:03:304499 DCHECK(entry->url.empty() ||
4500 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574501 entries.push_back(std::move(entry));
4502 previous_item_sequence_number = frame_entry->item_sequence_number();
4503 }
4504 }
4505 // If |entries| was constructed by iterating backwards from
4506 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4507 // earliest-at-the-front. Reverse it.
4508 if (direction == Direction::kBack)
4509 std::reverse(entries.begin(), entries.end());
4510 return entries;
4511}
4512
Domenic Denicolacd30f5f82022-03-16 21:48:014513blink::mojom::NavigationApiHistoryEntryArraysPtr
4514NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554515 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574516 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404517 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444518 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404519 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574520
Nate Chapind1fe3612021-04-16 20:45:574521 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554522 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574523
Nate Chapine82339d02022-05-03 23:48:254524 // NOTE: |entry_index| is the index where this entry will commit if no
4525 // modifications are made between now and DidCommitNavigation. This is used to
4526 // walk |entries_| and determine which entries should be exposed by the
4527 // navigation API. It is important to calculate this correctly, because blink
4528 // will cancel a same-document history commit if it's not present in the
4529 // entries blink knows about.
4530 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574531 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304532 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254533 bool will_create_new_entry = false;
4534 if (GetPendingEntryIndex() != -1) {
4535 entry_index = GetPendingEntryIndex();
4536 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4537 pending_item_sequence_number = frame_entry->item_sequence_number();
4538 pending_document_sequence_number =
4539 frame_entry->document_sequence_number();
4540 }
4541 } else if (request &&
4542 !NavigationTypeUtils::IsReload(
4543 request->common_params().navigation_type) &&
4544 !NavigationTypeUtils::IsHistory(
4545 request->common_params().navigation_type) &&
4546 !request->common_params().should_replace_current_entry &&
4547 !request->common_params()
4548 .is_history_navigation_in_new_child_frame) {
4549 will_create_new_entry = true;
4550 entry_index = GetLastCommittedEntryIndex() + 1;
4551 // Don't set pending_item_sequence_number or
4552 // pending_document_sequence_number in this case - a new unique isn/dsn will
4553 // be calculated in the renderer later.
4554 } else if (GetLastCommittedEntryIndex() != -1) {
4555 entry_index = GetLastCommittedEntryIndex();
4556 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574557 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304558 pending_document_sequence_number =
4559 frame_entry->document_sequence_number();
4560 }
Nate Chapind1fe3612021-04-16 20:45:574561 }
4562
Domenic Denicolacd30f5f82022-03-16 21:48:014563 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254564 if (entry_index == -1) {
4565 // TODO(rakina): Exit early when there is no last committed entry.
4566 // Remove when InitialNavigationEntry ships.
4567 return entry_arrays;
4568 }
4569
Domenic Denicolacd30f5f82022-03-16 21:48:014570 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574571 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374572 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574573
4574 // Don't populate forward entries if they will be truncated by a new entry.
4575 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014576 entry_arrays->forward_entries =
4577 PopulateSingleNavigationApiHistoryEntryVector(
4578 Direction::kForward, entry_index, pending_origin, node,
4579 site_instance.get(), pending_item_sequence_number,
4580 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574581 }
Nate Chapin4e657a472022-02-06 03:38:374582 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574583}
4584
Nate Chapinfbfe5af2021-06-10 17:22:084585NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574586NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084587 FrameNavigationEntry* current_entry,
4588 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574589 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084590 if (!target_entry || !target_entry->committed_origin())
4591 return HistoryNavigationAction::kStopLooking;
4592 if (current_entry->site_instance() != target_entry->site_instance())
4593 return HistoryNavigationAction::kStopLooking;
4594 if (!current_entry->committed_origin()->IsSameOriginWith(
4595 *target_entry->committed_origin())) {
4596 return HistoryNavigationAction::kStopLooking;
4597 }
4598
4599 // NOTE: We don't actually care between kSameDocument and
4600 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574601 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084602 return HistoryNavigationAction::kDifferentDocument;
4603 return HistoryNavigationAction::kKeepLooking;
4604}
4605
Domenic Denicolacc094fb2022-03-16 23:40:574606void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204607 RenderFrameHostImpl* initiator_rfh,
Yoav Weissa7449c3b2022-11-22 15:15:144608 absl::optional<blink::scheduler::TaskAttributionId>
4609 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574610 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204611 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084612 FrameNavigationEntry* current_entry =
4613 GetLastCommittedEntry()->GetFrameEntry(node);
4614 if (!current_entry)
4615 return;
4616
Yoav Weiss8c573952022-11-17 17:35:134617 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4618 // when `navigation.traverseTo()` is called.
4619
Nate Chapinfbfe5af2021-06-10 17:22:084620 // We want to find the nearest matching entry that is contiguously
4621 // same-instance and same-origin. Check back first, then forward.
4622 // TODO(japhet): Link spec here once it exists.
4623 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574624 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084625 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4626 if (result == HistoryNavigationAction::kStopLooking)
4627 break;
4628 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144629 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084630 return;
4631 }
4632 }
4633 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574634 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084635 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4636 if (result == HistoryNavigationAction::kStopLooking)
4637 break;
4638 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144639 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084640 return;
4641 }
4642 }
Nate Chapinbf682fa32022-09-26 22:41:204643
4644 // If we fall through to here, a matching NavigationEntry couldn't be found.
4645 // Notify the renderer that the navigation was cancelled.
4646 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4647 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084648}
4649
Domenic Denicolacc094fb2022-03-16 23:40:574650bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304651 network::mojom::ReferrerPolicy referrer_policy) {
4652 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4653 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4654}
4655
shivanigithubf405bf0d2021-11-05 17:58:334656bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4657 const FrameTreeNode* frame_tree_node) const {
4658 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4659 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544660 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Ali Hijazid87307d2022-11-07 20:15:034661 return frame_tree_->is_prerendering() ||
shivanigithubf405bf0d2021-11-05 17:58:334662 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544663}
4664
Julie Jeongeun Kim0e242242022-11-30 10:45:094665void NavigationControllerImpl::DidChangeReferrerPolicy(
4666 FrameTreeNode* node,
4667 network::mojom::ReferrerPolicy referrer_policy) {
4668 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4669 if (!entry)
4670 return;
4671
4672 // The FrameNavigationEntry may want to change whether to protect its url
4673 // in the navigation API when the referrer policy changes.
4674 entry->set_protect_url_in_navigation_api(
4675 ShouldProtectUrlInNavigationApi(referrer_policy));
4676}
4677
[email protected]8ff00d72012-10-23 19:12:214678} // namespace content