blob: 7f1e3a3892ac976e084d127367eca6ddaa8e9a57 [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"
William Liu055a3542023-04-02 17:21:1961#include "content/browser/browser_context_impl.h"
[email protected]825b1662012-03-12 19:07:3162#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4163#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0464#include "content/browser/dom_storage/session_storage_namespace_impl.h"
danakjc492bf82020-09-09 20:02:4465#include "content/browser/renderer_host/debug_urls.h"
66#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0067#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3368#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4469#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5770#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4471#include "content/browser/renderer_host/navigation_request.h"
William Liu055a3542023-04-02 17:21:1972#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_cache.h"
73#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_manager.h"
danakjc492bf82020-09-09 20:02:4474#include "content/browser/renderer_host/navigator.h"
75#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0076#include "content/browser/renderer_host/render_view_host_impl.h"
Sharon Yangd70a5392021-10-26 23:06:3277#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3378#include "content/browser/site_instance_impl.h"
Kunihiko Sakamoto346a74e2021-03-10 08:57:4879#include "content/browser/web_package/subresource_web_bundle_navigation_info.h"
Camille Lamy5193caa2018-10-12 11:59:4280#include "content/common/content_constants_internal.h"
Nate Chapind1fe3612021-04-16 20:45:5781#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5182#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1183#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1984#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1185#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4686#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0087#include "content/public/browser/navigation_details.h"
[email protected]7f6f44c2011-12-14 13:23:3888#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1689#include "content/public/browser/notification_types.h"
Lei Zhang96031532019-10-10 19:05:4790#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5891#include "content/public/browser/render_widget_host.h"
92#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1093#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3494#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1995#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3896#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1097#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:4798#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:4399#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59100#include "media/base/mime_util.h"
Arthur Sonzogni620cec62018-12-13 13:08:57101#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18102#include "services/metrics/public/cpp/ukm_builders.h"
103#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17104#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37105#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44106#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58107#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39108#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30109#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21110#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06111#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43112#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50113#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31114#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51115#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
sbinglera07ae732022-12-02 20:49:05116#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature_state.mojom.h"
[email protected]cca6f392014-05-28 21:32:26117#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29118
[email protected]8ff00d72012-10-23 19:12:21119namespace content {
[email protected]e9ba4472008-09-14 15:42:43120namespace {
121
122// Invoked when entries have been pruned, or removed. For example, if the
123// current entries are [google, digg, yahoo], with the current entry google,
124// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47125void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50126 int index,
[email protected]c12bf1a12008-09-17 16:28:49127 int count) {
[email protected]8ff00d72012-10-23 19:12:21128 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50129 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49130 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14131 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43132}
133
[email protected]e9ba4472008-09-14 15:42:43134// Configure all the NavigationEntries in entries for restore. This resets
135// the transition type to reload and makes sure the content state isn't empty.
136void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57137 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48138 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47139 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43140 // Use a transition type of reload so that we don't incorrectly increase
141 // the typed count.
Lei Zhang96031532019-10-10 19:05:47142 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
143 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43144 }
145}
146
[email protected]bf70edce2012-06-20 22:32:22147// Determines whether or not we should be carrying over a user agent override
148// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57149bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22150 return last_entry && last_entry->GetIsOverridingUserAgent();
151}
152
Camille Lamy5193caa2018-10-12 11:59:42153// Determines whether to override user agent for a navigation.
154bool ShouldOverrideUserAgent(
155 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57156 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42157 switch (override_user_agent) {
158 case NavigationController::UA_OVERRIDE_INHERIT:
159 return ShouldKeepOverride(last_committed_entry);
160 case NavigationController::UA_OVERRIDE_TRUE:
161 return true;
162 case NavigationController::UA_OVERRIDE_FALSE:
163 return false;
Camille Lamy5193caa2018-10-12 11:59:42164 }
165 NOTREACHED();
166 return false;
167}
168
Rakina Zata Amni312822d72021-06-04 16:13:37169// Returns true if this navigation should be treated as a reload. For e.g.
clamy0a656e42018-02-06 18:18:28170// navigating to the last committed url via the address bar or clicking on a
Rakina Zata Amni312822d72021-06-04 16:13:37171// link which results in a navigation to the last committed URL (but wasn't
172// converted to do a replacement navigation in the renderer), etc.
Fergal Daly766177d2020-07-07 07:54:04173// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
174// |base_url_for_data_url|, |transition_type| correspond to the new navigation
175// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
176// navigation that committed.
177bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
178 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57179 const GURL& virtual_url,
180 const GURL& base_url_for_data_url,
181 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57182 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37183 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57184 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37185 // Navigations intended to do a replacement shouldn't be converted to do a
186 // reload.
187 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28188 return false;
clamy0a656e42018-02-06 18:18:28189 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45190 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55191 return false;
192
arthursonzogni7a8243682017-12-14 16:41:42193 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28194 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42195 return false;
196
ananta3bdd8ae2016-12-22 17:11:55197 // We treat (PAGE_TRANSITION_RELOAD | PAGE_TRANSITION_FROM_ADDRESS_BAR),
198 // PAGE_TRANSITION_TYPED or PAGE_TRANSITION_LINK transitions as navigations
199 // which should be treated as reloads.
clamy0a656e42018-02-06 18:18:28200 bool transition_type_can_be_converted = false;
201 if (ui::PageTransitionCoreTypeIs(transition_type,
202 ui::PAGE_TRANSITION_RELOAD) &&
203 (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)) {
204 transition_type_can_be_converted = true;
ananta3bdd8ae2016-12-22 17:11:55205 }
clamy0a656e42018-02-06 18:18:28206 if (ui::PageTransitionCoreTypeIs(transition_type,
ananta3bdd8ae2016-12-22 17:11:55207 ui::PAGE_TRANSITION_TYPED)) {
clamy0a656e42018-02-06 18:18:28208 transition_type_can_be_converted = true;
209 }
210 if (ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_LINK))
211 transition_type_can_be_converted = true;
212 if (!transition_type_can_be_converted)
213 return false;
214
215 // This check is required for cases like view-source:, etc. Here the URL of
216 // the navigation entry would contain the url of the page, while the virtual
217 // URL contains the full URL including the view-source prefix.
218 if (virtual_url != last_committed_entry->GetVirtualURL())
219 return false;
220
Fergal Daly766177d2020-07-07 07:54:04221 // Check that the URLs match.
222 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
223 // If there's no frame entry then by definition the URLs don't match.
224 if (!frame_entry)
225 return false;
226
227 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28228 return false;
229
230 // This check is required for Android WebView loadDataWithBaseURL. Apps
231 // can pass in anything in the base URL and we need to ensure that these
232 // match before classifying it as a reload.
233 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
234 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
235 return false;
ananta3bdd8ae2016-12-22 17:11:55236 }
237
clamy0a656e42018-02-06 18:18:28238 // Skip entries with SSL errors.
239 if (last_committed_entry->ssl_error())
240 return false;
241
242 // Don't convert to a reload when the last navigation was a POST or the new
243 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04244 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28245 return false;
246
247 return true;
ananta3bdd8ae2016-12-22 17:11:55248}
249
Anton Bikineevf62d1bf2021-05-15 17:56:07250absl::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12251 const mojom::DidCommitProvisionalLoadParams& params,
252 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32253 // Error pages commit in an opaque origin, yet have the real URL that resulted
254 // in an error as the |params.url|. Since successful reload of an error page
255 // should commit in the correct origin, setting the opaque origin on the
256 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17257 if (request && request->DidEncounterError())
Anton Bikineevf62d1bf2021-05-15 17:56:07258 return absl::nullopt;
Nasko Oskov03912102019-01-11 00:21:32259
Anton Bikineevf62d1bf2021-05-15 17:56:07260 return absl::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32261}
262
Camille Lamy5193caa2018-10-12 11:59:42263bool IsValidURLForNavigation(bool is_main_frame,
264 const GURL& virtual_url,
265 const GURL& dest_url) {
266 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
267 if (is_main_frame && !virtual_url.is_valid() && !virtual_url.is_empty()) {
268 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
269 << virtual_url.possibly_invalid_spec();
270 return false;
271 }
272
273 // Don't attempt to navigate to non-empty invalid URLs.
274 if (!dest_url.is_valid() && !dest_url.is_empty()) {
275 LOG(WARNING) << "Refusing to load invalid URL: "
276 << dest_url.possibly_invalid_spec();
277 return false;
278 }
279
280 // The renderer will reject IPC messages with URLs longer than
281 // this limit, so don't attempt to navigate with a longer URL.
282 if (dest_url.spec().size() > url::kMaxURLChars) {
283 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
284 << " characters.";
285 return false;
286 }
287
Aaron Colwell33109c592020-04-21 21:31:19288 // Reject renderer debug URLs because they should have been handled before
289 // we get to this point. This check handles renderer debug URLs
290 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
291 // provides defense-in-depth if a renderer debug URL manages to get here via
292 // some other path. We want to reject the navigation here so it doesn't
293 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30294 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19295 LOG(WARNING) << "Refusing to load renderer debug URL: "
296 << dest_url.possibly_invalid_spec();
297 return false;
298 }
299
Camille Lamy5193caa2018-10-12 11:59:42300 return true;
301}
302
Mikel Astizba9cf2fd2017-12-17 10:38:10303// See replaced_navigation_entry_data.h for details: this information is meant
304// to ensure |*output_entry| keeps track of its original URL (landing page in
305// case of server redirects) as it gets replaced (e.g. history.replaceState()),
306// without overwriting it later, for main frames.
307void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57308 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10309 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17310 if (output_entry->GetReplacedEntryData().has_value() ||
311 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10312 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17313 }
Mikel Astizba9cf2fd2017-12-17 10:38:10314
315 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57316 data.first_committed_url = replaced_entry->GetURL();
317 data.first_timestamp = replaced_entry->GetTimestamp();
318 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29319 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10320}
321
Minggang Wangb9f3fa92021-07-01 15:30:31322blink::mojom::NavigationType GetNavigationType(
323 const GURL& old_url,
324 const GURL& new_url,
325 ReloadType reload_type,
326 NavigationEntryImpl* entry,
327 const FrameNavigationEntry& frame_entry,
328 bool has_pending_cross_document_commit,
329 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49330 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13331 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49332 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23333 // Reload navigations
334 switch (reload_type) {
335 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31336 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23337 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31338 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23339 case ReloadType::ORIGINAL_REQUEST_URL:
Minggang Wangb9f3fa92021-07-01 15:30:31340 return blink::mojom::NavigationType::RELOAD_ORIGINAL_REQUEST_URL;
clamyea99ea12018-05-28 13:54:23341 case ReloadType::NONE:
342 break; // Fall through to rest of function.
343 }
344
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08345 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31346 return entry->GetHasPostData()
347 ? blink::mojom::NavigationType::RESTORE_WITH_POST
348 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23349 }
350
danakjb952ef12021-01-14 19:58:49351 const bool can_be_same_document =
352 // A pending cross-document commit means this navigation will not occur in
353 // the current document, as that document would end up being replaced in
354 // the meantime.
355 !has_pending_cross_document_commit &&
356 // If the current document is an error page, we should always treat it as
357 // a different-document navigation so that we'll attempt to load the
358 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49359 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13360 // If the navigation is an embedder-initiated navigation of a fenced
361 // frame root (i.e. enters a fenced frame tree from outside),
362 // same-document navigations should be disabled because we don't want to
363 // allow information to be joined across multiple embedder-initiated
364 // fenced frame navigations (which may contain separate cross-site data).
365 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49366 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
367 // same-document navigations should be disabled because we want to force
368 // the creation of a new browsing context group.
369 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12370
clamyea99ea12018-05-28 13:54:23371 // History navigations.
372 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12373 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31374 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
375 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23376 }
377 DCHECK(!is_same_document_history_load);
378
379 // A same-document fragment-navigation happens when the only part of the url
380 // that is modified is after the '#' character.
381 //
382 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12383 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23384 //
385 // Note: this check is only valid for navigations that are not history
386 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
387 // history navigation from 'A#foo' to 'A#bar' is not a same-document
388 // navigation, but a different-document one. This is why history navigation
389 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47390 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
391 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12392
393 // The one case where we do the wrong thing here and incorrectly choose
394 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
395 // the renderer is a frameset. All frameset navigations should be
396 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
397 // navigation would do the right thing, as it would send it to the browser and
398 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
399 // into this method). But since we can't tell that case here for browser-
400 // initiated navigations, we have to get the renderer involved. In that case
401 // the navigation would be restarted due to the renderer spending a reply of
402 // mojom::CommitResult::RestartCrossDocument.
403
404 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31405 ? blink::mojom::NavigationType::SAME_DOCUMENT
406 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23407}
408
Camille Lamy5193caa2018-10-12 11:59:42409// Adjusts the original input URL if needed, to get the URL to actually load and
410// the virtual URL, which may differ.
411void RewriteUrlForNavigation(const GURL& original_url,
412 BrowserContext* browser_context,
413 GURL* url_to_load,
414 GURL* virtual_url,
415 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42416 // Allow the browser URL handler to rewrite the URL. This will, for example,
417 // remove "view-source:" from the beginning of the URL to get the URL that
418 // will actually be loaded. This real URL won't be shown to the user, just
419 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31420 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42421 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
422 url_to_load, browser_context, reverse_on_redirect);
423}
424
425#if DCHECK_IS_ON()
426// Helper sanity check function used in debug mode.
427void ValidateRequestMatchesEntry(NavigationRequest* request,
428 NavigationEntryImpl* entry) {
429 if (request->frame_tree_node()->IsMainFrame()) {
430 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
431 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31432 ui::PageTransitionFromInt(request->common_params().transition),
433 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42434 }
Nasko Oskovc36327d2019-01-03 23:23:04435 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42436 entry->should_clear_history_list());
437 DCHECK_EQ(request->common_params().has_user_gesture,
438 entry->has_user_gesture());
439 DCHECK_EQ(request->common_params().base_url_for_data_url,
440 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04441 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42442 entry->GetCanLoadLocalResources());
443 DCHECK_EQ(request->common_params().started_from_context_menu,
444 entry->has_started_from_context_menu());
445
446 FrameNavigationEntry* frame_entry =
447 entry->GetFrameEntry(request->frame_tree_node());
448 if (!frame_entry) {
449 NOTREACHED();
450 return;
451 }
452
Camille Lamy5193caa2018-10-12 11:59:42453 DCHECK_EQ(request->common_params().method, frame_entry->method());
454
Nasko Oskovc36327d2019-01-03 23:23:04455 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42456 if (redirect_size == frame_entry->redirect_chain().size()) {
457 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04458 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42459 frame_entry->redirect_chain()[i]);
460 }
461 } else {
462 NOTREACHED();
463 }
464}
465#endif // DCHECK_IS_ON()
466
Dave Tapuska8bfd84c2019-03-26 20:47:16467// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20468// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16469bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20470 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16471 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20472 DCHECK(sandboxed_initiator_rfh);
473 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
474 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16475 for (auto& item : navigations) {
476 bool within_subtree = false;
477 // Check whether this NavigationRequest affects a frame within the
478 // sandboxed frame's subtree by walking up the tree looking for the
479 // sandboxed frame.
480 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03481 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20482 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16483 within_subtree = true;
484 break;
485 }
486 }
487 if (!within_subtree)
488 return false;
489 }
490 return true;
491}
492
[email protected]e9ba4472008-09-14 15:42:43493} // namespace
494
arthursonzogni66f711c2019-10-08 14:40:36495// NavigationControllerImpl::PendingEntryRef------------------------------------
496
497NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
498 base::WeakPtr<NavigationControllerImpl> controller)
499 : controller_(controller) {}
500
501NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
502 if (!controller_) // Can be null with interstitials.
503 return;
504
505 controller_->PendingEntryRefDeleted(this);
506}
507
[email protected]d202a7c2012-01-04 07:53:47508// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29509
[email protected]23a918b2014-07-15 09:51:36510const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23511
[email protected]765b35502008-08-21 00:51:20512// static
[email protected]d202a7c2012-01-04 07:53:47513size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23514 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20515
[email protected]e6fec472013-05-14 05:29:02516// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20517// when testing.
518static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29519
[email protected]71fde352011-12-29 03:29:56520// static
dcheng9bfa5162016-04-09 01:00:57521std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
522 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10523 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07524 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21525 absl::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10526 ui::PageTransition transition,
527 bool is_renderer_initiated,
528 const std::string& extra_headers,
529 BrowserContext* browser_context,
530 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
531 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21532 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Lukasz Anforowicz641234d52019-11-07 21:07:10533 nullptr /* source_site_instance */, transition, is_renderer_initiated,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17534 extra_headers, browser_context, std::move(blob_url_loader_factory),
535 true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10536}
537
538// static
539std::unique_ptr<NavigationEntryImpl>
540NavigationControllerImpl::CreateNavigationEntry(
541 const GURL& url,
542 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07543 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21544 absl::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10545 SiteInstance* source_site_instance,
dcheng9bfa5162016-04-09 01:00:57546 ui::PageTransition transition,
547 bool is_renderer_initiated,
548 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09549 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17550 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
551 bool rewrite_virtual_urls) {
552 GURL url_to_load = url;
553 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56554 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17555 if (rewrite_virtual_urls) {
556 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
557 &reverse_on_redirect);
558 }
Lukasz Anforowicz641234d52019-11-07 21:07:10559 // Let the NTP override the navigation params and pretend that this is a
560 // browser-initiated, bookmark-like navigation.
561 GetContentClient()->browser()->OverrideNavigationParams(
Scott Violetcf6ea7e2021-06-09 21:09:21562 source_site_instance, &transition, &is_renderer_initiated, &referrer,
563 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10564
Patrick Monettef507e982019-06-19 20:18:06565 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28566 nullptr, // The site instance for tabs is sent on navigation
567 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21568 url_to_load, referrer, initiator_origin, initiator_base_url,
569 std::u16string(), transition, is_renderer_initiated,
570 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17571 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42572 entry->SetVirtualURL(virtual_url);
573 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56574 entry->set_update_virtual_url_with_url(reverse_on_redirect);
575 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06576 return entry;
[email protected]71fde352011-12-29 03:29:56577}
578
[email protected]cdcb1dee2012-01-04 00:46:20579// static
580void NavigationController::DisablePromptOnRepost() {
581 g_check_for_repost = false;
582}
583
[email protected]c5b88d82012-10-06 17:03:33584base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
585 base::Time t) {
586 // If |t| is between the water marks, we're in a run of duplicates
587 // or just getting out of it, so increase the high-water mark to get
588 // a time that probably hasn't been used before and return it.
589 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35590 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33591 return high_water_mark_;
592 }
593
594 // Otherwise, we're clear of the last duplicate run, so reset the
595 // water marks.
596 low_water_mark_ = high_water_mark_ = t;
597 return t;
598}
599
ckitagawa0faa5e42020-06-17 17:30:54600NavigationControllerImpl::ScopedShowRepostDialogForTesting::
601 ScopedShowRepostDialogForTesting()
602 : was_disallowed_(g_check_for_repost) {
603 g_check_for_repost = true;
604}
605
606NavigationControllerImpl::ScopedShowRepostDialogForTesting::
607 ~ScopedShowRepostDialogForTesting() {
608 g_check_for_repost = was_disallowed_;
609}
610
Nate Chapin9eb16be72022-09-23 22:54:31611NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
612 base::SafeRef<NavigationControllerImpl> controller)
613 : controller_(controller) {
614 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
615 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
616 frame_tree_node_id_to_keys_.insert(
617 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
618 if (auto* frame_entry = frame_tree_node->current_frame_host()
619 ->last_committed_frame_entry()) {
620 frame_tree_node_id_to_doc_seq_nos_.insert(
621 {frame_tree_node->frame_tree_node_id(),
622 frame_entry->document_sequence_number()});
623 }
624 }
625 PopulateKeySet(Direction::kBack);
626 PopulateKeySet(Direction::kForward);
627}
628
629void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
630 Direction direction) {
631 // Keep track of which FrameTreeNodes may still have relevant API keys in
632 // additional FrameNavigationEntries.
633 std::set<FrameTreeNode*> nodes_to_process;
634 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
635 nodes_to_process.insert(node);
636 }
637
638 const int offset = direction == Direction::kForward ? 1 : -1;
639 const int start = direction == Direction::kForward
640 ? controller_->GetLastCommittedEntryIndex()
641 : controller_->GetLastCommittedEntryIndex() - 1;
642 for (int i = start;
643 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
644 i += offset) {
645 std::set<FrameTreeNode*> nodes_to_continue_processing;
646
647 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
648 entry->ForEachFrameEntry([this, &nodes_to_process,
649 &nodes_to_continue_processing,
650 &entry](FrameNavigationEntry* frame_entry) {
651 // Find the |node| that matches |frame_entry|, if any.
652 FrameTreeNode* node = nullptr;
653 if (frame_entry == entry->root_node()->frame_entry) {
654 node = controller_->frame_tree().root();
655 } else {
656 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
657 if (it == names_to_nodes_.end())
658 return;
659 node = it->second;
660 }
661
662 // Skip this node if a previous step determine there are no longer
663 // relevant navigation API keys in this direction.
664 if (nodes_to_process.find(node) == nodes_to_process.end())
665 return;
666
667 // Stop processing |node| if we reach a point where it's cross-origin.
668 // See also PopulateSingleNavigationApiHistoryEntryVector().
669 url::Origin frame_entry_origin =
670 frame_entry->committed_origin().value_or(url::Origin::Resolve(
671 frame_entry->url(),
672 frame_entry->initiator_origin().value_or(url::Origin())));
673 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
674 return;
675
676 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
677 frame_entry->navigation_api_key());
678 // Mark |node| as needing more processing for the next entry.
679 nodes_to_continue_processing.insert(node);
680
681 // Check whether |node| went cross-document. If so, its children are
682 // no longer the same conceptual iframe as the current one, and
683 // should no longer be processed. This check is intentionally done
684 // after processing the current |node|, which may still have relevant
685 // discarded API keys.
686 if (frame_entry->document_sequence_number() !=
687 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50688 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31689 nodes_to_process.erase(descendant);
690 }
691 });
692
693 nodes_to_process.swap(nodes_to_continue_processing);
694 }
695}
696
697NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
698 std::set<std::string> all_keys;
699 // Find all remaining navigation API keys after some entries have been
700 // removed.
701 for (auto& entry : controller_->entries_) {
702 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
703 all_keys.insert(frame_entry->navigation_api_key());
704 });
705 }
706
707 // Notify each frame in the renderer of any disposed navigation API keys.
708 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
709 std::vector<std::string> disposed_keys;
710 for (const auto& key : id_to_keys.second) {
711 if (all_keys.find(key) == all_keys.end())
712 disposed_keys.push_back(key);
713 }
714 if (disposed_keys.empty())
715 continue;
716
717 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
718 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
719 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
720 }
721}
722
[email protected]d202a7c2012-01-04 07:53:47723NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00724 BrowserContext* browser_context,
725 FrameTree& frame_tree,
726 NavigationControllerDelegate* delegate)
727 : frame_tree_(frame_tree),
728 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57729 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22730 ssl_manager_(this),
Lei Zhang96031532019-10-10 19:05:47731 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)) {
[email protected]3d7474ff2011-07-27 17:47:37732 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29733}
734
[email protected]d202a7c2012-01-04 07:53:47735NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00736 // The NavigationControllerImpl might be called inside its delegate
737 // destructor. Calling it is not valid anymore.
738 delegate_ = nullptr;
739 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29740}
741
Matt Falkenhagen548ed1562021-07-06 01:38:26742WebContents* NavigationControllerImpl::DeprecatedGetWebContents() {
743 return delegate_->DeprecatedGetWebContents();
[email protected]fbc5e5f92012-01-02 06:08:32744}
745
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57746BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55747 return browser_context_;
748}
749
[email protected]d202a7c2012-01-04 07:53:47750void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30751 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36752 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57753 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47754 // Note that it's possible for `entries_` to contain multiple entries at this
755 // point, as Restore() might be called on a NavigationController that is
756 // already used (e.g. due to WebView's restoreState() API), not only for fresh
757 // NavigationControllers. These entries are not cleared to preserve legacy
758 // behavior and also because `pending_entry_` might point to one of the
759 // pre-existing entries. An exception for this is when `entries_` contains
760 // only the initial NavigationEntry, which must be removed.
761
762 // Do not proceed if selected_navigation will be out of bounds for the updated
763 // entries_ list, since it will be assigned to last_committed_entry_index_ and
764 // used to index entries_.
765 // TODO(https://crbug.com/1287624): Consider also returning early if entries
766 // is empty, since there should be no work to do (rather than marking the
767 // existing entries as needing reload). Also consider returning early if the
768 // selected index is -1, which represents a no-committed-entry state.
769 if (selected_navigation < -1 ||
770 selected_navigation >=
771 base::checked_cast<int>(entries->size() + entries_.size())) {
772 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24773 }
Charlie Reis23c26da2022-01-29 00:57:47774
Rakina Zata Amni46087a12022-11-11 08:28:38775 // There will always be at least one entry (new NavigationControllers will
776 // have the initial NavigationEntry).
777 if (selected_navigation == -1)
778 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47779
Rakina Zata Amni46087a12022-11-11 08:28:38780 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
781 // If we are on the initial NavigationEntry, it must be the only entry in
782 // the list. Since it's impossible to do a history navigation to the
783 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
784 // `pending_entry` might be set for a new non-history navigation).
785 // Note that we should not clear `entries_` if `entries` is empty (when
786 // InitialNavigationEntry mode is enabled), since that would leave us
787 // without any NavigationEntry.
788 CHECK_EQ(1, GetEntryCount());
789 CHECK_EQ(-1, pending_entry_index_);
790 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47791 }
[email protected]ce3fa3c2009-04-20 19:55:57792
[email protected]ce3fa3c2009-04-20 19:55:57793 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44794 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03795 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47796 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43797 if (entry->GetURL().is_empty()) {
798 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01799 // persisting the initial NavigationEntry [which is no longer possible but
800 // some old persisted sessions might still contain it] or when the
801 // serializer failed to write the URL because it's too long). Trying to
802 // restore and navigate to an entry with an empty URL will result in
803 // crashes, so change the URL to about:blank. See also
804 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43805 entry->SetURL(GURL(url::kAboutBlankURL));
806 }
dcheng36b6aec92015-12-26 06:16:36807 entries_.push_back(
808 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47809 }
avif16f85a72015-11-13 18:25:03810
811 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
812 // cleared out safely.
813 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57814
815 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36816 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57817}
818
toyoshim6142d96f2016-12-19 09:07:25819void NavigationControllerImpl::Reload(ReloadType reload_type,
820 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03821 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
822 (int)reload_type);
823 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
824 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28825 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28826 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32827 int current_index = -1;
828
Carlos IL42b416592019-10-07 23:10:36829 if (entry_replaced_by_post_commit_error_) {
830 // If there is an entry that was replaced by a currently active post-commit
831 // error navigation, this can't be the initial navigation.
832 DCHECK(!IsInitialNavigation());
833 // If the current entry is a post commit error, we reload the entry it
834 // replaced instead. We leave the error entry in place until a commit
835 // replaces it, but the pending entry points to the original entry in the
836 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
837 // case that pending_entry_ != entries_[pending_entry_index_].
838 entry = entry_replaced_by_post_commit_error_.get();
839 current_index = GetCurrentEntryIndex();
840 } else if (IsInitialNavigation() && pending_entry_) {
841 // If we are reloading the initial navigation, just use the current
842 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32843 entry = pending_entry_;
844 // The pending entry might be in entries_ (e.g., after a Clone), so we
845 // should also update the current_index.
846 current_index = pending_entry_index_;
847 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00848 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32849 current_index = GetCurrentEntryIndex();
850 if (current_index != -1) {
creis3da03872015-02-20 21:12:32851 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32852 }
[email protected]979a4bc2013-04-24 01:27:15853 }
[email protected]241db352013-04-22 18:04:05854
[email protected]59167c22013-06-03 18:07:32855 // If we are no where, then we can't reload. TODO(darin): We should add a
856 // CanReload method.
857 if (!entry)
858 return;
859
Rakina Zata Amnif297a802022-01-18 03:53:43860 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
861 // We should never navigate to an existing initial NavigationEntry that is
862 // the initial NavigationEntry for the initial empty document that hasn't
863 // been overridden by the synchronous about:blank commit, to preserve
864 // legacy behavior where trying to reload when the main frame is on the
865 // initial empty document won't result in a navigation. See also
866 // https://crbug.com/1277414.
867 return;
868 }
869
Aran Gilman37d11632019-10-08 23:07:15870 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30871 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07872 // they really want to do this. If they do, the dialog will call us back
873 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57874 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02875
[email protected]106a0812010-03-18 00:15:12876 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57877 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47878 return;
initial.commit09911bf2008-07-26 23:55:29879 }
Lei Zhang96031532019-10-10 19:05:47880
Wang Huia25efabc2022-09-24 17:27:22881 // Set ReloadType for |entry|.
882 entry->set_reload_type(reload_type);
883
Lei Zhang96031532019-10-10 19:05:47884 if (!IsInitialNavigation())
885 DiscardNonCommittedEntries();
886
887 pending_entry_ = entry;
888 pending_entry_index_ = current_index;
889 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
890
Nate Chapin45f620582021-09-30 17:45:43891 // location.reload() goes through BeginNavigation, so all reloads triggered
892 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13893 NavigateToExistingPendingEntry(
894 reload_type,
895 /*initiator_rfh=*/nullptr,
896 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
897 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29898}
899
[email protected]d202a7c2012-01-04 07:53:47900void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48901 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12902}
903
[email protected]d202a7c2012-01-04 07:53:47904void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49905 // If the pending reload type has been cleared by another navigation
906 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48907 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49908 return;
[email protected]106a0812010-03-18 00:15:12909 }
Wang Hui96ab1012022-10-11 02:05:49910 Reload(pending_reload_, false);
911 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12912}
913
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57914bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09915 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11916}
917
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57918bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38919 // Check that we're on the initial NavigationEntry and that this is not a
920 // cloned tab.
921 return IsInitialNavigation() && GetEntryCount() == 1 &&
922 GetLastCommittedEntry()->IsInitialEntry() &&
923 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40924}
925
Aran Gilman37d11632019-10-08 23:07:15926NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
927 int nav_entry_id) const {
avi254eff02015-07-01 08:27:58928 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:03929 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:58930}
931
Adithya Srinivasan9b0c99c2021-08-10 15:19:45932NavigationEntryImpl*
933NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
934 int nav_entry_id) const {
935 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
936 if (entry)
937 return entry;
938 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:52939 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:45940 : nullptr;
941}
942
W. James MacLeanc07dc41b2022-07-25 18:52:16943void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:57944 const url::Origin& origin) {
945 for (int i = 0; i < GetEntryCount(); i++) {
946 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:16947 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57948 }
949 if (entry_replaced_by_post_commit_error_) {
950 // It's possible we could come back to this entry if the error
951 // page/interstitial goes away.
952 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:16953 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57954 }
W. James MacLean1c40862c2020-04-27 21:05:57955}
956
avi25764702015-06-23 15:43:37957void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:57958 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:00959 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:37960 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:27961 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:20962}
963
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57964NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:47965 if (pending_entry_)
966 return pending_entry_;
967 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:20968}
969
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57970NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:32971 // The pending entry is safe to return for new (non-history), browser-
972 // initiated navigations. Most renderer-initiated navigations should not
973 // show the pending entry, to prevent URL spoof attacks.
974 //
975 // We make an exception for renderer-initiated navigations in new tabs, as
976 // long as no other page has tried to access the initial empty document in
977 // the new tab. If another page modifies this blank page, a URL spoof is
978 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:32979 bool safe_to_show_pending =
980 pending_entry_ &&
981 // Require a new navigation.
avi0dca04d2015-01-26 20:21:09982 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:32983 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:46984 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:32985
986 // Also allow showing the pending entry for history navigations in a new tab,
987 // such as Ctrl+Back. In this case, no existing page is visible and no one
988 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:15989 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
990 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:32991 safe_to_show_pending = true;
992
993 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:19994 return pending_entry_;
995 return GetLastCommittedEntry();
996}
997
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57998int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:20999 if (pending_entry_index_ != -1)
1000 return pending_entry_index_;
1001 return last_committed_entry_index_;
1002}
1003
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571004NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381005 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031006 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201007}
1008
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571009bool NavigationControllerImpl::CanViewSource() {
Jeremy Roman2d8dfe132021-07-06 20:51:261010 const std::string& mime_type =
Ali Hijazid87307d2022-11-07 20:15:031011 frame_tree_->root()->current_frame_host()->GetPage().contents_mime_type();
Kinuko Yasuda74702f92017-07-31 03:27:531012 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1013 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271014 NavigationEntry* visible_entry = GetVisibleEntry();
1015 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391016 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161017}
1018
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571019int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271020 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451021 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271022 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551023 return last_committed_entry_index_;
1024}
1025
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571026int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451027 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291028 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551029 return static_cast<int>(entries_.size());
1030}
1031
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571032NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371033 if (index < 0 || index >= GetEntryCount())
1034 return nullptr;
1035
avif16f85a72015-11-13 18:25:031036 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251037}
1038
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571039NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471040 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201041}
1042
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571043int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461044 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031045}
1046
Kevin McNee3b3a56192023-03-17 14:40:591047absl::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031048 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591049 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1050 return index;
1051 }
Shivani Sharma298d12852019-01-22 20:04:031052 }
Kevin McNee3b3a56192023-03-17 14:40:591053 return absl::nullopt;
1054}
1055
1056bool NavigationControllerImpl::CanGoBack() {
1057 return GetIndexForGoBack().has_value();
1058}
1059
1060absl::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
1061 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1062 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1063 return index;
1064 }
1065 }
1066 return absl::nullopt;
[email protected]765b35502008-08-21 00:51:201067}
1068
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571069bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591070 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201071}
1072
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571073bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031074 int index = GetIndexForOffset(offset);
1075 return index >= 0 && index < GetEntryCount();
1076}
1077
Xiaohan Wang7f8052e02022-01-14 18:44:281078#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151079bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151080 if (offset == 0)
1081 return true;
1082 int increment = offset > 0 ? 1 : -1;
1083 int non_skippable_entries = 0;
1084 for (int index = GetIndexForOffset(increment);
1085 index >= 0 && index < GetEntryCount(); index += increment) {
1086 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1087 non_skippable_entries++;
1088
1089 if (non_skippable_entries == std::abs(offset))
1090 return true;
1091 }
1092 return false;
1093}
1094#endif
1095
[email protected]d202a7c2012-01-04 07:53:471096void NavigationControllerImpl::GoBack() {
Kevin McNee3b3a56192023-03-17 14:40:591097 const absl::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061098
Kevin McNee3b3a56192023-03-17 14:40:591099 // TODO(mcnee): `GoBack` has been permissive about being called when it's not
1100 // possible to go back. Fix any callers that do this. If there are no issues,
1101 // change this to `DCHECK(CanGoBack())`.
1102 if (!target_index.has_value()) {
1103 base::debug::DumpWithoutCrashing();
1104 return;
shivanisha55201872018-12-13 04:29:061105 }
Miyoung Shin1c565c912021-03-17 12:11:211106
Kevin McNee3b3a56192023-03-17 14:40:591107 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201108}
1109
[email protected]d202a7c2012-01-04 07:53:471110void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161111 // Note that at least one entry (the last one) will be non-skippable since
1112 // entries are marked skippable only when they add another entry because of
1113 // redirect or pushState.
Kevin McNee3b3a56192023-03-17 14:40:591114 const absl::optional<int> target_index = GetIndexForGoForward();
1115
1116 // TODO(mcnee): `GoForward` has been permissive about being called when it's
1117 // not possible to go forward. Fix any callers that do this. If there are no
1118 // issues, change this to `DCHECK(CanGoForward())`.
1119 if (!target_index.has_value()) {
1120 base::debug::DumpWithoutCrashing();
1121 return;
shivanisha55201872018-12-13 04:29:061122 }
Kevin McNee3b3a56192023-03-17 14:40:591123
1124 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201125}
1126
[email protected]d202a7c2012-01-04 07:53:471127void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131128 GoToIndex(index, /*initiator_rfh=*/nullptr,
1129 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
1130 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161131}
1132
Nate Chapinbf682fa32022-09-26 22:41:201133void NavigationControllerImpl::GoToIndex(
1134 int index,
1135 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131136 absl::optional<blink::scheduler::TaskAttributionId>
1137 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201138 const std::string* navigation_api_key) {
Rakina Zata Amnid605d462022-06-01 10:17:031139 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
sunjian30574a62017-03-21 21:39:441140 TRACE_EVENT0("browser,navigation,benchmark",
1141 "NavigationControllerImpl::GoToIndex");
[email protected]765b35502008-08-21 00:51:201142 if (index < 0 || index >= static_cast<int>(entries_.size())) {
Rakina Zata Amni4595c36a2023-02-01 03:51:181143 // We've seen reports of this NOTREACHED being hit on Android WebView, where
1144 // we won't get the log message below. The following code ensures that
1145 // `index` and `entries_size` will show up on the minidump for that case.
1146 base::debug::Alias(&index);
1147 const size_t entries_size = entries_.size();
1148 base::debug::Alias(&entries_size);
1149 NOTREACHED() << "Index " << index
1150 << " is out of bounds, entries_.size() is " << entries_size;
[email protected]765b35502008-08-21 00:51:201151 return;
1152 }
1153
Rakina Zata Amnif297a802022-01-18 03:53:431154 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1155 // We should never navigate to an existing initial NavigationEntry that is
1156 // the initial NavigationEntry for the initial empty document that hasn't
1157 // been overridden by the synchronous about:blank commit, to preserve
1158 // legacy behavior where trying to reload when the main frame is on the
1159 // initial empty document won't result in a navigation. See also
1160 // https://crbug.com/1277414.
1161 return;
1162 }
1163
[email protected]cbab76d2008-10-13 22:42:471164 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201165
arthursonzogni5c4c202d2017-04-25 23:41:271166 DCHECK_EQ(nullptr, pending_entry_);
1167 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431168
arthursonzogni5c4c202d2017-04-25 23:41:271169 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201170 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271171 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1172 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201173 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131174 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201175 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201176}
1177
[email protected]d202a7c2012-01-04 07:53:471178void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121179 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031180 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201181 return;
1182
[email protected]9ba14052012-06-22 23:50:031183 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201184}
1185
Nate Chapinbf682fa32022-09-26 22:41:201186void NavigationControllerImpl::GoToOffsetFromRenderer(
1187 int offset,
Yoav Weiss8c573952022-11-17 17:35:131188 RenderFrameHostImpl* initiator_rfh,
1189 absl::optional<blink::scheduler::TaskAttributionId>
1190 soft_navigation_heuristics_task_id) {
Nate Chapin45f620582021-09-30 17:45:431191 // Note: This is actually reached in unit tests.
1192 if (!CanGoToOffset(offset))
1193 return;
1194
Nate Chapinbf682fa32022-09-26 22:41:201195 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131196 soft_navigation_heuristics_task_id,
1197 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431198}
1199
Xiaohan Wang7f8052e02022-01-14 18:44:281200#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151201void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1202 // Note: This is actually reached in unit tests.
1203 if (!CanGoToOffsetWithSkipping(offset))
1204 return;
1205
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421206 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151207 GoToIndex(GetIndexForOffset(offset));
1208 return;
1209 }
1210 int increment = offset > 0 ? 1 : -1;
1211 // Find the offset without counting skippable entries.
1212 int target_index = GetIndexForOffset(increment);
1213 int non_skippable_entries = 0;
1214 for (int index = target_index; index >= 0 && index < GetEntryCount();
1215 index += increment) {
1216 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1217 non_skippable_entries++;
1218
1219 if (non_skippable_entries == std::abs(offset)) {
1220 target_index = index;
1221 break;
1222 }
1223 }
1224
1225 GoToIndex(target_index);
1226}
1227#endif
1228
[email protected]41374f12013-07-24 02:49:281229bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151230 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281231 return false;
[email protected]6a13a6c2011-12-20 21:47:121232
[email protected]43032342011-03-21 14:10:311233 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281234 return true;
[email protected]cbab76d2008-10-13 22:42:471235}
1236
Michael Thiessen9b14d512019-09-23 21:19:471237void NavigationControllerImpl::PruneForwardEntries() {
1238 DiscardNonCommittedEntries();
1239 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471240 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471241 if (num_removed <= 0)
1242 return;
Nate Chapin9eb16be72022-09-23 22:54:311243 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471244 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1245 NotifyPrunedEntries(this, remove_start_index /* start index */,
1246 num_removed /* count */);
1247}
1248
Aran Gilman37d11632019-10-08 23:07:151249void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1250 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321251 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311252 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511253 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1254 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321255 }
1256}
1257
Harkiran Bolariaba823e42021-05-21 18:30:361258base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1259 const GURL& url,
1260 const Referrer& referrer,
1261 ui::PageTransition transition,
1262 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471263 LoadURLParams params(url);
1264 params.referrer = referrer;
1265 params.transition_type = transition;
1266 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361267 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471268}
1269
Harkiran Bolariaba823e42021-05-21 18:30:361270base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1271 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061272 if (params.is_renderer_initiated)
1273 DCHECK(params.initiator_origin.has_value());
1274
naskob8744d22014-08-28 17:07:431275 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151276 "NavigationControllerImpl::LoadURLWithParams", "url",
1277 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291278 bool is_explicit_navigation =
1279 GetContentClient()->browser()->IsExplicitNavigation(
1280 params.transition_type);
1281 if (HandleDebugURL(params.url, params.transition_type,
1282 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431283 // If Telemetry is running, allow the URL load to proceed as if it's
1284 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491285 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431286 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361287 return nullptr;
[email protected]47752982014-07-29 08:01:431288 }
[email protected]8bf1048012012-02-08 01:22:181289
[email protected]cf002332012-08-14 19:17:471290 // Checks based on params.load_type.
1291 switch (params.load_type) {
1292 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431293 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471294 break;
1295 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261296 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471297 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361298 return nullptr;
[email protected]cf002332012-08-14 19:17:471299 }
1300 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461301 }
[email protected]e47ae9472011-10-13 19:48:341302
[email protected]e47ae9472011-10-13 19:48:341303 // The user initiated a load, we don't need to reload anymore.
1304 needs_reload_ = false;
1305
Harkiran Bolariaba823e42021-05-21 18:30:361306 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441307}
1308
Mohamed Abdelhalim833de902019-09-16 17:41:451309bool NavigationControllerImpl::PendingEntryMatchesRequest(
1310 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191311 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451312 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191313}
1314
[email protected]d202a7c2012-01-04 07:53:471315bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321316 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071317 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331318 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441319 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251320 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471321 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131322 NavigationRequest* navigation_request) {
1323 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331324
1325 // Note: validation checks and renderer kills due to invalid commit messages
1326 // must happen before getting here, in
1327 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1328 // effects of the navigation have already occurred.
1329
[email protected]cd2e15742013-03-08 04:08:311330 is_initial_navigation_ = false;
1331
Wang Hui96ab1012022-10-11 02:05:491332 // Any pending request to repost a form submission is no longer valid, since a
1333 // different NavigationEntry is committing.
1334 pending_reload_ = ReloadType::NONE;
1335
[email protected]0e8db942008-09-24 21:21:481336 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431337 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451338 if (entry_replaced_by_post_commit_error_) {
1339 // Same document navigation events with a post-commit error should already
1340 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1341 // reaching here.
1342 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331343
Rakina Zata Amnie2d31312022-11-18 03:38:451344 // Any commit while a post-commit error page is showing should put the
1345 // original entry back, replacing the error page's entry. This includes
1346 // reloads, where the original entry was used as the pending entry and
1347 // should now be at the correct index at commit time.
1348 entries_[last_committed_entry_index_] =
1349 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481350 }
Rakina Zata Amnie2d31312022-11-18 03:38:451351 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1352 details->previous_entry_index = GetLastCommittedEntryIndex();
1353 if (PendingEntryMatchesRequest(navigation_request) &&
1354 pending_entry_->GetIsOverridingUserAgent() !=
1355 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1356 overriding_user_agent_changed = true;
1357 }
1358#if BUILDFLAG(IS_ANDROID)
1359 // TODO(crbug.com/1266277): Clean up the logic of setting
1360 // |overriding_user_agent_changed| post-launch.
1361 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1362 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
1363 // Must honor user agent overrides in the |navigation_request|, such as
1364 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1365 // result, besides comparing |pending_entry_|'s user agent against
1366 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1367 // agent against LastCommittedEntry's.
1368 if (navigation_request->is_overriding_user_agent() !=
1369 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1370 overriding_user_agent_changed = true;
1371 }
1372 }
1373#endif // BUILDFLAG(IS_ANDROID)
[email protected]ecd9d8702008-08-28 22:10:171374
Dave Tapuskaa2ab4f252021-07-08 21:31:281375 bool is_main_frame_navigation = !rfh->GetParent();
1376
Alexander Timind2f2e4f22019-04-02 20:04:531377 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1378 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281379 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141380 // BackForwardCacheMetrics to be associated with the new navigation's
1381 // NavigationEntry, by either creating a new object or reusing the previous
1382 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281383 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Arthur Sonzognif6785ec2022-12-05 10:11:501384 if (navigation_request->frame_tree_node()->frame_tree().type() ==
Dave Tapuskaa2ab4f252021-07-08 21:31:281385 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141386 back_forward_cache_metrics = BackForwardCacheMetrics::
1387 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281388 GetLastCommittedEntry(), is_main_frame_navigation,
1389 params.document_sequence_number);
1390 }
Yuzu Saijo29f96ca92022-12-08 04:54:121391
Alexander Timind2f2e4f22019-04-02 20:04:531392 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281393 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451394 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1395 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531396 }
1397 }
1398
Rakina Zata Amnifd8370b2022-11-14 13:32:251399 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1400 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091401 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251402 details->did_replace_entry =
1403 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091404
fdegans9caf66a2015-07-30 21:10:421405 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111406 // except for restored entries. This should be true even if the current commit
1407 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291408 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481409 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081410 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111411
1412 // Only make changes based on the pending entry if the NavigationRequest
1413 // matches it. Otherwise, the pending entry may be for a different request
1414 // (e.g., if a slow history navigation is pending while an auto-subframe
1415 // commit occurs).
1416 if (PendingEntryMatchesRequest(navigation_request)) {
1417 // It is no longer necessary to consider the pending entry as restored.
1418 if (pending_entry_->IsRestored()) {
1419 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1420 was_restored = true;
1421 }
[email protected]e9ba4472008-09-14 15:42:431422
Charlie Reisf8cde712022-10-20 16:25:091423 // If the SiteInstance has changed from the matching pending entry, this
1424 // must be treated as a new navigation with replacement. Set the replacement
1425 // bit here and ClassifyNavigation will identify this case and return
1426 // NEW_ENTRY.
1427 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1428 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1429 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251430 // TODO(nasko,creis,rakina): Move this to happen before committing the
1431 // navigation. This is a bit complicated because we don't currently
1432 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091433 details->did_replace_entry = true;
1434 }
Nasko Oskovaee2f862018-06-15 00:05:521435 }
[email protected]bcd904482012-02-01 01:54:221436
[email protected]e9ba4472008-09-14 15:42:431437 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101438 NavigationType navigation_type =
1439 ClassifyNavigation(rfh, params, navigation_request);
1440 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451441
Rakina Zata Amnie2d31312022-11-18 03:38:451442 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451443 // Ensure that this navigation does not add a navigation entry, since
1444 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1445 // beyond the last committed one. Therefore, `should_replace_current_entry`
1446 // should be set, which replaces the current entry, or this should be a
1447 // reload, which does not create a new entry.
1448 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1449 // navigation that is restored will not be creating a new entry anyways, so
1450 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1451 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1452 // pointed out in the issue.
Rakina Zata Amnifd8370b2022-11-14 13:32:251453 DCHECK(navigation_request->common_params().should_replace_current_entry ||
shivanigithub189833f2022-04-27 18:08:451454 navigation_request->GetReloadType() != ReloadType::NONE ||
Miyoung Shin3299cbf2022-11-22 01:41:101455 navigation_type == NAVIGATION_TYPE_AUTO_SUBFRAME);
shivanigithub189833f2022-04-27 18:08:451456 }
1457
Rakina Zata Amnie2d31312022-11-18 03:38:451458 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551459 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241460 // This is a subframe navigation on the initial empty document, which used
1461 // to not have a NavigationEntry to attach to. Now it can attach to the
1462 // initial NavigationEntry, and we must ensure that its NavigationEntry
1463 // will keep the "initial NavigationEntry" status and won't append a new
1464 // NavigationEntry (it should always do replacement instead).
1465 // See also https://crbug.com/1277414.
1466 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551467 // Subframe navigation on initial NavigationEntry must not append a new
1468 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1469 // means every subframe navigation that happens while we're on the initial
1470 // NavigationEntry will always reuse the existing NavigationEntry and
1471 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101472 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1473 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551474 // This is a navigation that modifies the initial NavigationEntry, either
1475 // for a replacement or a reload. The initial NavigationEntry should
1476 // retain its "initial NavigationEntry" status in this case.
1477 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241478 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251479 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1480 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241481 // This is a synchronous about:blank navigation on the main frame, which
1482 // used to not create a NavigationEntry when we have no NavigationEntry on
1483 // FrameTree creation. We now have the initial NavigationEntry and are on
1484 // the initial NavigationEntry. To preserve old behavior, we should still
1485 // keep the "initial" status for the new NavigationEntry that we will
1486 // create for this navigation, so that subframe navigations under the
1487 // synchronously committed about:blank document will never append new
1488 // NavigationEntry, and instead will just reuse the initial
1489 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1490 // See also https://crbug.com/1277414.
1491 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551492 }
1493 }
1494 DCHECK(!details->should_stay_as_initial_entry ||
1495 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201496
eugenebutee08663a2017-04-27 17:43:121497 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441498 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121499
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071500 details->is_prerender_activation =
1501 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241502 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1503 ->GetOutermostMainFrame()
1504 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071505
Peter Boströmd7592132019-01-30 04:50:311506 // Make sure we do not discard the pending entry for a different ongoing
1507 // navigation when a same document commit comes in unexpectedly from the
1508 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1509 // other navigation types. See https://crbug.com/900036.
1510 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061511 bool keep_pending_entry =
1512 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101513 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061514 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311515
Miyoung Shin3299cbf2022-11-22 01:41:101516 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061517 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491518 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051519 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001520 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431521 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061522 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491523 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1524 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001525 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431526 break;
[email protected]8ff00d72012-10-23 19:12:211527 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471528 RendererDidNavigateNewSubframe(
1529 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001530 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431531 break;
[email protected]8ff00d72012-10-23 19:12:211532 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391533 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251534 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001535 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081536 // We don't send a notification about auto-subframe PageState during
1537 // UpdateStateForFrame, since it looks like nothing has changed. Send
1538 // it here at commit time instead.
1539 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431540 return false;
creis59d5a47cb2016-08-24 23:57:191541 }
[email protected]e9ba4472008-09-14 15:42:431542 break;
Aran Gilman37d11632019-10-08 23:07:151543 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431544 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151545 break;
[email protected]765b35502008-08-21 00:51:201546 }
1547
[email protected]688aa65c62012-09-28 04:32:221548 // At this point, we know that the navigation has just completed, so
1549 // record the time.
1550 //
1551 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261552 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331553 base::Time timestamp =
1554 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1555 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131556 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221557
Peter Boströmd7592132019-01-30 04:50:311558 // If we aren't keeping the pending entry, there shouldn't be one at this
1559 // point. Clear it again in case any error cases above forgot to do so.
1560 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1561 // been cleared instead of protecting against it.
1562 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551563 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141564
[email protected]e9ba4472008-09-14 15:42:431565 // All committed entries should have nonempty content state so WebKit doesn't
1566 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471567 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321568 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221569 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441570 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141571
Alexander Timind2f2e4f22019-04-02 20:04:531572 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1573 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281574 if (back_forward_cache_metrics &&
1575 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531576 active_entry->set_back_forward_cache_metrics(
1577 std::move(back_forward_cache_metrics));
1578 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281579
1580 // `back_forward_cache_metrics()` may return null as we do not record
1581 // back-forward cache metrics for navigations in non-primary frame trees.
1582 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141583 // TODO(https://crbug.com/1338089): Remove this.
1584 // These are both only available from details at this point, so we capture
1585 // them here.
1586 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101587 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141588 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1589 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281590 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1591 navigation_request,
1592 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1593 }
naskoc7533512016-05-06 17:01:121594
Charles Reisc0507202017-09-21 00:40:021595 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1596 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1597 // A mismatch can occur if the renderer lies or due to a unique name collision
1598 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121599 FrameNavigationEntry* frame_entry =
1600 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021601 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1602 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031603 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081604 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1605 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031606 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201607
1608 // Remember the bindings the renderer process has at this point, so that
1609 // we do not grant this entry additional bindings if we come back to it.
1610 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301611 }
[email protected]132e281a2012-07-31 18:32:441612
[email protected]97d8f0d2013-10-29 16:49:211613 // Once it is committed, we no longer need to track several pieces of state on
1614 // the entry.
naskoc7533512016-05-06 17:01:121615 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131616
[email protected]49bd30e62011-03-22 20:12:591617 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221618 // TODO(creis): This check won't pass for subframes until we create entries
1619 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001620 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421621 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591622
[email protected]e9ba4472008-09-14 15:42:431623 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001624 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001625 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311626 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531627
arthursonzogni7ddc6542021-04-09 09:16:501628 active_entry->SetIsOverridingUserAgent(
1629 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031630
[email protected]93f230e02011-06-01 14:40:001631 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291632
aelias100c9192017-01-13 00:01:431633 if (overriding_user_agent_changed)
1634 delegate_->UpdateOverridingUserAgent();
1635
creis03b48002015-11-04 00:54:561636 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1637 // one knows the latest NavigationEntry it is showing (whether it has
1638 // committed anything in this navigation or not). This allows things like
1639 // state and title updates from RenderFrames to apply to the latest relevant
1640 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381641 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031642 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381643 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431644
1645 if (navigation_request->IsPrerenderedPageActivation()) {
1646 BroadcastHistoryOffsetAndLength();
1647 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1648 // is activated. As a result, a "prerenderingchange" event listener sees the
1649 // history.length which is not updated yet. We should guarantee that
1650 // history's length and offset should be updated before a
1651 // "prerenderingchange" event listener runs. One possible approach is to use
1652 // the same IPC which "prerenderingchange" uses, and propagate history's
1653 // length and offset together with that.
1654 }
1655
[email protected]e9ba4472008-09-14 15:42:431656 return true;
initial.commit09911bf2008-07-26 23:55:291657}
1658
[email protected]8ff00d72012-10-23 19:12:211659NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321660 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101661 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241662 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591663 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511664 "ClassifyNavigation");
1665
avi7c6f35e2015-05-08 17:52:381666 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241667 // A new entry. We may or may not have a corresponding pending entry, and
1668 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001669 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491670 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061671 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381672 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241673 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511674 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381675 return NAVIGATION_TYPE_NEW_SUBFRAME;
1676 }
1677
Charlie Reisc0f17d2d2021-01-12 18:52:491678 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381679 DCHECK(!params.history_list_was_cleared);
1680
avi39c1edd32015-06-04 20:06:001681 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381682 // All manual subframes would be did_create_new_entry and handled above, so
1683 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081684 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1685 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381686 }
1687
Rakina Zata Amnif6950d552020-11-24 03:26:101688 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1689 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381690 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1691 // create a new page.
1692
Hayato Ito2ae49442021-07-02 02:59:251693 // This main frame navigation is not a history navigation (since
1694 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1695 // reload or a replacement navigation, which will modify the existing entry.
1696 //
Nasko Oskov332593c2018-08-16 17:21:341697 // TODO(nasko): With error page isolation, reloading an existing session
1698 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491699 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341700 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511701 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491702 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061703 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381704 }
1705
Charlie Reisf8cde712022-10-20 16:25:091706 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521707 // If the SiteInstance of the |pending_entry_| does not match the
1708 // SiteInstance that got committed, treat this as a new navigation with
1709 // replacement. This can happen if back/forward/reload encounters a server
1710 // redirect to a different site or an isolated error page gets successfully
1711 // reloaded into a different SiteInstance.
1712 if (pending_entry_->site_instance() &&
1713 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491714 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061715 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521716 }
creis77c9aa32015-09-25 19:59:421717
Nasko Oskovaee2f862018-06-15 00:05:521718 if (pending_entry_index_ == -1) {
1719 // In this case, we have a pending entry for a load of a new URL but Blink
1720 // didn't do a new navigation (params.did_create_new_entry). First check
1721 // to make sure Blink didn't treat a new cross-process navigation as
1722 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161723 // we must treat it as NEW rather than the converted reload case below,
1724 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451725 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161726 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061727 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521728 }
1729
1730 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161731 // We will create a pending entry, but NavigateWithoutEntry will convert
1732 // it to a reload since it's the same page and not create a new entry for
1733 // it. (The user doesn't want to have a new back/forward entry when they
1734 // do this.) Therefore we want to just ignore the pending entry and go
1735 // back to where we were (the "existing entry").
1736 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061737 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521738 }
avi7c6f35e2015-05-08 17:52:381739 }
1740
Rakina Zata Amni153d5702021-09-13 22:48:001741 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381742 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491743 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1744 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161745 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061746 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381747 }
1748
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121749 if (navigation_request->DidEncounterError() &&
1750 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101751 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381752 // If the renderer was going to a new pending entry that got cleared because
1753 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491754 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381755 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511756 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491757 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061758 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381759 }
1760
Charlie Reisc0f17d2d2021-01-12 18:52:491761 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101762 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511763 trace_return.traced_value()->SetInteger("existing_entry_index",
1764 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381765 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441766 // The renderer has committed a navigation to an entry that no longer
1767 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491768 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061769 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381770 }
1771
avi7c6f35e2015-05-08 17:52:381772 // Since we weeded out "new" navigations above, we know this is an existing
1773 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491774 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061775 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381776}
1777
Rakina Zata Amni3460d382021-10-29 00:43:371778void NavigationControllerImpl::UpdateNavigationEntryDetails(
1779 NavigationEntryImpl* entry,
1780 RenderFrameHostImpl* rfh,
1781 const mojom::DidCommitProvisionalLoadParams& params,
1782 NavigationRequest* request,
1783 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001784 bool is_new_entry,
1785 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371786 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171787 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371788 entry->AddOrUpdateFrameEntry(
1789 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571790 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371791 rfh->GetSiteInstance(), nullptr, params.url,
1792 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171793 Referrer(*params.referrer),
1794 request ? request->common_params().initiator_origin : params.origin,
W. James MacLean23e90a12022-12-21 04:38:211795 request ? request->common_params().initiator_base_url : absl::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171796 request ? request->GetRedirectChain() : redirects, params.page_state,
1797 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amniafd3c6582021-11-30 06:19:171798 (request ? request->GetSubresourceWebBundleNavigationInfo() : nullptr),
Rakina Zata Amni3460d382021-10-29 00:43:371799 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171800 rfh, request && request->IsSameDocument(),
1801 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371802
1803 if (rfh->GetParent()) {
1804 // Only modify the NavigationEntry for main frame navigations.
1805 return;
1806 }
1807 if (entry->update_virtual_url_with_url())
1808 UpdateVirtualURLToURL(entry, params.url);
1809 // Don't use the page type from the pending entry. Some interstitial page
1810 // may have set the type to interstitial. Once we commit, however, the page
1811 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171812 entry->set_page_type((request && request->DidEncounterError())
1813 ? PAGE_TYPE_ERROR
1814 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431815 if (commit_details && commit_details->should_stay_as_initial_entry) {
1816 // Retain the "initial NavigationEntry" status.
1817 if (request->IsSameDocument()) {
1818 // If this is for a same-document navigation, the NavigationEntry must be
1819 // reused and should already be marked as the initial NavigationEntry.
1820 DCHECK(entry->IsInitialEntry());
1821 } else {
1822 // If this is for a cross-document navigation, it can be caused by a
1823 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1824 // "for synchronous about:blank" in the latter case, and also when it is
1825 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1826 // is not for a synchronous about:blank commit.
1827 NavigationEntryImpl::InitialNavigationEntryState new_state =
1828 NavigationEntryImpl::InitialNavigationEntryState::
1829 kInitialNotForSynchronousAboutBlank;
1830 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1831 request->is_synchronous_renderer_commit()) {
1832 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1833 kInitialForSynchronousAboutBlank;
1834 }
1835 entry->set_initial_navigation_entry_state(new_state);
1836 }
1837 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1838 // Remove the "initial NavigationEntry" status.
1839 entry->set_initial_navigation_entry_state(
1840 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001841 }
Rakina Zata Amniddf10502022-01-15 02:56:551842
Rakina Zata Amni3460d382021-10-29 00:43:371843 if (is_new_entry) {
1844 // Some properties of the NavigationEntry are only set when the entry is
1845 // new (we aren't reusing it).
1846 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171847 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1848 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371849 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1850 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1851 } else {
1852 // We are reusing the NavigationEntry. The site instance will normally be
1853 // the same except for a few cases:
1854 // 1) session restore, when no site instance will be assigned or
1855 // 2) redirect, when the site instance is reset.
1856 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1857 entry->site_instance() == rfh->GetSiteInstance());
1858 }
1859}
1860
Rakina Zata Amniafd3c6582021-11-30 06:19:171861void NavigationControllerImpl::CreateInitialEntry() {
1862 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031863 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171864 auto params = mojom::DidCommitProvisionalLoadParams::New();
1865 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1866 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1867 // before we have initial NavigationEntries.
1868 params->url = GURL::EmptyGURL();
1869 params->http_status_code = 0;
1870 params->url_is_unreachable = false;
1871 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171872 params->post_id = -1;
1873 params->embedding_token = base::UnguessableToken::Create();
1874 params->navigation_token = base::UnguessableToken::Create();
1875 params->did_create_new_entry = true;
1876 params->origin = rfh->GetLastCommittedOrigin();
1877 params->should_update_history = true;
1878 params->item_sequence_number = 0;
1879 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151880 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171881 params->transition = is_in_fenced_frame_tree
1882 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1883 : ui::PAGE_TRANSITION_LINK;
1884 params->referrer = blink::mojom::Referrer::New();
1885
Rakina Zata Amniafd3c6582021-11-30 06:19:171886 auto new_entry = std::make_unique<NavigationEntryImpl>(
1887 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381888 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211889 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1890 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1891 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171892 UpdateNavigationEntryDetails(
1893 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001894 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1895 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171896
1897 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1898 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001899 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171900}
1901
Charlie Reisc0f17d2d2021-01-12 18:52:491902void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321903 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071904 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361905 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441906 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471907 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001908 NavigationRequest* request,
1909 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571910 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071911 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451912 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:521913 absl::optional<GURL> initiator_base_url;
1914 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
1915 initiator_base_url = request->common_params().initiator_base_url;
1916 }
Lukasz Anforowicz435bcb582019-07-12 20:50:061917
creisf49dfc92016-07-26 17:05:181918 // First check if this is an in-page navigation. If so, clone the current
1919 // entry instead of looking at the pending entry, because the pending entry
1920 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451921 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301922 FrameNavigationEntry* previous_frame_entry =
1923 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451924 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481925 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571926 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:081927 rfh->GetSiteInstance(), nullptr, params.url,
1928 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:211929 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:091930 request->GetRedirectChain(), params.page_state, params.method,
1931 params.post_id, nullptr /* blob_url_loader_factory */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:481932 request->GetSubresourceWebBundleNavigationInfo(),
Antonio Sartori78a749f2020-11-30 12:03:391933 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301934 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:571935 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:301936 // FrameNavigationEntry.
1937 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:571938 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:031939
creisf49dfc92016-07-26 17:05:181940 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:031941 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:521942 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1943 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571944 // TODO(jam): we had one report of this with a URL that was redirecting to
1945 // only tildes. Until we understand that better, don't copy the cert in
1946 // this case.
1947 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571948 }
creisf49dfc92016-07-26 17:05:181949
Patrick Monette50e8bd82019-06-13 22:40:451950 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1951 // that |frame_entry| should now have a reference count of exactly 2: one
1952 // due to the local variable |frame_entry|, and another due to |new_entry|
1953 // also retaining one. This should never fail, because it's the main frame.
1954 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181955 }
1956
Harkiran Bolaria59290d62021-03-17 01:53:011957 // If this is an activation navigation from a prerendered page, transfer the
1958 // new entry from an entry already created and stored in the
1959 // NavigationRequest. |new_entry| will not have been set prior to this as
1960 // |is_same_document| is mutually exclusive with
1961 // |IsPrerenderedPageActivation|.
1962 if (request->IsPrerenderedPageActivation()) {
1963 DCHECK(!is_same_document);
1964 DCHECK(!new_entry);
1965 new_entry = request->TakePrerenderNavigationEntry();
1966 DCHECK(new_entry);
1967 }
1968
Charlie Reisc0f17d2d2021-01-12 18:52:491969 // Only make a copy of the pending entry if it is appropriate for the new
1970 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451971 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041972 // 1. The SiteInstance hasn't been assigned to something else.
1973 // 2. The pending entry was intended as a new entry, rather than being a
1974 // history navigation that was interrupted by an unrelated,
1975 // renderer-initiated navigation.
1976 // TODO(csharrison): Investigate whether we can remove some of the coarser
1977 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451978 if (!new_entry && PendingEntryMatchesRequest(request) &&
1979 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:341980 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:431981 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:351982 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:431983
Camille Lamy62b826012019-02-26 09:15:471984 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451985 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:181986 }
1987
Charlie Reisc0f17d2d2021-01-12 18:52:491988 // For cross-document commits with no matching pending entry, create a new
1989 // entry.
creisf49dfc92016-07-26 17:05:181990 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061991 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:071992 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:211993 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:581994 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:451995 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:171996 nullptr, // blob_url_loader_factory
1997 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:241998
1999 // Find out whether the new entry needs to update its virtual URL on URL
2000 // change and set up the entry accordingly. This is needed to correctly
2001 // update the virtual URL when replaceState is called after a pushState.
2002 GURL url = params.url;
2003 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492004 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412005 // update the virtual URL based on the new URL. For example, this is needed
2006 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2007 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372008 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2009 &url, browser_context_, &needs_update);
2010 new_entry->set_update_virtual_url_with_url(needs_update);
2011
Camille Lamy62b826012019-02-26 09:15:472012 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452013 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432014 }
2015
Harkiran Bolaria59290d62021-03-17 01:53:012016 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
2017 // for prerendered contents, if any. This is because prerendering/activation
2018 // technically won't be creating a new document. Unlike BFCache, prerendering
2019 // creates a new NavigationEntry rather than using an existing one.
2020 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372021 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2022 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002023 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082024
Harkiran Bolaria59290d62021-03-17 01:53:012025 // history.pushState() is classified as a navigation to a new page, but sets
2026 // is_same_document to true. In this case, we already have the title and
2027 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452028 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012029 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2030 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2031 }
[email protected]3a868f212014-08-09 10:41:192032 }
[email protected]ff64b3e2014-05-31 04:07:332033
[email protected]60d6cca2013-04-30 08:47:132034 DCHECK(!params.history_list_was_cleared || !replace_entry);
2035 // The browser requested to clear the session history when it initiated the
2036 // navigation. Now we know that the renderer has updated its state accordingly
2037 // and it is safe to also clear the browser side history.
2038 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552039 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132040 entries_.clear();
2041 last_committed_entry_index_ = -1;
2042 }
2043
Nasko Oskovaee2f862018-06-15 00:05:522044 // If this is a new navigation with replacement and there is a
2045 // pending_entry_ which matches the navigation reported by the renderer
2046 // process, then it should be the one replaced, so update the
2047 // last_committed_entry_index_ to use it.
2048 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092049 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522050 last_committed_entry_index_ = pending_entry_index_;
2051 }
2052
Alexander Timine3ec4192020-04-20 16:39:402053 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412054 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402055 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052056
Yuzu Saijoa725585f2022-11-28 04:14:032057 // If this is a history navigation and the old entry has an existing
2058 // back/forward cache metrics object, keep using the old one so that the
2059 // reasons logged from the last time the page navigated gets preserved.
2060 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2061 request)) {
2062 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2063 // because some tests do not have a pending entry.
2064 NavigationEntryImpl* entry =
2065 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2066 if (entry && entry->back_forward_cache_metrics()) {
2067 scoped_refptr<BackForwardCacheMetrics> metrics =
2068 entry->TakeBackForwardCacheMetrics();
2069 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2070 }
2071 }
2072
Carlos IL42b416592019-10-07 23:10:362073 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312074 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152075 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432076}
2077
Charlie Reisc0f17d2d2021-01-12 18:52:492078void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322079 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072080 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362081 bool is_same_document,
jam48cea9082017-02-15 06:13:292082 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452083 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002084 bool keep_pending_entry,
2085 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562086 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2087 << "that a last committed entry exists.";
2088
[email protected]e9ba4472008-09-14 15:42:432089 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002090 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432091
Charlie Reis7e2cb6d2021-01-26 01:27:162092 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002093 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162094 // We're guaranteed to have a last committed entry if intended_as_new_entry
2095 // is true.
avicbdc4c12015-07-01 16:07:112096 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162097
2098 // If the NavigationRequest matches a new pending entry and is classified as
2099 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2100 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092101 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162102 // Note: The pending entry will usually have a real ReloadType here, but
2103 // it can still be ReloadType::NONE in cases that
2104 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2105
2106 // If we classified this correctly, the SiteInstance should not have
2107 // changed.
2108 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2109
2110 // For converted reloads, we assign the entry's unique ID to be that of
2111 // the new one. Since this is always the result of a user action, we want
2112 // to dismiss infobars, etc. like a regular user-initiated navigation.
2113 entry->set_unique_id(pending_entry_->GetUniqueID());
2114
2115 // The extra headers may have changed due to reloading with different
2116 // headers.
2117 entry->set_extra_headers(pending_entry_->extra_headers());
2118 }
2119 // Otherwise, this was intended as a new entry but the pending entry was
2120 // lost in the meantime and no new entry was created. We are stuck at the
2121 // last committed entry.
2122
2123 // Even if this is a converted reload from pressing enter in the omnibox,
2124 // the server could redirect, requiring an update to the SSL status. If this
2125 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452126 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162127 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472128 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452129 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162130 }
Rakina Zata Amnif6950d552020-11-24 03:26:102131 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112132 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102133 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162134
eugenebut604866f2017-05-10 21:35:362135 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452136 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362137 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2138 // this was a restored same document navigation entry, then it won't have
2139 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2140 // navigated it.
jam48cea9082017-02-15 06:13:292141 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522142 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2143 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292144 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2145 was_restored) {
2146 entry->GetSSL() = last_entry->GetSSL();
2147 }
2148 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452149 // In rapid back/forward navigations |request| sometimes won't have a cert
2150 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192151 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452152 if (request->GetSSLInfo().has_value() &&
2153 request->GetSSLInfo()->is_valid()) {
2154 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522155 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2156 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192157 entry->GetSSL() = SSLStatus();
2158 }
jam48cea9082017-02-15 06:13:292159 }
avicbdc4c12015-07-01 16:07:112160 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272161 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572162 // navigations that are EXISTING_ENTRY are same-document navigations that
2163 // result in replacement (e.g. history.replaceState(), location.replace(),
2164 // forced replacements for trivial session history contexts). For these
2165 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112166 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102167
Mikel Astizba9cf2fd2017-12-17 10:38:102168 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2169 // to avoid misleading interpretations (e.g. URLs paired with
2170 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2171 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2172 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2173
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572174 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102175
eugenebut604866f2017-05-10 21:35:362176 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452177 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362178 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472179 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452180 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112181 }
2182 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432183
Rakina Zata Amni3460d382021-10-29 00:43:372184 UpdateNavigationEntryDetails(entry, rfh, params, request,
2185 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002186 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302187
[email protected]5ccd4dc2012-10-24 02:28:142188 // The redirected to page should not inherit the favicon from the previous
2189 // page.
eugenebut604866f2017-05-10 21:35:362190 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482191 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142192
Peter Boströmd7592132019-01-30 04:50:312193 // We should also usually discard the pending entry if it corresponds to a
2194 // different navigation, since that one is now likely canceled. In rare
2195 // cases, we leave the pending entry for another navigation in place when we
2196 // know it is still ongoing, to avoid a flicker in the omnibox (see
2197 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432198 //
2199 // Note that we need to use the "internal" version since we don't want to
2200 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312201 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002202 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392203
Carlos IL4dea8902020-05-26 15:14:292204 // Update the last committed index to reflect the committed entry.
avicbdc4c12015-07-01 16:07:112205 last_committed_entry_index_ = GetIndexOfEntry(entry);
[email protected]e9ba4472008-09-14 15:42:432206}
2207
[email protected]d202a7c2012-01-04 07:53:472208void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322209 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072210 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362211 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472212 bool replace_entry,
2213 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002214 NavigationRequest* request,
2215 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262216 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2217 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552218 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2219 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112220
[email protected]e9ba4472008-09-14 15:42:432221 // Manual subframe navigations just get the current entry cloned so the user
2222 // can go back or forward to it. The actual subframe information will be
2223 // stored in the page state for each of those entries. This happens out of
2224 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092225 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2226 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382227
Mikel Astizba9cf2fd2017-12-17 10:38:102228 // The DCHECK below documents the fact that we don't know of any situation
2229 // where |replace_entry| is true for subframe navigations. This simplifies
2230 // reasoning about the replacement struct for subframes (see
2231 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2232 DCHECK(!replace_entry);
2233
Patrick Monette50e8bd82019-06-13 22:40:452234 // This FrameNavigationEntry might not end up being used in the
2235 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072236 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452237 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:522238 absl::optional<GURL> initiator_base_url;
2239 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2240 initiator_base_url = request->common_params().initiator_base_url;
2241 }
Nate Chapin63db0d12022-01-20 22:03:302242 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2243 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2244 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572245 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302246 if (is_same_document) {
2247 FrameNavigationEntry* previous_frame_entry =
2248 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572249 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302250 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572251 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302252 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572253 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302254 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572255 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302256 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572257 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302258 policy_container_policies->referrer_policy);
2259 }
2260
Patrick Monette50e8bd82019-06-13 22:40:452261 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482262 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572263 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082264 rfh->GetSiteInstance(), nullptr, params.url,
2265 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212266 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2267 request->GetRedirectChain(), params.page_state, params.method,
2268 params.post_id, nullptr /* blob_url_loader_factory */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482269 request->GetSubresourceWebBundleNavigationInfo(),
Domenic Denicolacc094fb2022-03-16 23:40:572270 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032271
creisce0ef3572017-01-26 17:53:082272 std::unique_ptr<NavigationEntryImpl> new_entry =
2273 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452274 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032275 frame_tree_->root());
creise062d542015-08-25 02:01:552276
Alexander Timine3ec4192020-04-20 16:39:402277 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412278 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402279 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472280
creisce0ef3572017-01-26 17:53:082281 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452282 // to replace, which can happen due to a unique name change. See
2283 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2284 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382285
Dave Tapuska87696ae2021-11-18 18:48:312286 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152287 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432288}
2289
[email protected]d202a7c2012-01-04 07:53:472290bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322291 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072292 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392293 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252294 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002295 NavigationRequest* request,
2296 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292297 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2298 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2299
[email protected]e9ba4472008-09-14 15:42:432300 // We're guaranteed to have a previously committed entry, and we now need to
2301 // handle navigation inside of a subframe in it without creating a new entry.
2302 DCHECK(GetLastCommittedEntry());
2303
creis913c63ce2016-07-16 19:52:522304 // For newly created subframes, we don't need to send a commit notification.
2305 // This is only necessary for history navigations in subframes.
2306 bool send_commit_notification = false;
2307
Rakina Zata Amnif6950d552020-11-24 03:26:102308 // If |nav_entry_id| is non-zero and matches an existing entry, this
2309 // is a history navigation. Update the last committed index accordingly. If
2310 // we don't recognize the |nav_entry_id|, it might be a recently
2311 // pruned entry. We'll handle it below.
2312 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2313 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472314 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062315 // Make sure that a subframe commit isn't changing the main frame's
2316 // origin. Otherwise the renderer process may be confused, leading to a
2317 // URL spoof. We can't check the path since that may change
2318 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572319 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2320 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242321 // We should use checks similar to RenderFrameHostImpl's
2322 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2323 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572324 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2325 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2326 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2327 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522328 current_top_url.DeprecatedGetOriginAsURL() !=
2329 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442330 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512331 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062332 }
creis3cdc3b02015-05-29 23:00:472333
creis913c63ce2016-07-16 19:52:522334 // We only need to discard the pending entry in this history navigation
2335 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062336 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002337 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522338
2339 // History navigations should send a commit notification.
2340 send_commit_notification = true;
avi98405c22015-05-21 20:47:062341 }
[email protected]e9ba4472008-09-14 15:42:432342 }
[email protected]f233e4232013-02-23 00:55:142343
creisce0ef3572017-01-26 17:53:082344 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2345 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372346 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2347 // exists), or we may want to clobber it and create a new one. We update in
2348 // cases where the corresponding FrameNavigationEntry is conceptually similar
2349 // to the document described by the commit params: same-document
2350 // navigations, history traversal to an existing entry, and reloads (including
2351 // a "soft reload" where we navigate to the same url without flagging it as a
2352 // reload). But in the case of a different document that is not logically
2353 // related to the committed FrameNavigationEntry's document (cross-document,
2354 // not same url, not a reload, not a history traversal), we replace rather
2355 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252356 //
Nate Chapin9f169072021-06-09 19:32:372357 // In the case where we update, the FrameNavigationEntry will potentially be
2358 // shared across multiple NavigationEntries, and any updates will be reflected
2359 // in all of those NavigationEntries. In the replace case, any existing
2360 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252361 //
2362 // When navigating away from the initial empty document, we also update rather
2363 // than replace. Either update or replace will overwrite the initial empty
2364 // document state for |last_committed|, but if the FrameNavigationEntry for
2365 // the initial empty document is shared across multiple NavigationEntries (due
2366 // to a navigation in another frame), we want to make sure we overwrite the
2367 // initial empty document state everywhere this FrameNavigationEntry is used,
2368 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452369 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372370 FrameNavigationEntry* last_committed_frame_entry =
2371 last_committed->GetFrameEntry(rfh->frame_tree_node());
2372 NavigationEntryImpl::UpdatePolicy update_policy =
2373 NavigationEntryImpl::UpdatePolicy::kUpdate;
2374 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312375 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372376 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252377 last_committed_frame_entry->url() != params.url &&
2378 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372379 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2380 }
2381
Rakina Zata Amni3460d382021-10-29 00:43:372382 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002383 update_policy, false /* is_new_entry */,
2384 commit_details);
creis625a0c7d2015-03-24 23:17:122385
creis913c63ce2016-07-16 19:52:522386 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432387}
2388
[email protected]d202a7c2012-01-04 07:53:472389int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232390 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032391 for (size_t i = 0; i < entries_.size(); ++i) {
2392 if (entries_[i].get() == entry)
2393 return i;
2394 }
2395 return -1;
[email protected]765b35502008-08-21 00:51:202396}
2397
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572398void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242399 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572400 NavigationControllerImpl* source =
2401 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572402 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382403 DCHECK_EQ(1, GetEntryCount());
2404 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472405 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172406 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572407
Francois Dorayeaace782017-06-21 16:37:242408 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442409 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572410 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572411
Fergal Dalya1d569972021-03-16 03:24:532412 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302413 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532414 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2415 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302416 }
[email protected]4e6419c2010-01-15 04:50:342417
Lukasz Anforowicz0de0f452020-12-02 19:57:152418 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572419}
2420
Aran Gilman37d11632019-10-08 23:07:152421void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2422 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162423 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012424 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162425
[email protected]d202a7c2012-01-04 07:53:472426 NavigationControllerImpl* source =
2427 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252428
avi2b177592014-12-10 02:08:022429 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012430 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252431
[email protected]474f8512013-05-31 22:31:162432 // We now have one entry, possibly with a new pending entry. Ensure that
2433 // adding the entries from source won't put us over the limit.
2434 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572435 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572436 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252437
Carlos IL4dea8902020-05-26 15:14:292438 // Insert the entries from source. Ignore any pending entry, since it has not
2439 // committed in source.
[email protected]474f8512013-05-31 22:31:162440 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172441 DCHECK_NE(max_source_index, -1);
2442 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572443
2444 // Ignore the source's current entry if merging with replacement.
2445 // TODO(davidben): This should preserve entries forward of the current
2446 // too. http://crbug.com/317872
2447 if (replace_entry && max_source_index > 0)
2448 max_source_index--;
2449
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572450 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252451
2452 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552453 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142454
Hayato Ito2c8c08d02021-06-23 03:38:432455 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252456}
2457
[email protected]79368982013-11-13 01:11:012458bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162459 // If there is no last committed entry, we cannot prune. Even if there is a
2460 // pending entry, it may not commit, leaving this WebContents blank, despite
2461 // possibly giving it new entries via CopyStateFromAndPrune.
2462 if (last_committed_entry_index_ == -1)
2463 return false;
[email protected]9350602e2013-02-26 23:27:442464
[email protected]474f8512013-05-31 22:31:162465 // We cannot prune if there is a pending entry at an existing entry index.
2466 // It may not commit, so we have to keep the last committed entry, and thus
2467 // there is no sensible place to keep the pending entry. It is ok to have
2468 // a new pending entry, which can optionally commit as a new navigation.
2469 if (pending_entry_index_ != -1)
2470 return false;
2471
[email protected]474f8512013-05-31 22:31:162472 return true;
2473}
2474
[email protected]79368982013-11-13 01:11:012475void NavigationControllerImpl::PruneAllButLastCommitted() {
2476 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162477
avi2b177592014-12-10 02:08:022478 DCHECK_EQ(0, last_committed_entry_index_);
2479 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442480
Hayato Ito2c8c08d02021-06-23 03:38:432481 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442482}
2483
[email protected]79368982013-11-13 01:11:012484void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162485 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012486 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262487
Nate Chapin9eb16be72022-09-23 22:54:312488 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2489
[email protected]474f8512013-05-31 22:31:162490 // Erase all entries but the last committed entry. There may still be a
2491 // new pending entry after this.
2492 entries_.erase(entries_.begin(),
2493 entries_.begin() + last_committed_entry_index_);
2494 entries_.erase(entries_.begin() + 1, entries_.end());
2495 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262496}
2497
Christian Dullweber1af31e62018-02-22 11:49:482498void NavigationControllerImpl::DeleteNavigationEntries(
2499 const DeletionPredicate& deletionPredicate) {
2500 // It is up to callers to check the invariants before calling this.
2501 CHECK(CanPruneAllButLastCommitted());
2502 std::vector<int> delete_indices;
2503 for (size_t i = 0; i < entries_.size(); i++) {
2504 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572505 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482506 delete_indices.push_back(i);
2507 }
2508 }
2509 if (delete_indices.empty())
2510 return;
2511
2512 if (delete_indices.size() == GetEntryCount() - 1U) {
2513 PruneAllButLastCommitted();
2514 } else {
2515 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382516 for (const auto& index : base::Reversed(delete_indices)) {
2517 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482518 }
Hayato Ito2c8c08d02021-06-23 03:38:432519 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482520 }
2521 delegate()->NotifyNavigationEntriesDeleted();
2522}
2523
Shivani Sharma883f5f32019-02-12 18:20:012524bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2525 auto* entry = GetEntryAtIndex(index);
2526 return entry && entry->should_skip_on_back_forward_ui();
2527}
2528
Carlos Caballero35ce710c2019-09-19 10:59:452529BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2530 return back_forward_cache_;
2531}
2532
William Liu055a3542023-04-02 17:21:192533NavigationEntryScreenshotCache*
2534NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
2535 CHECK_EQ(frame_tree_->type(), FrameTree::Type::kPrimary);
2536 if (!nav_entry_screenshot_cache_ && AreBackForwardTransitionsEnabled()) {
2537 nav_entry_screenshot_cache_ =
2538 std::make_unique<NavigationEntryScreenshotCache>(
2539 BrowserContextImpl::From(browser_context_)
2540 ->GetNavigationEntryScreenshotManager()
2541 ->GetSafeRef(),
2542 this);
2543 }
2544 return nav_entry_screenshot_cache_.get();
2545}
2546
clamy987a3752018-05-03 17:36:262547void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2548 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2549 // progress, since this will cause a use-after-free. (We only allow this
2550 // when the tab is being destroyed for shutdown, since it won't return to
2551 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032552 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262553
2554 if (was_failure && pending_entry_) {
2555 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2556 } else {
2557 failed_pending_entry_id_ = 0;
2558 }
2559
2560 if (pending_entry_) {
2561 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332562 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262563 pending_entry_index_ = -1;
2564 pending_entry_ = nullptr;
2565 }
arthursonzogni66f711c2019-10-08 14:40:362566
2567 // Ensure any refs to the current pending entry are ignored if they get
2568 // deleted, by clearing the set of known refs. All future pending entries will
2569 // only be affected by new refs.
2570 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262571}
2572
2573void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2574 if (pending_entry_)
2575 pending_entry_->set_ssl_error(error);
2576}
2577
Xiaohan Wang7f8052e02022-01-14 18:44:282578#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422579// static
2580bool NavigationControllerImpl::ValidateDataURLAsString(
2581 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2582 if (!data_url_as_string)
2583 return false;
2584
2585 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2586 return false;
2587
2588 // The number of characters that is enough for validating a data: URI.
2589 // From the GURL's POV, the only important part here is scheme, it doesn't
2590 // check the actual content. Thus we can take only the prefix of the url, to
2591 // avoid unneeded copying of a potentially long string.
2592 const size_t kDataUriPrefixMaxLen = 64;
2593 GURL data_url(
2594 std::string(data_url_as_string->front_as<char>(),
2595 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2596 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2597 return false;
2598
2599 return true;
2600}
2601#endif
2602
Shivani Sharma194877032019-03-07 17:52:472603void NavigationControllerImpl::NotifyUserActivation() {
2604 // When a user activation occurs, ensure that all adjacent entries for the
2605 // same document clear their skippable bit, so that the history manipulation
2606 // intervention does not apply to them.
shivanigithub99368382021-06-16 18:33:372607 if (base::FeatureList::IsEnabled(
2608 features::kDebugHistoryInterventionNoUserActivation)) {
2609 return;
2610 }
2611
Shivani Sharmac4cc8922019-04-18 03:11:172612 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472613}
2614
clamy987a3752018-05-03 17:36:262615bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2616 RenderFrameHostImpl* render_frame_host,
Julie Jeongeun Kimed2e5ba72019-09-12 10:14:172617 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client) {
clamy987a3752018-05-03 17:36:262618 NavigationEntryImpl* entry =
2619 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2620 if (!entry)
2621 return false;
2622
2623 FrameNavigationEntry* frame_entry =
2624 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2625 if (!frame_entry)
2626 return false;
2627
Nate Chapin45f620582021-09-30 17:45:432628 // |is_browser_initiated| is false here because a navigation in a new subframe
2629 // always begins with renderer action (i.e., an HTML element being inserted
2630 // into the DOM), so it is always renderer-initiated.
Camille Lamy5193caa2018-10-12 11:59:422631 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572632 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232633 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432634 true /* is_history_navigation_in_new_child */,
2635 false /* is_browser_initiated */);
clamyea99ea12018-05-28 13:54:232636
2637 if (!request)
2638 return false;
2639
arthursonzognif046d4a2019-12-12 19:08:102640 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412641
Rakina Zata Amni1c83b082023-02-08 01:09:002642 SCOPED_CRASH_KEY_STRING256(
2643 "Bug1400009", "req_url",
2644 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2645 SCOPED_CRASH_KEY_NUMBER(
2646 "Bug1400009", "nav_entry_si",
2647 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2648 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2649 frame_entry->site_instance()
2650 ? ((int)frame_entry->site_instance()->GetId())
2651 : -1);
2652 bool has_sig =
2653 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2654 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2655 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2656 has_sig ? (!!frame_tree_->GetRenderViewHost(
2657 frame_entry->site_instance()->group()))
2658 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052659 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2660 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232661
2662 return true;
clamy987a3752018-05-03 17:36:262663}
2664
Tsuyoshi Horo52fd08e2020-07-07 07:03:452665bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2666 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2667 if (!entry)
2668 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432669
2670 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2671 // We should never navigate to an existing initial NavigationEntry that is
2672 // the initial NavigationEntry for the initial empty document that hasn't
2673 // been overridden by the synchronous about:blank commit, to preserve
2674 // legacy behavior where trying to reload when the main frame is on the
2675 // initial empty document won't result in a navigation. See also
2676 // https://crbug.com/1277414.
2677 return false;
2678 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452679 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2680 if (!frame_entry)
2681 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142682 ReloadType reload_type = ReloadType::NORMAL;
2683 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452684 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142685 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452686 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432687 false /* is_history_navigation_in_new_child */,
2688 true /* is_browser_initiated */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452689 if (!request)
2690 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052691 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452692 return true;
2693}
2694
clamy987a3752018-05-03 17:36:262695void NavigationControllerImpl::NavigateFromFrameProxy(
2696 RenderFrameHostImpl* render_frame_host,
2697 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022698 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452699 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072700 const absl::optional<url::Origin>& initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212701 const absl::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262702 bool is_renderer_initiated,
2703 SiteInstance* source_site_instance,
2704 const Referrer& referrer,
2705 ui::PageTransition page_transition,
2706 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252707 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262708 const std::string& method,
2709 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092710 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142711 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212712 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502713 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392714 const absl::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292715 blink::mojom::NavigationInitiatorActivationAndAdStatus
2716 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222717 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492718 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462719 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452720 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582721 bool is_container_initiated,
2722 absl::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582723 if (is_renderer_initiated)
2724 DCHECK(initiator_origin.has_value());
2725
clamy987a3752018-05-03 17:36:262726 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582727
Rakina Zata Amni2322f4f82022-01-24 13:24:242728 // Don't allow an entry replacement if there is no entry to replace.
2729 // http://crbug.com/457149
2730 if (GetEntryCount() == 0)
2731 should_replace_current_entry = false;
2732
clamy987a3752018-05-03 17:36:262733 // Create a NavigationEntry for the transfer, without making it the pending
2734 // entry. Subframe transfers should have a clone of the last committed entry
2735 // with a FrameNavigationEntry for the target frame. Main frame transfers
2736 // should have a new NavigationEntry.
2737 // TODO(creis): Make this unnecessary by creating (and validating) the params
2738 // directly, passing them to the destination RenderFrameHost. See
2739 // https://crbug.com/536906.
2740 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262741 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262742 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452743 DCHECK(GetLastCommittedEntry());
2744 entry = GetLastCommittedEntry()->Clone();
2745 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172746 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2747 // Renderer-initiated navigation that target a remote frame are currently
2748 // classified as browser-initiated when this one has already navigated.
2749 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372750 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2751 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2752 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2753 // same-document navigation), they will still be present in the
2754 // committed NavigationEntry that will be referenced to construct the new
2755 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262756 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082757 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582758 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072759 absl::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212760 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto22a27b142023-02-10 06:42:492761 blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482762 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori79d549d2021-02-18 12:59:542763 nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262764 } else {
2765 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172766 // If `node` is the outermost main frame, it rewrites a virtual url in order
2767 // to adjust the original input url if needed. For inner frames such as
2768 // fenced frames or subframes, they don't rewrite urls as the urls are not
2769 // input urls by users.
2770 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy987a3752018-05-03 17:36:262771 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212772 url, referrer, initiator_origin, initiator_base_url,
2773 source_site_instance, page_transition, is_renderer_initiated,
2774 extra_headers, browser_context_, blob_url_loader_factory,
2775 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262776 entry->root_node()->frame_entry->set_source_site_instance(
2777 static_cast<SiteInstanceImpl*>(source_site_instance));
2778 entry->root_node()->frame_entry->set_method(method);
2779 }
clamy987a3752018-05-03 17:36:262780
Camille Lamy5193caa2018-10-12 11:59:422781 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452782 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262783 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422784 override_user_agent = true;
clamy987a3752018-05-03 17:36:262785 }
2786 // TODO(creis): Set user gesture and intent received timestamp on Android.
2787
2788 // We may not have successfully added the FrameNavigationEntry to |entry|
2789 // above (per https://crbug.com/608402), in which case we create it from
2790 // scratch. This works because we do not depend on |frame_entry| being inside
2791 // |entry| during NavigateToEntry. This will go away when we shortcut this
2792 // further in https://crbug.com/536906.
2793 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2794 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452795 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082796 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582797 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072798 absl::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212799 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto22a27b142023-02-10 06:42:492800 blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482801 nullptr /* subresource_web_bundle_navigation_info */,
Nate Chapin63db0d12022-01-20 22:03:302802 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572803 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262804 }
2805
Camille Lamy5193caa2018-10-12 11:59:422806 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022807 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452808 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292809 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212810 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422811 params.source_site_instance = source_site_instance;
2812 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2813 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032814 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422815 params.referrer = referrer;
2816 /* params.redirect_chain: skip */
2817 params.extra_headers = extra_headers;
2818 params.is_renderer_initiated = is_renderer_initiated;
2819 params.override_user_agent = UA_OVERRIDE_INHERIT;
2820 /* params.base_url_for_data_url: skip */
2821 /* params.virtual_url_for_data_url: skip */
2822 /* params.data_url_as_string: skip */
2823 params.post_data = post_body;
2824 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582825 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422826 /* params.frame_name: skip */
2827 // TODO(clamy): See if user gesture should be propagated to this function.
2828 params.has_user_gesture = false;
2829 params.should_clear_history_list = false;
2830 params.started_from_context_menu = false;
2831 /* params.navigation_ui_data: skip */
2832 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222833 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542834 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212835 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412836 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502837 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292838 params.initiator_activation_and_ad_status =
2839 initiator_activation_and_ad_status;
Camille Lamy5193caa2018-10-12 11:59:422840
2841 std::unique_ptr<NavigationRequest> request =
2842 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032843 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142844 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392845 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492846 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582847 is_unfenced_top_navigation, is_container_initiated,
2848 embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232849
2850 if (!request)
2851 return;
2852
Garrett Tanzerbb8db412022-09-27 21:59:462853 // Force the navigation to take place in a new browsing instance.
2854 // This is used by _unfencedTop in fenced frames to ensure that navigations
2855 // leaving the fenced context create a new browsing instance.
2856 if (force_new_browsing_instance) {
2857 request->coop_status().ForceBrowsingInstanceSwap();
2858 }
2859
Arthur Hemery948742762019-09-18 10:06:242860 // At this stage we are proceeding with this navigation. If this was renderer
2861 // initiated with user gesture, we need to make sure we clear up potential
2862 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2863 DiscardNonCommittedEntries();
2864
Lukasz Anforowicz9ee83c272020-12-01 20:14:052865 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262866}
2867
[email protected]d1198fd2012-08-13 22:50:192868void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252869 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212870 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192871 if (!session_storage_namespace)
2872 return;
2873
2874 // We can't overwrite an existing SessionStorage without violating spec.
2875 // Attempts to do so may give a tab access to another tab's session storage
2876 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152877 bool successful_insert =
2878 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252879 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052880 static_cast<SessionStorageNamespaceImpl*>(
2881 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302882 .second;
2883 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192884}
2885
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572886bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452887 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032888 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462889}
2890
Aran Gilman37d11632019-10-08 23:07:152891SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252892 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302893 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252894 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032895 DOMStorageContextWrapper* context_wrapper =
2896 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2897
2898 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252899 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032900 if (it != session_storage_namespace_map_.end()) {
2901 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152902 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2903 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472904
michaelnbacbcbd2016-02-09 00:32:032905 return it->second.get();
2906 }
2907
2908 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102909 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2910 SessionStorageNamespaceImpl::Create(context_wrapper);
2911 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2912 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252913 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102914 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302915
Daniel Murphy31bbb8b12018-02-07 21:44:102916 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302917}
2918
2919SessionStorageNamespace*
2920NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252921 return GetSessionStorageNamespace(
2922 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302923}
2924
2925const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572926NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302927 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552928}
[email protected]d202a7c2012-01-04 07:53:472929
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572930bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562931 return needs_reload_;
2932}
[email protected]a26023822011-12-29 00:23:552933
[email protected]46bb5e9c2013-10-03 22:16:472934void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412935 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2936}
2937
2938void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472939 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412940 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542941
2942 if (last_committed_entry_index_ != -1) {
2943 entries_[last_committed_entry_index_]->SetTransitionType(
2944 ui::PAGE_TRANSITION_RELOAD);
2945 }
[email protected]46bb5e9c2013-10-03 22:16:472946}
2947
[email protected]d202a7c2012-01-04 07:53:472948void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572949 DCHECK_LT(index, GetEntryCount());
2950 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312951 DiscardNonCommittedEntries();
2952
Nate Chapin9eb16be72022-09-23 22:54:312953 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:312954 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122955 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312956 last_committed_entry_index_--;
2957}
2958
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572959NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272960 // If there is no pending_entry_, there should be no pending_entry_index_.
2961 DCHECK(pending_entry_ || pending_entry_index_ == -1);
2962
2963 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:362964 // at that index. An exception is while a reload of a post commit error page
2965 // is ongoing; in that case pending entry will point to the entry replaced
2966 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:272967 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:362968 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
2969 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:272970
[email protected]022af742011-12-28 18:37:252971 return pending_entry_;
2972}
2973
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572974int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:272975 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:272976 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:552977 return pending_entry_index_;
2978}
2979
avi25764702015-06-23 15:43:372980void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:572981 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:362982 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:312983 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:002984 bool in_fenced_frame_tree,
2985 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:312986 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
2987 // set because:
2988 // 1) They don't influence the history of the outer page.
2989 // 2) They are always replace only navigation (there is always only one entry
2990 // in their history stack).
2991 // 3) Are not top level navigations and appear similar to iframes.
2992 // Navigations of the fenced frame might create a new NavigationEntry, which
2993 // will call this function. Non fenced frame navigations will never have
2994 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
2995 // InsertOrReplaceEntry.
2996 DCHECK_EQ(in_fenced_frame_tree,
2997 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
2998 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:202999
avi5cad4912015-06-19 05:25:443000 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3001 // need to keep continuity with the pending entry, so copy the pending entry's
3002 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3003 // then the renderer navigated on its own, independent of the pending entry,
3004 // so don't copy anything.
3005 if (pending_entry_ && pending_entry_index_ == -1)
3006 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203007
Rakina Zata Amnia4e27222021-12-22 01:05:003008 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203009
creisee17e932015-07-17 17:56:223010 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453011 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103012 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573013 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363014 // If the new entry is a post-commit error page, we store the current last
3015 // committed entry to the side so that we can put it back when navigating
3016 // away from the error.
3017 if (was_post_commit_error) {
3018 DCHECK(!entry_replaced_by_post_commit_error_);
3019 entry_replaced_by_post_commit_error_ =
3020 std::move(entries_[last_committed_entry_index_]);
3021 }
dcheng36b6aec92015-12-26 06:16:363022 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223023 return;
3024 }
[email protected]765b35502008-08-21 00:51:203025
creis37979a62015-08-04 19:48:183026 // We shouldn't see replace == true when there's no committed entries.
3027 DCHECK(!replace);
3028
Michael Thiessen9b14d512019-09-23 21:19:473029 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203030
Shivani Sharmad8c8d652019-02-13 17:27:573031 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203032
dcheng36b6aec92015-12-26 06:16:363033 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203034 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293035}
3036
Shivani Sharmad8c8d652019-02-13 17:27:573037void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163038 if (entries_.size() < max_entry_count())
3039 return;
3040
3041 DCHECK_EQ(max_entry_count(), entries_.size());
3042 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573043 CHECK_EQ(pending_entry_index_, -1);
3044
3045 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423046 // Retrieve the oldest skippable entry.
3047 for (; index < GetEntryCount(); index++) {
3048 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3049 break;
Shivani Sharmad8c8d652019-02-13 17:27:573050 }
3051
3052 // If there is no skippable entry or if it is the last committed entry then
3053 // fall back to pruning the oldest entry. It is not safe to prune the last
3054 // committed entry.
3055 if (index == GetEntryCount() || index == last_committed_entry_index_)
3056 index = 0;
3057
3058 bool should_succeed = RemoveEntryAtIndex(index);
3059 DCHECK_EQ(true, should_succeed);
3060
3061 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253062}
3063
clamy3cb9bea92018-07-10 12:42:023064void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163065 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203066 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:133067 absl::optional<blink::scheduler::TaskAttributionId>
3068 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203069 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503070 TRACE_EVENT0("navigation",
3071 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273072 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023073 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363074 if (pending_entry_index_ != -1) {
3075 // The pending entry may not be in entries_ if a post-commit error page is
3076 // showing.
3077 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3078 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3079 }
Gyuyoung Kim107c2a02021-04-13 01:49:303080 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573081 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013082 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033083 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573084 int nav_entry_id = pending_entry_->GetUniqueID();
Nate Chapinbf682fa32022-09-26 22:41:203085 bool is_browser_initiated = !initiator_rfh;
Yoav Weiss8c573952022-11-17 17:35:133086 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3087 // the same as the top level frame being navigated.
3088 if (root->current_frame_host() != initiator_rfh) {
3089 soft_navigation_heuristics_task_id = absl::nullopt;
3090 }
Arthur Sonzogni620cec62018-12-13 13:08:573091
[email protected]83c2e232011-10-07 21:36:463092 // If we were navigating to a slow-to-commit page, and the user performs
3093 // a session history navigation to the last committed page, RenderViewHost
3094 // will force the throbber to start, but WebKit will essentially ignore the
3095 // navigation, and won't send a message to stop the throbber. To prevent this
3096 // from happening, we drop the navigation here and stop the slow-to-commit
3097 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023098 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083099 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273100 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033101 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123102
[email protected]83c2e232011-10-07 21:36:463103 DiscardNonCommittedEntries();
3104 return;
3105 }
3106
creisce0ef3572017-01-26 17:53:083107 // Compare FrameNavigationEntries to see which frames in the tree need to be
3108 // navigated.
clamy3cb9bea92018-07-10 12:42:023109 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3110 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Nate Chapin45f620582021-09-30 17:45:433111 FindFramesToNavigate(root, reload_type, is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133112 soft_navigation_heuristics_task_id, &same_document_loads,
3113 &different_document_loads);
creis4e2ecb72015-06-20 00:46:303114
3115 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573116 // We were unable to match any frames to navigate. This can happen if a
3117 // history navigation targets a subframe that no longer exists
3118 // (https://crbug.com/705550). In this case, we need to update the current
3119 // history entry to the pending one but keep the main document loaded. We
3120 // also need to ensure that observers are informed about the updated
3121 // current history entry (e.g., for greying out back/forward buttons), and
3122 // that renderer processes update their history offsets. The easiest way
3123 // to do all that is to schedule a "redundant" same-document navigation in
3124 // the main frame.
3125 //
3126 // Note that we don't want to remove this history entry, as it might still
3127 // be valid later, since a frame that it's targeting may be recreated.
3128 //
3129 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3130 // need to repeat history navigations until finding the one that works.
3131 // Consider changing this behavior to keep looking for the first valid
3132 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023133 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423134 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573135 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573136 ReloadType::NONE /* reload_type */,
3137 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433138 false /* is_history_navigation_in_new_child */,
3139 is_browser_initiated);
clamy3cb9bea92018-07-10 12:42:023140 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573141 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023142 DiscardPendingEntry(false);
3143 return;
3144 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573145 same_document_loads.push_back(std::move(navigation_request));
3146
3147 // Sanity check that we never take this branch for any kinds of reloads,
3148 // as those should've queued a different-document load in the main frame.
3149 DCHECK(!is_forced_reload);
3150 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303151 }
3152
Nate Chapinbf682fa32022-09-26 22:41:203153 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163154 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203155 if (initiator_rfh && initiator_rfh->IsSandboxed(
3156 network::mojom::WebSandboxFlags::kTopNavigation)) {
3157 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3158 initiator_rfh, same_document_loads) &&
3159 DoesSandboxNavigationStayWithinSubtree(
3160 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503161 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163162 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203163 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3164 initiator_rfh,
3165 navigates_inside_tree
3166 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3167 : blink::mojom::WebFeature::
3168 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523169
3170 // If the navigation occurred outside the tree discard it because
3171 // the sandboxed frame didn't have permission to navigate outside
3172 // its tree. If it is possible that the navigation is both inside and
3173 // outside the frame tree and we discard it entirely because we don't
3174 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143175 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203176 // If a |navigation_api_key| was provided, this navigation originated from
3177 // the navigation API. Notify the renderer that the navigation was
3178 // cancelled so the navigation API can fire an error event and reject the
3179 // relevant promise.
3180 if (navigation_api_key) {
3181 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3182 *navigation_api_key,
3183 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3184 }
Dave Tapuska855c1e12019-08-23 20:45:523185 DiscardPendingEntry(false);
3186 return;
3187 }
Dave Tapuska8bfd84c2019-03-26 20:47:163188 }
3189
Nate Chapin6c43c022023-02-13 23:32:423190 // If it is possible that this traverse may involve a same-document navigation
3191 // in the initiator and there is a Navigation API key involved, then we may
3192 // need to notify the initiator if it fails. (The early returns above either
3193 // do not involve these cases or already notify the initiator.)
3194 // The event only needs to fire for the initiator, and only if the initiator
3195 // itself is performing a same-document navigation (because the event will not
3196 // fire if it navigates cross-document).
3197 if (navigation_api_key) {
3198 for (auto& item : same_document_loads) {
3199 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3200 item->set_pending_navigation_api_key(*navigation_api_key);
3201 break;
3202 }
3203 }
3204 }
3205
Carlos Caballero539a421c2020-07-06 10:25:573206 // BackForwardCache:
3207 // Navigate immediately if the document is in the BackForwardCache.
3208 if (back_forward_cache_.GetEntry(nav_entry_id)) {
3209 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3210 DCHECK_EQ(reload_type, ReloadType::NONE);
3211 auto navigation_request = CreateNavigationRequestFromEntry(
3212 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3213 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433214 false /* is_history_navigation_in_new_child */, is_browser_initiated);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053215 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573216
3217 return;
3218 }
3219
3220 // History navigation might try to reuse a specific BrowsingInstance, already
3221 // used by a page in the cache. To avoid having two different main frames that
3222 // live in the same BrowsingInstance, evict the all pages with this
3223 // BrowsingInstance from the cache.
3224 //
3225 // For example, take the following scenario:
3226 //
3227 // A1 = Some page on a.com
3228 // A2 = Some other page on a.com
3229 // B3 = An uncacheable page on b.com
3230 //
3231 // Then the following navigations occur:
3232 // A1->A2->B3->A1
3233 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3234 // take its place) and A1 will be created in the same BrowsingInstance (and
3235 // SiteInstance), as A2.
3236 //
3237 // If we didn't do anything, both A1 and A2 would remain alive in the same
3238 // BrowsingInstance/SiteInstance, which is unsupported by
3239 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3240 // A2 from the cache.
3241 if (pending_entry_->site_instance()) {
3242 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3243 pending_entry_->site_instance());
3244 }
3245
Rakina Zata Amnid605d462022-06-01 10:17:033246 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3247 pending_entry_ && pending_entry_->IsRestored());
3248 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3249 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3250 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3251 pending_entry_index_);
3252 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3253 last_committed_entry_index_);
3254 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3255 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3256 pending_entry_ && pending_entry_->IsInitialEntry());
3257 SCOPED_CRASH_KEY_BOOL(
3258 "nav_reentrancy", "pending_entry_initial2",
3259 pending_entry_ &&
3260 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3261 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3262 IsInitialNavigation());
3263 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3264 IsInitialBlankNavigation());
3265 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3266 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3267 (int)pending_reload_);
3268
clamy3cb9bea92018-07-10 12:42:023269 // This call does not support re-entrancy. See http://crbug.com/347742.
3270 CHECK(!in_navigate_to_pending_entry_);
3271 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303272
Rakina Zata Amnid605d462022-06-01 10:17:033273 // If the navigation-reentrancy is caused by calling
3274 // NavigateToExistingPendingEntry twice, this will note the previous call's
3275 // pending entry's ID.
3276 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3277 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3278
arthursonzogni66f711c2019-10-08 14:40:363279 // It is not possible to delete the pending NavigationEntry while navigating
3280 // to it. Grab a reference to delay potential deletion until the end of this
3281 // function.
3282 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3283
Nate Chapin154b14b2023-02-17 18:28:163284 // If there is a main-frame same-document history navigation, we may defer
3285 // the subframe history navigations in order to give JS in the main frame the
3286 // opportunity to cancel the entire traverse via the navigate event. In that
3287 // case, we need to stash the main frame request's navigation token on the
3288 // subframes, so they can look up the main frame request and defer themselves
3289 // until it completes.
3290 if (!same_document_loads.empty() &&
3291 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3292 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3293 // The token will only be returned in cases where deferring the navigation
3294 // is necessary.
3295 if (auto main_frame_same_document_token =
3296 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3297 for (auto& item : same_document_loads) {
3298 if (item.get() != main_frame_request) {
3299 item->set_main_frame_same_document_history_token(
3300 main_frame_same_document_token);
3301 }
3302 }
3303 for (auto& item : different_document_loads) {
3304 item->set_main_frame_same_document_history_token(
3305 main_frame_same_document_token);
3306 }
3307 }
3308 }
3309
creis4e2ecb72015-06-20 00:46:303310 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023311 for (auto& item : same_document_loads) {
3312 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053313 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303314 }
clamy3cb9bea92018-07-10 12:42:023315 for (auto& item : different_document_loads) {
3316 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053317 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303318 }
clamy3cb9bea92018-07-10 12:42:023319
3320 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303321}
3322
Alex Moshchuk3a4e77a2020-05-29 21:32:573323NavigationControllerImpl::HistoryNavigationAction
3324NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303325 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573326 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423327 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583328 // Only active and prerendered documents are allowed to navigate in their
3329 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423330 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013331 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583332 // - If the document is in pending deletion, the browser already committed
3333 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3334 // - If the document is in back-forward cache, it's not allowed to navigate
3335 // as it should remain frozen. Ignore the request and evict the document
3336 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423337 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583338 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423339 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113340 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3341 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423342 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113343 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423344 }
arthursonzogni03f76152019-02-12 10:35:203345
Alex Moshchuk3a4e77a2020-05-29 21:32:573346 // Reloads should result in a different-document load. Note that reloads may
3347 // also happen via the |needs_reload_| mechanism where the reload_type is
3348 // NONE, so detect this by comparing whether we're going to the same
3349 // entry that we're currently on. Similarly to above, only main frames
3350 // should reach this. Note that subframes support reloads, but that's done
3351 // via a different path that doesn't involve FindFramesToNavigate (see
3352 // RenderFrameHost::Reload()).
3353 if (reload_type != ReloadType::NONE ||
3354 pending_entry_index_ == last_committed_entry_index_) {
3355 DCHECK(frame->IsMainFrame());
3356 return HistoryNavigationAction::kDifferentDocument;
3357 }
3358
Alex Moshchuk47d1a4bd2020-06-01 22:15:343359 // If there is no new FrameNavigationEntry for the frame, ignore the
3360 // load. For example, this may happen when going back to an entry before a
3361 // frame was created. Suppose we commit a same-document navigation that also
3362 // results in adding a new subframe somewhere in the tree. If we go back,
3363 // the new subframe will be missing a FrameNavigationEntry in the previous
3364 // NavigationEntry, but we shouldn't delete or change what's loaded in
3365 // it.
3366 //
Alex Moshchuke65c39272020-06-03 17:55:373367 // Note that in this case, there is no need to keep looking for navigations
3368 // in subframes, which would be missing FrameNavigationEntries as well.
3369 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343370 // It's important to check this before checking |old_item| below, since both
3371 // might be null, and in that case we still shouldn't change what's loaded in
3372 // this frame. Note that scheduling any loads assumes that |new_item| is
3373 // non-null. See https://crbug.com/1088354.
3374 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3375 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373376 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343377
Charlie Reisa474fb62022-03-17 02:31:363378 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3379 // which history item it is currently on, since this may be different than the
3380 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3381 // (e.g., if a history navigation is targeting multiple frames and only some
3382 // have committed so far).
creis4e2ecb72015-06-20 00:46:303383 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363384 frame->current_frame_host()->last_committed_frame_entry();
3385 if (!old_item) {
3386 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3387 // fall back to the last committed NavigationEntry's record for this frame.
3388 // This may happen in cases like the initial state of the RenderFrameHost.
3389 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3390 // accurate FrameNavigationEntry and eliminate this case.
3391 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3392 }
3393 // If neither approach finds a FrameNavigationEntry, schedule a
3394 // different-document load.
3395 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573396 if (!old_item)
3397 return HistoryNavigationAction::kDifferentDocument;
3398
Alex Moshchuk3a4e77a2020-05-29 21:32:573399 // If the new item is not in the same SiteInstance, schedule a
3400 // different-document load. Newly restored items may not have a SiteInstance
3401 // yet, in which case it will be assigned on first commit.
3402 if (new_item->site_instance() &&
3403 new_item->site_instance() != old_item->site_instance())
3404 return HistoryNavigationAction::kDifferentDocument;
3405
3406 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313407 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3408 // that we do this even if the history navigation would not be modifying this
3409 // frame were it live.
3410 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573411 return HistoryNavigationAction::kDifferentDocument;
3412
3413 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313414 // Starting a navigation after a crash early-promotes the speculative
3415 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3416 // committed yet, so we can not possibly perform a same-document history
3417 // navigation. The frame would need to be reloaded with a cross-document
3418 // navigation.
3419 if (!frame->current_frame_host()->has_committed_any_navigation())
3420 return HistoryNavigationAction::kDifferentDocument;
3421
creis54131692016-08-12 18:32:253422 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493423 // sequence number but different item sequence number.
3424 if (new_item->document_sequence_number() ==
3425 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573426 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493427 }
avib48cb312016-05-05 21:35:003428
Alex Moshchuk3a4e77a2020-05-29 21:32:573429 // Otherwise, if both item and document sequence numbers differ, this
3430 // should be a different document load.
3431 return HistoryNavigationAction::kDifferentDocument;
3432 }
3433
3434 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373435 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573436 DCHECK_EQ(new_item->document_sequence_number(),
3437 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373438 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573439}
3440
3441void NavigationControllerImpl::FindFramesToNavigate(
3442 FrameTreeNode* frame,
3443 ReloadType reload_type,
Nate Chapin45f620582021-09-30 17:45:433444 bool is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133445 absl::optional<blink::scheduler::TaskAttributionId>
3446 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573447 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3448 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3449 DCHECK(pending_entry_);
3450 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3451
3452 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3453
3454 if (action == HistoryNavigationAction::kSameDocument) {
3455 std::unique_ptr<NavigationRequest> navigation_request =
3456 CreateNavigationRequestFromEntry(
3457 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133458 /*is_same_document_history_load=*/true,
3459 /*is_history_navigation_in_new_child_frame=*/false,
3460 is_browser_initiated, soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573461 if (navigation_request) {
3462 // Only add the request if was properly created. It's possible for the
3463 // creation to fail in certain cases, e.g. when the URL is invalid.
3464 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303465 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573466 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473467 std::unique_ptr<NavigationRequest> navigation_request =
3468 CreateNavigationRequestFromEntry(
3469 frame, pending_entry_, new_item, reload_type,
3470 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433471 false /* is_history_navigation_in_new_child */,
3472 is_browser_initiated);
Lei Zhang96031532019-10-10 19:05:473473 if (navigation_request) {
3474 // Only add the request if was properly created. It's possible for the
3475 // creation to fail in certain cases, e.g. when the URL is invalid.
3476 different_document_loads->push_back(std::move(navigation_request));
3477 }
3478 // For a different document, the subframes will be destroyed, so there's
3479 // no need to consider them.
3480 return;
Alex Moshchuke65c39272020-06-03 17:55:373481 } else if (action == HistoryNavigationAction::kStopLooking) {
3482 return;
creis4e2ecb72015-06-20 00:46:303483 }
3484
Yoav Weiss8c573952022-11-17 17:35:133485 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3486 // we currently only support soft navigation heuristics for the top level
3487 // frame.
creis4e2ecb72015-06-20 00:46:303488 for (size_t i = 0; i < frame->child_count(); i++) {
Nate Chapin45f620582021-09-30 17:45:433489 FindFramesToNavigate(frame->child_at(i), reload_type, is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133490 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
Nate Chapin45f620582021-09-30 17:45:433491 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303492 }
3493}
3494
Harkiran Bolariaba823e42021-05-21 18:30:363495base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243496 const LoadURLParams& params) {
3497 // Find the appropriate FrameTreeNode.
3498 FrameTreeNode* node = nullptr;
3499 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3500 !params.frame_name.empty()) {
3501 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033502 ? frame_tree_->FindByID(params.frame_tree_node_id)
3503 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503504 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243505 }
3506
3507 // If no FrameTreeNode was specified, navigate the main frame.
3508 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033509 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243510
Camille Lamy5193caa2018-10-12 11:59:423511 // Compute overrides to the LoadURLParams for |override_user_agent|,
3512 // |should_replace_current_entry| and |has_user_gesture| that will be used
3513 // both in the creation of the NavigationEntry and the NavigationRequest.
3514 // Ideally, the LoadURLParams themselves would be updated, but since they are
3515 // passed as a const reference, this is not possible.
3516 // TODO(clamy): When we only create a NavigationRequest, move this to
3517 // CreateNavigationRequestFromLoadURLParams.
3518 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3519 GetLastCommittedEntry());
3520
Rakina Zata Amnie2d31312022-11-18 03:38:453521 // An entry replacement must happen if the current browsing context should
3522 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333523 bool should_replace_current_entry =
3524 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453525 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423526
clamy21718cc22018-06-13 13:34:243527 // Javascript URLs should not create NavigationEntries. All other navigations
3528 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243529 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373530 std::unique_ptr<NavigationEntryImpl> entry =
3531 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3532 should_replace_current_entry,
3533 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243534 DiscardPendingEntry(false);
3535 SetPendingEntry(std::move(entry));
3536 }
3537
3538 // Renderer-debug URLs are sent to the renderer process immediately for
3539 // processing and don't need to create a NavigationRequest.
3540 // Note: this includes navigations to JavaScript URLs, which are considered
3541 // renderer-debug URLs.
3542 // Note: we intentionally leave the pending entry in place for renderer debug
3543 // URLs, unlike the cases below where we clear it if the navigation doesn't
3544 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303545 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483546 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3547 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153548 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Oleg Davydov2cc0167b2019-02-05 14:32:483549 params.url, browser_context_)) {
3550 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363551 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483552 }
3553
clamy21718cc22018-06-13 13:34:243554 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363555 return nullptr;
clamy21718cc22018-06-13 13:34:243556 }
3557
Antonio Sartori78a749f2020-11-30 12:03:393558 DCHECK(pending_entry_);
3559
clamy21718cc22018-06-13 13:34:243560 // Convert navigations to the current URL to a reload.
3561 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3562 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3563 // DevTools sometimes issues navigations to main frames that they do not
3564 // expect to see treated as reload, and it only works because they pass a
3565 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3566 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543567 ReloadType reload_type = params.reload_type;
3568 if (reload_type == ReloadType::NONE &&
3569 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043570 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243571 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243572 params.load_type ==
3573 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543574 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243575 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473576 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393577
3578 // If this is a reload of an existing FrameNavigationEntry and we had a
3579 // policy container for it, then we should copy it into the pending entry,
3580 // so that it is copied to the navigation request in
3581 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453582 FrameNavigationEntry* previous_frame_entry =
3583 GetLastCommittedEntry()->GetFrameEntry(node);
3584 if (previous_frame_entry &&
3585 previous_frame_entry->policy_container_policies()) {
3586 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3587 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393588 }
3589 }
3590
3591 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173592 // document, then we should copy the document polices from RenderFrameHost's
3593 // PolicyContainerHost. The NavigationRequest will create a new
3594 // PolicyContainerHost with the document policies from the |pending_entry_|,
3595 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3596 // the navigation. This way, we ensure that we keep enforcing the right
3597 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453598 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393599 if (node->current_frame_host() &&
3600 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193601 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163602 node->current_frame_host()
3603 ->policy_container_host()
3604 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233605 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393606 }
clamy21718cc22018-06-13 13:34:243607 }
3608
3609 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263610 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243611
Tsuyoshi Horo167ca6432022-03-09 05:16:393612 // This will be used to set the Navigation Timing API navigationStart
3613 // parameter for browser navigations in new tabs (intents, tabs opened through
3614 // "Open link in new tab"). If the navigation must wait on the current
3615 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3616 // will be updated when the BeforeUnload ack is received.
3617 const auto navigation_start_time = base::TimeTicks::Now();
3618
Camille Lamy5193caa2018-10-12 11:59:423619 std::unique_ptr<NavigationRequest> request =
3620 CreateNavigationRequestFromLoadParams(
3621 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143622 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393623 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3624 navigation_start_time);
clamy21718cc22018-06-13 13:34:243625
3626 // If the navigation couldn't start, return immediately and discard the
3627 // pending NavigationEntry.
3628 if (!request) {
3629 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363630 return nullptr;
clamy21718cc22018-06-13 13:34:243631 }
3632
Camille Lamy5193caa2018-10-12 11:59:423633#if DCHECK_IS_ON()
3634 // Safety check that NavigationRequest and NavigationEntry match.
3635 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3636#endif
3637
clamy21718cc22018-06-13 13:34:243638 // This call does not support re-entrancy. See http://crbug.com/347742.
3639 CHECK(!in_navigate_to_pending_entry_);
3640 in_navigate_to_pending_entry_ = true;
3641
arthursonzogni66f711c2019-10-08 14:40:363642 // It is not possible to delete the pending NavigationEntry while navigating
3643 // to it. Grab a reference to delay potential deletion until the end of this
3644 // function.
3645 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3646
Harkiran Bolariaba823e42021-05-21 18:30:363647 base::WeakPtr<NavigationHandle> created_navigation_handle(
3648 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053649 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243650
3651 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363652 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243653}
3654
clamyea99ea12018-05-28 13:54:233655void NavigationControllerImpl::HandleRendererDebugURL(
3656 FrameTreeNode* frame_tree_node,
3657 const GURL& url) {
3658 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243659 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3660 // the renderer process is not live, unless it is the initial navigation
3661 // of the tab.
clamyea99ea12018-05-28 13:54:233662 if (!IsInitialNavigation()) {
3663 DiscardNonCommittedEntries();
3664 return;
3665 }
Fergal Dalyecd3b0202020-06-25 01:57:373666 // The current frame is always a main frame. If IsInitialNavigation() is
3667 // true then there have been no navigations and any frames of this tab must
3668 // be in the same renderer process. If that has crashed then the only frame
3669 // that can be revived is the main frame.
3670 frame_tree_node->render_manager()
3671 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233672 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223673
3674 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3675 // notification, so set is loading to true here to properly surface it when
3676 // the renderer process is done handling the URL.
3677 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3678 if (!url.SchemeIs(url::kJavaScriptScheme)) {
3679 bool was_loading = frame_tree_node->frame_tree()
Arthur Sonzognif6785ec2022-12-05 10:11:503680 .LoadingTree()
Julie Jeongeun Kim50d124c2022-10-21 13:51:223681 ->IsLoadingIncludingInnerFrameTrees();
3682 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
3683 frame_tree_node->DidStartLoading(true /* should_show_loading_ui */,
3684 was_loading);
3685 }
clamyea99ea12018-05-28 13:54:233686 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3687}
3688
clamy21718cc22018-06-13 13:34:243689std::unique_ptr<NavigationEntryImpl>
3690NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3691 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423692 const LoadURLParams& params,
3693 bool override_user_agent,
3694 bool should_replace_current_entry,
3695 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393696 // Browser initiated navigations might not have a blob_url_loader_factory set
3697 // in params even if the navigation is to a blob URL. If that happens, lookup
3698 // the correct url loader factory to use here.
3699 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483700 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473701 // Resolve the blob URL in the storage partition associated with the target
3702 // frame. This is the storage partition the URL will be loaded in, and only
3703 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393704 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473705 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393706 }
3707
clamy21718cc22018-06-13 13:34:243708 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443709 // extra_headers in params are \n separated; navigation entries want \r\n.
3710 std::string extra_headers_crlf;
3711 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243712
3713 // For subframes, create a pending entry with a corresponding frame entry.
3714 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453715 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243716 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083717 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243718 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073719 params.url, absl::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213720 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3721 "GET", -1, blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:483722 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori78a749f2020-11-30 12:03:393723 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163724 // a conversion of a new navigation into a reload, we will set the right
3725 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193726 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243727 } else {
3728 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173729 // If `node` is the outermost main frame, it rewrites a virtual url in order
3730 // to adjust the original input url if needed. For inner frames such as
3731 // fenced frames or subframes, they don't rewrite urls as the urls are not
3732 // input urls by users.
3733 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy21718cc22018-06-13 13:34:243734 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063735 params.url, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213736 params.initiator_base_url, params.source_site_instance.get(),
3737 params.transition_type, params.is_renderer_initiated,
3738 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3739 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243740 entry->set_source_site_instance(
3741 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3742 entry->SetRedirectChain(params.redirect_chain);
3743 }
3744
3745 // Set the FTN ID (only used in non-site-per-process, for tests).
3746 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243747 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423748 entry->SetIsOverridingUserAgent(override_user_agent);
3749 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543750 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243751
clamy21718cc22018-06-13 13:34:243752 switch (params.load_type) {
3753 case LOAD_TYPE_DEFAULT:
3754 break;
3755 case LOAD_TYPE_HTTP_POST:
3756 entry->SetHasPostData(true);
3757 entry->SetPostData(params.post_data);
3758 break;
3759 case LOAD_TYPE_DATA:
3760 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3761 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283762#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243763 entry->SetDataURLAsString(params.data_url_as_string);
3764#endif
3765 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3766 break;
clamy21718cc22018-06-13 13:34:243767 }
3768
3769 // TODO(clamy): NavigationEntry is meant for information that will be kept
3770 // after the navigation ended and therefore is not appropriate for
3771 // started_from_context_menu. Move started_from_context_menu to
3772 // NavigationUIData.
3773 entry->set_started_from_context_menu(params.started_from_context_menu);
3774
3775 return entry;
3776}
3777
clamyea99ea12018-05-28 13:54:233778std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423779NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3780 FrameTreeNode* node,
3781 const LoadURLParams& params,
3782 bool override_user_agent,
3783 bool should_replace_current_entry,
3784 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143785 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423786 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573787 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393788 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223789 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493790 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453791 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583792 bool is_container_initiated,
3793 absl::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573794 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283795 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533796 // All renderer-initiated navigations must have an initiator_origin.
3797 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513798
Camille Lamy5193caa2018-10-12 11:59:423799 GURL url_to_load;
3800 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323801
Camille Lamy2baa8022018-10-19 16:43:173802 // For main frames, rewrite the URL if necessary and compute the virtual URL
3803 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263804 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423805 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173806 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423807 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423808
Camille Lamy2baa8022018-10-19 16:43:173809 // For DATA loads, override the virtual URL.
3810 if (params.load_type == LOAD_TYPE_DATA)
3811 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423812
Camille Lamy2baa8022018-10-19 16:43:173813 if (virtual_url.is_empty())
3814 virtual_url = url_to_load;
3815
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573816 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283817
Aran Gilman249eb122019-12-02 23:32:463818 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3819 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3820 // return different results, leading to a different URL in the
3821 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3822 // pending NavigationEntry, as we'll only make one call to
3823 // RewriteUrlForNavigation.
3824 VLOG_IF(1, (url_to_load != frame_entry->url()))
3825 << "NavigationRequest and FrameEntry have different URLs: "
3826 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283827
Camille Lamy2baa8022018-10-19 16:43:173828 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423829 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173830 // NavigationRequest.
3831 } else {
3832 url_to_load = params.url;
3833 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243834 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173835 }
Camille Lamy5193caa2018-10-12 11:59:423836
Ehsan Karamad44fc72112019-02-26 18:15:473837 if (node->render_manager()->is_attaching_inner_delegate()) {
3838 // Avoid starting any new navigations since this node is now preparing for
3839 // attaching an inner delegate.
3840 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203841 }
Camille Lamy5193caa2018-10-12 11:59:423842
Ian Vollick1c6dd3e2022-04-13 02:06:263843 if (!IsValidURLForNavigation(node->IsOutermostMainFrame(), virtual_url,
3844 url_to_load))
Camille Lamy5193caa2018-10-12 11:59:423845 return nullptr;
3846
danakjd83d706d2020-11-25 22:11:123847 // Look for a pending commit that is to another document in this
3848 // FrameTreeNode. If one exists, then the last committed URL will not be the
3849 // current URL by the time this navigation commits.
3850 bool has_pending_cross_document_commit =
3851 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213852 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123853
Minggang Wangb9f3fa92021-07-01 15:30:313854 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493855 /*old_url=*/node->current_url(),
3856 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3857 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133858 /*is_same_document_history_load=*/false,
3859 is_embedder_initiated_fenced_frame_navigation,
3860 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423861
3862 // Create the NavigationParams based on |params|.
3863
Hiroki Nakagawa4ed61282021-06-18 05:37:233864 bool is_view_source_mode = entry->IsViewSourceMode();
3865 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293866
Antonio Sartori6984c742021-08-26 08:03:413867 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:293868
Hiroki Nakagawa4ed61282021-06-18 05:37:233869 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293870 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253871 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293872
Minggang Wangb9f3fa92021-07-01 15:30:313873 blink::mojom::CommonNavigationParamsPtr common_params =
3874 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:213875 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513876 blink::mojom::Referrer::New(params.referrer.url,
3877 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213878 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513879 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393880 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513881 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143882 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413883 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273884 false /* has_text_fragment_token */,
3885 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3886 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513887 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:053888 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423889
Minggang Wangb9f3fa92021-07-01 15:30:313890 blink::mojom::CommitNavigationParamsPtr commit_params =
3891 blink::mojom::CommitNavigationParams::New(
Rakina Zata Amnic7367852022-11-07 17:10:403892 absl::nullopt,
Ari Chivukula43d2cf82023-01-24 03:16:073893 // The correct storage key and session storage key will be computed
3894 // before committing the navigation.
3895 blink::StorageKey(), blink::StorageKey(), override_user_agent,
3896 params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323897 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503898 std::vector<net::RedirectInfo>(), params.post_content_type,
3899 common_params->url, common_params->method,
3900 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313901 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133902 entry->GetSubframeUniqueNames(node),
3903 /*intended_as_new_entry=*/true,
3904 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143905 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3906 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:133907 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313908 params.should_clear_history_list,
3909 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223910 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:133911 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:513912 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283913#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:133914 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143915#endif
Yoav Weiss8c573952022-11-17 17:35:133916 /*is_browser_initiated=*/!params.is_renderer_initiated,
Yoav Weiss8c573952022-11-17 17:35:133917 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:073918 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133919 /*force_enabled_origin_trials=*/std::vector<std::string>(),
3920 /*origin_agent_cluster=*/false,
3921 /*origin_agent_cluster_left_as_default=*/true,
3922 /*enabled_client_hints=*/
3923 std::vector<network::mojom::WebClientHintsType>(),
3924 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
3925 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:013926 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:133927 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:583928 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:133929 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:133930 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:283931 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:133932 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:443933 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:423934 network::mojom::NavigationDeliveryType::kDefault,
Yoav Weiss8c573952022-11-17 17:35:133935 /*view_transition_state=*/absl::nullopt,
sbinglera07ae732022-12-02 20:49:053936 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
3937 /*modified_runtime_features=*/
Garrett Tanzer29de7112022-12-06 21:26:323938 base::flat_map<::blink::mojom::RuntimeFeatureState, bool>(),
Yuzu Saijo29f96ca92022-12-08 04:54:123939 /*fenced_frame_properties=*/absl::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:053940 /*not_restored_reasons=*/nullptr,
3941 /*load_with_storage_access=*/false);
Xiaohan Wang7f8052e02022-01-14 18:44:283942#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423943 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143944 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423945 }
3946#endif
3947
Lucas Furukawa Gadania9c45682019-07-31 22:05:143948 commit_params->was_activated = params.was_activated;
Camille Lamy5193caa2018-10-12 11:59:423949
Camille Lamy5193caa2018-10-12 11:59:423950 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3951 std::string extra_headers_crlf;
3952 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:093953
Alex Moshchuk9321e6a2022-12-07 21:58:313954 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143955 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:083956 !params.is_renderer_initiated, params.was_opener_suppressed,
Antonio Sartori9a82f6f32020-12-14 09:22:453957 params.initiator_frame_token.has_value()
3958 ? &(params.initiator_frame_token.value())
3959 : nullptr,
3960 params.initiator_process_id, extra_headers_crlf, frame_entry, entry,
jongdeok.kim5de823b32022-06-14 04:37:503961 params.is_form_submission,
John Delaney50425f82020-04-07 16:26:213962 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:293963 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:453964 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583965 is_container_initiated, embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:093966 navigation_request->set_from_download_cross_origin_redirect(
3967 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:553968 navigation_request->set_force_new_browsing_instance(
3969 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:093970 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:423971}
3972
3973std::unique_ptr<NavigationRequest>
3974NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:233975 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573976 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:233977 FrameNavigationEntry* frame_entry,
3978 ReloadType reload_type,
3979 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:433980 bool is_history_navigation_in_new_child_frame,
Yoav Weiss8c573952022-11-17 17:35:133981 bool is_browser_initiated,
3982 absl::optional<blink::scheduler::TaskAttributionId>
3983 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:343984 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:233985 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:433986 // We should never navigate to an existing initial NavigationEntry that is the
3987 // initial NavigationEntry for the initial empty document that hasn't been
3988 // overridden by the synchronous about:blank commit, to preserve previous
3989 // behavior where trying to reload when the main frame is on the initial empty
3990 // document won't result in a navigation.
3991 // See also https://crbug.com/1277414.
3992 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:323993
clamyea99ea12018-05-28 13:54:233994 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:013995 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573996 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:233997 // We may have been redirected when navigating to the current URL.
3998 // Use the URL the user originally intended to visit as signaled by the
3999 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:014000 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574001 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:234002 dest_referrer = Referrer();
clamyea99ea12018-05-28 13:54:234003 }
4004
Ehsan Karamad44fc72112019-02-26 18:15:474005 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4006 // Avoid starting any new navigations since this node is now preparing for
4007 // attaching an inner delegate.
4008 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204009 }
4010
Ian Vollick1c6dd3e2022-04-13 02:06:264011 if (!IsValidURLForNavigation(frame_tree_node->IsOutermostMainFrame(),
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574012 entry->GetVirtualURL(), dest_url)) {
clamyea99ea12018-05-28 13:54:234013 return nullptr;
4014 }
4015
clamyea99ea12018-05-28 13:54:234016 // This will be used to set the Navigation Timing API navigationStart
4017 // parameter for browser navigations in new tabs (intents, tabs opened through
4018 // "Open link in new tab"). If the navigation must wait on the current
4019 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4020 // will be updated when the BeforeUnload ack is received.
4021 base::TimeTicks navigation_start = base::TimeTicks::Now();
clamyea99ea12018-05-28 13:54:234022
danakjd83d706d2020-11-25 22:11:124023 // Look for a pending commit that is to another document in this
4024 // FrameTreeNode. If one exists, then the last committed URL will not be the
4025 // current URL by the time this navigation commits.
4026 bool has_pending_cross_document_commit =
4027 frame_tree_node->render_manager()
4028 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494029 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214030 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124031
Minggang Wangb9f3fa92021-07-01 15:30:314032 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124033 /*old_url=*/frame_tree_node->current_url(),
4034 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:494035 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494036 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134037 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494038 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424039
4040 // A form submission may happen here if the navigation is a
4041 // back/forward/reload navigation that does a form resubmission.
4042 scoped_refptr<network::ResourceRequestBody> request_body;
4043 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:504044 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
4045 // entry. This way, it could be directly retrieved here. Right now, it is only
4046 // partially recovered when request.method == "POST" and request.body exists.
4047 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424048 if (frame_entry->method() == "POST") {
4049 request_body = frame_entry->GetPostData(&post_content_type);
4050 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304051 post_content_type = std::string(
4052 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504053 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424054 }
4055
4056 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314057 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514058 entry->ConstructCommonNavigationParams(
4059 *frame_entry, request_body, dest_url,
4060 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384061 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534062 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514063 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554064 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424065
4066 // TODO(clamy): |intended_as_new_entry| below should always be false once
4067 // Reload no longer leads to this being called for a pending NavigationEntry
4068 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314069 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144070 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404071 *frame_entry, common_params->url, common_params->method,
4072 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144073 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534074 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484075 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134076 frame_tree_node->AncestorOrSelfHasCSPEE(),
4077 soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144078 commit_params->post_content_type = post_content_type;
Camille Lamy5193caa2018-10-12 11:59:424079
W. James MacLeanb7d6092682022-10-05 15:23:264080 if (common_params->url.IsAboutSrcdoc()) {
4081 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4082 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594083 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264084 }
Alex Moshchuk9321e6a2022-12-07 21:58:314085 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144086 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434087 is_browser_initiated, false /* was_opener_suppressed */,
Takashi Toyoshimae87b7be2021-01-22 11:51:084088 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:454089 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
jongdeok.kim5de823b32022-06-14 04:37:504090 entry->extra_headers(), frame_entry, entry, is_form_submission,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474091 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294092 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4093 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474094 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234095}
4096
[email protected]d202a7c2012-01-04 07:53:474097void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214098 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274099 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404100
Takashi Toyoshimaea534ef22021-07-21 03:27:594101 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404102 // location bar will have up-to-date information about the security style
4103 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134104 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404105
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374106 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574107 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:464108
[email protected]b0f724c2013-09-05 04:21:134109 // TODO(avi): Remove. http://crbug.com/170921
4110 NotificationDetails notification_details =
4111 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154112 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4113 Source<NavigationController>(this),
4114 notification_details);
initial.commit09911bf2008-07-26 23:55:294115}
4116
initial.commit09911bf2008-07-26 23:55:294117// static
[email protected]d202a7c2012-01-04 07:53:474118size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234119 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154120 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214121 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234122}
4123
[email protected]d202a7c2012-01-04 07:53:474124void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224125 if (is_active && needs_reload_)
4126 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294127}
4128
[email protected]d202a7c2012-01-04 07:53:474129void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034130 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4131 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294132 if (!needs_reload_)
4133 return;
4134
Bo Liucdfa4b12018-11-06 00:21:444135 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4136 needs_reload_type_);
4137
initial.commit09911bf2008-07-26 23:55:294138 // Calling Reload() results in ignoring state, and not loading.
4139 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4140 // cached state.
avicc872d7242015-08-19 21:26:344141 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134142 NavigateToExistingPendingEntry(
4143 ReloadType::NONE,
4144 /*initiator_rfh=*/nullptr,
4145 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4146 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454147 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434148 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274149 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344150 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134151 NavigateToExistingPendingEntry(
4152 ReloadType::NONE,
4153 /*initiator_rfh=*/nullptr,
4154 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4155 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344156 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434157 // We should never navigate to an existing initial NavigationEntry that is
4158 // the initial NavigationEntry for the initial empty document that hasn't
4159 // been overridden by the synchronous about:blank commit, to preserve
4160 // legacy behavior where trying to reload when the main frame is on the
4161 // initial empty document won't result in a navigation. See also
4162 // https://crbug.com/1277414. If there is something to reload, the
4163 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4164 // it here.
avicc872d7242015-08-19 21:26:344165 needs_reload_ = false;
4166 }
initial.commit09911bf2008-07-26 23:55:294167}
4168
Kevin McNeeccca6172021-10-19 17:11:144169base::WeakPtr<NavigationHandle>
4170NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364171 RenderFrameHost* render_frame_host,
4172 const GURL& url,
4173 const std::string& error_page_html,
4174 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134175 RenderFrameHostImpl* rfhi =
4176 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584177
4178 // Only active documents can load post-commit error pages:
4179 // - If the document is in pending deletion, the browser already committed to
4180 // destroying this RenderFrameHost so ignore loading the error page.
4181 // - If the document is in back-forward cache, it's not allowed to navigate as
4182 // it should remain frozen. Ignore the request and evict the document from
4183 // back-forward cache.
4184 // - If the document is prerendering, it can navigate but when loading error
4185 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114186 if (rfhi->IsInactiveAndDisallowActivation(
4187 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144188 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114189 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584190
Rakina Zata Amni919b7922020-12-11 09:03:134191 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414192
Minggang Wangb9f3fa92021-07-01 15:30:314193 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434194 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594195 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4196 // the frame actually committed (e.g. iframe with "src" set to a
4197 // slow-responding URL). We should rewrite the URL to about:blank in this
4198 // case, as the renderer will only think a page is an error page if it has a
4199 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134200 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314201 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434202 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334203 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414204
arthursonzogni70ac7302020-05-28 08:49:054205 // Error pages have a fully permissive FramePolicy.
4206 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4207 // error pages.
4208 commit_params->frame_policy = blink::FramePolicy();
4209
John Delaney131ad362019-08-08 21:57:414210 std::unique_ptr<NavigationRequest> navigation_request =
4211 NavigationRequest::CreateBrowserInitiated(
4212 node, std::move(common_params), std::move(commit_params),
Alex Moshchuk9321e6a2022-12-07 21:58:314213 false /* was_opener_suppressed */,
Lingqi Chi82efa95e2020-12-29 05:31:194214 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:454215 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
John Delaneyf43556d2020-05-04 23:19:064216 "" /* extra_headers */, nullptr /* frame_entry */,
jongdeok.kim5de823b32022-06-14 04:37:504217 nullptr /* entry */, false /* is_form_submission */,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474218 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
4219 false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364220 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414221 navigation_request->set_net_error(error);
Charlie Reis09952ee2022-12-08 16:35:074222 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414223 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144224
4225 // Calling BeginNavigation may destroy the NavigationRequest.
4226 base::WeakPtr<NavigationRequest> created_navigation_request(
4227 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414228 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144229 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414230}
4231
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574232void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214233 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094234 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154235 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144236 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294237}
4238
[email protected]d202a7c2012-01-04 07:53:474239void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364240 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474241 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4242 // represent a no-committed-entry state.
4243 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364244 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474245 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4246 // if `entries_` contains pre-existing entries from the NavigationController
4247 // before restore, which would not be removed and will be at the front of the
4248 // entries list, causing the index to be off by the amount of pre-existing
4249 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294250 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294251}
[email protected]765b35502008-08-21 00:51:204252
arthursonzogni69a6a1b2019-09-17 09:23:004253void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004254 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4255}
4256
4257void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4258 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474259 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104260 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4261 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294262 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474263 return;
Michael Thiessenc5676d22019-09-25 22:32:104264 }
avi45a72532015-04-07 21:01:454265 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314266
4267 if (!delegate_)
4268 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374269 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484270}
4271
avi7c6f35e2015-05-08 17:52:384272int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4273 int nav_entry_id) const {
4274 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4275 if (entries_[i]->GetUniqueID() == nav_entry_id)
4276 return i;
4277 }
4278 return -1;
4279}
4280
[email protected]d202a7c2012-01-04 07:53:474281void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574282 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254283 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574284 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574285 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4286 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254287 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374288 // Normally, cloning a NavigationEntryImpl results in sharing
4289 // FrameNavigationEntries between the original and the clone. However, when
4290 // cloning from a different NavigationControllerImpl, we want to fork the
4291 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374292 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574293 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254294 }
Rakina Zata Amnie2d31312022-11-18 03:38:454295 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274296 DCHECK(pending_entry_index_ == -1 ||
4297 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254298}
[email protected]c5b88d82012-10-06 17:03:334299
4300void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184301 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334302 get_timestamp_callback_ = get_timestamp_callback;
4303}
[email protected]8ff00d72012-10-23 19:12:214304
Shivani Sharmaffb32b82019-04-09 16:58:474305// History manipulation intervention:
4306void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474307 bool replace_entry,
4308 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404309 bool is_renderer_initiated,
4310 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454311 // Note that for a subframe, previous_document_was_activated is true if the
4312 // gesture happened in any subframe (propagated to main frame) or in the main
4313 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474314 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274315 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474316 return;
4317 }
4318 if (last_committed_entry_index_ == -1)
4319 return;
4320
Shivani Sharmac4cc8922019-04-18 03:11:174321 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474322
Alexander Timine3ec4192020-04-20 16:39:404323 // Log UKM with the URL we are navigating away from.
4324 ukm::builders::HistoryManipulationIntervention(
4325 previous_page_load_ukm_source_id)
4326 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474327}
4328
Shivani Sharmac4cc8922019-04-18 03:11:174329void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4330 int reference_index,
4331 bool skippable) {
4332 auto* reference_entry = GetEntryAtIndex(reference_index);
4333 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4334
4335 int64_t document_sequence_number =
4336 reference_entry->root_node()->frame_entry->document_sequence_number();
4337 for (int index = 0; index < GetEntryCount(); index++) {
4338 auto* entry = GetEntryAtIndex(index);
4339 if (entry->root_node()->frame_entry->document_sequence_number() ==
4340 document_sequence_number) {
4341 entry->set_should_skip_on_back_forward_ui(skippable);
4342 }
4343 }
4344}
4345
arthursonzogni66f711c2019-10-08 14:40:364346std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4347NavigationControllerImpl::ReferencePendingEntry() {
4348 DCHECK(pending_entry_);
4349 auto pending_entry_ref =
4350 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4351 pending_entry_refs_.insert(pending_entry_ref.get());
4352 return pending_entry_ref;
4353}
4354
4355void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4356 // Ignore refs that don't correspond to the current pending entry.
4357 auto it = pending_entry_refs_.find(ref);
4358 if (it == pending_entry_refs_.end())
4359 return;
4360 pending_entry_refs_.erase(it);
4361
4362 if (!pending_entry_refs_.empty())
4363 return;
4364
4365 // The pending entry may be deleted before the last PendingEntryRef.
4366 if (!pending_entry_)
4367 return;
4368
4369 // We usually clear the pending entry when the matching NavigationRequest
4370 // fails, so that an arbitrary URL isn't left visible above a committed page.
4371 //
4372 // However, we do preserve the pending entry in some cases, such as on the
4373 // initial navigation of an unmodified blank tab. We also allow the delegate
4374 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4375 // user edit the URL and try again. This may be useful in cases that the
4376 // committed page cannot be attacker-controlled. In these cases, we still
4377 // allow the view to clear the pending entry and typed URL if the user
4378 // requests (e.g., hitting Escape with focus in the address bar).
4379 //
4380 // Do not leave the pending entry visible if it has an invalid URL, since this
4381 // might be formatted in an unexpected or unsafe way.
4382 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364383 bool should_preserve_entry =
4384 (pending_entry_ == GetVisibleEntry()) &&
4385 pending_entry_->GetURL().is_valid() &&
4386 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4387 if (should_preserve_entry)
4388 return;
4389
4390 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374391 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364392}
4393
Titouan Rigoudy6ec70402021-02-02 15:42:194394std::unique_ptr<PolicyContainerPolicies>
4395NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394396 RenderFrameHostImpl* rfh,
4397 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174398 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394399 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454400 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394401 FrameNavigationEntry* previous_frame_entry =
4402 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4403
4404 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4405 // ensure we always have a FrameNavigationEntry here.
4406 if (!previous_frame_entry)
4407 return nullptr;
4408
Titouan Rigoudy6ec70402021-02-02 15:42:194409 const PolicyContainerPolicies* previous_policies =
4410 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394411
Titouan Rigoudy6ec70402021-02-02 15:42:194412 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394413 return nullptr;
4414
4415 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234416 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394417 }
4418
Titouan Rigoudy72f892d2022-05-02 18:21:234419 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394420}
4421
Hayato Ito2c8c08d02021-06-23 03:38:434422void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504423 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434424 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4425 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4426 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504427
4428 auto callback = base::BindRepeating(
4429 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4430 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4431 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4432 }
4433 },
Hayato Ito2c8c08d02021-06-23 03:38:434434 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034435 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504436}
4437
4438void NavigationControllerImpl::DidAccessInitialMainDocument() {
4439 // We may have left a failed browser-initiated navigation in the address bar
4440 // to let the user edit it and try again. Clear it now that content might
4441 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034442 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504443 DiscardPendingEntry(false);
4444
4445 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374446 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504447}
4448
4449void NavigationControllerImpl::UpdateStateForFrame(
4450 RenderFrameHostImpl* rfhi,
4451 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564452 OPTIONAL_TRACE_EVENT1("content",
4453 "NavigationControllerImpl::UpdateStateForFrame",
4454 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504455 // The state update affects the last NavigationEntry associated with the given
4456 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4457 // in the case of an UpdateState from a frame being swapped out). We track
4458 // which entry this is in the RenderFrameHost's nav_entry_id.
4459 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4460 if (!entry)
4461 return;
4462
4463 FrameNavigationEntry* frame_entry =
4464 entry->GetFrameEntry(rfhi->frame_tree_node());
4465 if (!frame_entry)
4466 return;
4467
4468 // The SiteInstance might not match if we do a cross-process navigation with
4469 // replacement (e.g., auto-subframe), in which case the swap out of the old
4470 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4471 // has already been replaced and destroyed.
4472 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4473 return;
4474
4475 if (page_state == frame_entry->page_state())
4476 return; // Nothing to update.
4477
4478 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4479
4480 // The document_sequence_number and item_sequence_number recorded in the
4481 // FrameNavigationEntry should not differ from the one coming with the update,
4482 // since it must come from the same document. Do not update it if a difference
4483 // is detected, as this indicates that |frame_entry| is not the correct one.
4484 blink::ExplodedPageState exploded_state;
4485 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4486 return;
4487
4488 if (exploded_state.top.document_sequence_number !=
4489 frame_entry->document_sequence_number() ||
4490 exploded_state.top.item_sequence_number !=
4491 frame_entry->item_sequence_number()) {
4492 return;
4493 }
4494
4495 frame_entry->SetPageState(page_state);
4496 NotifyEntryChanged(entry);
4497}
4498
Domenic Denicolacd30f5f82022-03-16 21:48:014499std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4500NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574501 Direction direction,
4502 int entry_index,
4503 const url::Origin& pending_origin,
4504 FrameTreeNode* node,
4505 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304506 int64_t pending_item_sequence_number,
4507 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014508 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454509 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174510 // Don't process the initial entry.
4511 DCHECK_EQ(GetEntryCount(), 1);
4512 return entries;
4513 }
Nate Chapind1fe3612021-04-16 20:45:574514 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304515 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574516 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4517 i += offset) {
4518 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414519 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574520 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014521 // An entry should only appear in the navigation API entries if it is for
4522 // the same origin as the document being committed. Check the committed
4523 // origin, or if that is not available (during restore), check against the
4524 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414525 url::Origin frame_entry_origin =
4526 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4527 frame_entry->url(),
4528 frame_entry->initiator_origin().value_or(url::Origin())));
4529 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574530 break;
4531 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4532 continue;
4533 blink::ExplodedPageState exploded_page_state;
4534 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4535 &exploded_page_state)) {
4536 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304537
4538 // If the document represented by this FNE hid its full url from appearing
4539 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014540 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304541 // document).
4542 std::u16string url;
4543 if (pending_document_sequence_number ==
4544 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574545 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304546 url = frame_state.url_string.value_or(std::u16string());
4547 }
4548
Domenic Denicolacd30f5f82022-03-16 21:48:014549 blink::mojom::NavigationApiHistoryEntryPtr entry =
4550 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574551 frame_state.navigation_api_key.value_or(std::u16string()),
4552 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094553 frame_state.item_sequence_number,
4554 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304555 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174556
Nate Chapin63db0d12022-01-20 22:03:304557 DCHECK(entry->url.empty() ||
4558 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574559 entries.push_back(std::move(entry));
4560 previous_item_sequence_number = frame_entry->item_sequence_number();
4561 }
4562 }
4563 // If |entries| was constructed by iterating backwards from
4564 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4565 // earliest-at-the-front. Reverse it.
4566 if (direction == Direction::kBack)
4567 std::reverse(entries.begin(), entries.end());
4568 return entries;
4569}
4570
Domenic Denicolacd30f5f82022-03-16 21:48:014571blink::mojom::NavigationApiHistoryEntryArraysPtr
4572NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554573 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574574 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404575 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444576 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404577 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574578
Nate Chapind1fe3612021-04-16 20:45:574579 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554580 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574581
Nate Chapine82339d02022-05-03 23:48:254582 // NOTE: |entry_index| is the index where this entry will commit if no
4583 // modifications are made between now and DidCommitNavigation. This is used to
4584 // walk |entries_| and determine which entries should be exposed by the
4585 // navigation API. It is important to calculate this correctly, because blink
4586 // will cancel a same-document history commit if it's not present in the
4587 // entries blink knows about.
4588 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574589 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304590 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254591 bool will_create_new_entry = false;
4592 if (GetPendingEntryIndex() != -1) {
4593 entry_index = GetPendingEntryIndex();
4594 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4595 pending_item_sequence_number = frame_entry->item_sequence_number();
4596 pending_document_sequence_number =
4597 frame_entry->document_sequence_number();
4598 }
4599 } else if (request &&
4600 !NavigationTypeUtils::IsReload(
4601 request->common_params().navigation_type) &&
4602 !NavigationTypeUtils::IsHistory(
4603 request->common_params().navigation_type) &&
4604 !request->common_params().should_replace_current_entry &&
4605 !request->common_params()
4606 .is_history_navigation_in_new_child_frame) {
4607 will_create_new_entry = true;
4608 entry_index = GetLastCommittedEntryIndex() + 1;
4609 // Don't set pending_item_sequence_number or
4610 // pending_document_sequence_number in this case - a new unique isn/dsn will
4611 // be calculated in the renderer later.
4612 } else if (GetLastCommittedEntryIndex() != -1) {
4613 entry_index = GetLastCommittedEntryIndex();
4614 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574615 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304616 pending_document_sequence_number =
4617 frame_entry->document_sequence_number();
4618 }
Nate Chapind1fe3612021-04-16 20:45:574619 }
4620
Domenic Denicolacd30f5f82022-03-16 21:48:014621 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254622 if (entry_index == -1) {
4623 // TODO(rakina): Exit early when there is no last committed entry.
4624 // Remove when InitialNavigationEntry ships.
4625 return entry_arrays;
4626 }
4627
Domenic Denicolacd30f5f82022-03-16 21:48:014628 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574629 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374630 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574631
4632 // Don't populate forward entries if they will be truncated by a new entry.
4633 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014634 entry_arrays->forward_entries =
4635 PopulateSingleNavigationApiHistoryEntryVector(
4636 Direction::kForward, entry_index, pending_origin, node,
4637 site_instance.get(), pending_item_sequence_number,
4638 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574639 }
Nate Chapin4e657a472022-02-06 03:38:374640 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574641}
4642
Nate Chapinfbfe5af2021-06-10 17:22:084643NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574644NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084645 FrameNavigationEntry* current_entry,
4646 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574647 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084648 if (!target_entry || !target_entry->committed_origin())
4649 return HistoryNavigationAction::kStopLooking;
4650 if (current_entry->site_instance() != target_entry->site_instance())
4651 return HistoryNavigationAction::kStopLooking;
4652 if (!current_entry->committed_origin()->IsSameOriginWith(
4653 *target_entry->committed_origin())) {
4654 return HistoryNavigationAction::kStopLooking;
4655 }
4656
4657 // NOTE: We don't actually care between kSameDocument and
4658 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574659 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084660 return HistoryNavigationAction::kDifferentDocument;
4661 return HistoryNavigationAction::kKeepLooking;
4662}
4663
Domenic Denicolacc094fb2022-03-16 23:40:574664void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204665 RenderFrameHostImpl* initiator_rfh,
Yoav Weissa7449c3b2022-11-22 15:15:144666 absl::optional<blink::scheduler::TaskAttributionId>
4667 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574668 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204669 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084670 FrameNavigationEntry* current_entry =
4671 GetLastCommittedEntry()->GetFrameEntry(node);
4672 if (!current_entry)
4673 return;
4674
Yoav Weiss8c573952022-11-17 17:35:134675 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4676 // when `navigation.traverseTo()` is called.
4677
Nate Chapinfbfe5af2021-06-10 17:22:084678 // We want to find the nearest matching entry that is contiguously
4679 // same-instance and same-origin. Check back first, then forward.
4680 // TODO(japhet): Link spec here once it exists.
4681 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574682 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084683 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4684 if (result == HistoryNavigationAction::kStopLooking)
4685 break;
4686 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144687 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084688 return;
4689 }
4690 }
4691 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574692 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084693 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4694 if (result == HistoryNavigationAction::kStopLooking)
4695 break;
4696 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144697 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084698 return;
4699 }
4700 }
Nate Chapinbf682fa32022-09-26 22:41:204701
4702 // If we fall through to here, a matching NavigationEntry couldn't be found.
4703 // Notify the renderer that the navigation was cancelled.
4704 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4705 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084706}
4707
Domenic Denicolacc094fb2022-03-16 23:40:574708bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304709 network::mojom::ReferrerPolicy referrer_policy) {
4710 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4711 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4712}
4713
shivanigithubf405bf0d2021-11-05 17:58:334714bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4715 const FrameTreeNode* frame_tree_node) const {
4716 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4717 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544718 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Ali Hijazid87307d2022-11-07 20:15:034719 return frame_tree_->is_prerendering() ||
shivanigithubf405bf0d2021-11-05 17:58:334720 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544721}
4722
Julie Jeongeun Kim0e242242022-11-30 10:45:094723void NavigationControllerImpl::DidChangeReferrerPolicy(
4724 FrameTreeNode* node,
4725 network::mojom::ReferrerPolicy referrer_policy) {
4726 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4727 if (!entry)
4728 return;
4729
4730 // The FrameNavigationEntry may want to change whether to protect its url
4731 // in the navigation API when the referrer policy changes.
4732 entry->set_protect_url_in_navigation_api(
4733 ShouldProtectUrlInNavigationApi(referrer_policy));
4734}
4735
[email protected]8ff00d72012-10-23 19:12:214736} // namespace content