blob: ddb35ac4cddf35b8dd711c0497ceb89f0a86f6fe [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"
Sharon Yang242ef822023-05-15 21:07:3265#include "content/browser/process_lock.h"
danakjc492bf82020-09-09 20:02:4466#include "content/browser/renderer_host/debug_urls.h"
67#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0068#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3369#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4470#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5771#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4472#include "content/browser/renderer_host/navigation_request.h"
William Liu055a3542023-04-02 17:21:1973#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_cache.h"
74#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_manager.h"
danakjc492bf82020-09-09 20:02:4475#include "content/browser/renderer_host/navigator.h"
76#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0077#include "content/browser/renderer_host/render_view_host_impl.h"
Mike Jacksone2aa7af2023-05-17 06:45:0778#include "content/browser/renderer_host/system_entropy_utils.h"
Sharon Yangd70a5392021-10-26 23:06:3279#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3380#include "content/browser/site_instance_impl.h"
Camille Lamy5193caa2018-10-12 11:59:4281#include "content/common/content_constants_internal.h"
Nate Chapind1fe3612021-04-16 20:45:5782#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5183#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1184#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1985#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1186#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4687#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0088#include "content/public/browser/navigation_details.h"
[email protected]7f6f44c2011-12-14 13:23:3889#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1690#include "content/public/browser/notification_types.h"
Lei Zhang96031532019-10-10 19:05:4791#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5892#include "content/public/browser/render_widget_host.h"
93#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1094#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3495#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1996#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3897#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1098#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:4799#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:43100#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59101#include "media/base/mime_util.h"
Arthur Sonzogni620cec62018-12-13 13:08:57102#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18103#include "services/metrics/public/cpp/ukm_builders.h"
104#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17105#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37106#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44107#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58108#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39109#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30110#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21111#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06112#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43113#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50114#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31115#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51116#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
sbinglera07ae732022-12-02 20:49:05117#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature_state.mojom.h"
[email protected]cca6f392014-05-28 21:32:26118#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29119
[email protected]8ff00d72012-10-23 19:12:21120namespace content {
[email protected]e9ba4472008-09-14 15:42:43121namespace {
122
Charlie Reis951f43372023-05-05 00:30:07123// TODO(https://crbug.com/1439948): Remove this base::Feature kill switch once
124// the feature safely rolls out.
125BASE_FEATURE(kUpdateSessionHistoryIndexBeforeNavigationStateChanged,
126 "UpdateSessionHistoryIndexBeforeNavigationStateChanged",
127 base::FEATURE_ENABLED_BY_DEFAULT);
128
[email protected]e9ba4472008-09-14 15:42:43129// Invoked when entries have been pruned, or removed. For example, if the
130// current entries are [google, digg, yahoo], with the current entry google,
131// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47132void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50133 int index,
[email protected]c12bf1a12008-09-17 16:28:49134 int count) {
[email protected]8ff00d72012-10-23 19:12:21135 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50136 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49137 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14138 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43139}
140
[email protected]e9ba4472008-09-14 15:42:43141// Configure all the NavigationEntries in entries for restore. This resets
142// the transition type to reload and makes sure the content state isn't empty.
143void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57144 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48145 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47146 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43147 // Use a transition type of reload so that we don't incorrectly increase
148 // the typed count.
Lei Zhang96031532019-10-10 19:05:47149 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
150 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43151 }
152}
153
[email protected]bf70edce2012-06-20 22:32:22154// Determines whether or not we should be carrying over a user agent override
155// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57156bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22157 return last_entry && last_entry->GetIsOverridingUserAgent();
158}
159
Camille Lamy5193caa2018-10-12 11:59:42160// Determines whether to override user agent for a navigation.
161bool ShouldOverrideUserAgent(
162 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57163 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42164 switch (override_user_agent) {
165 case NavigationController::UA_OVERRIDE_INHERIT:
166 return ShouldKeepOverride(last_committed_entry);
167 case NavigationController::UA_OVERRIDE_TRUE:
168 return true;
169 case NavigationController::UA_OVERRIDE_FALSE:
170 return false;
Camille Lamy5193caa2018-10-12 11:59:42171 }
172 NOTREACHED();
173 return false;
174}
175
Rakina Zata Amni312822d72021-06-04 16:13:37176// Returns true if this navigation should be treated as a reload. For e.g.
clamy0a656e42018-02-06 18:18:28177// navigating to the last committed url via the address bar or clicking on a
Rakina Zata Amni312822d72021-06-04 16:13:37178// link which results in a navigation to the last committed URL (but wasn't
179// converted to do a replacement navigation in the renderer), etc.
Fergal Daly766177d2020-07-07 07:54:04180// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
181// |base_url_for_data_url|, |transition_type| correspond to the new navigation
182// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
183// navigation that committed.
184bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
185 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57186 const GURL& virtual_url,
187 const GURL& base_url_for_data_url,
188 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57189 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37190 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57191 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37192 // Navigations intended to do a replacement shouldn't be converted to do a
193 // reload.
194 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28195 return false;
clamy0a656e42018-02-06 18:18:28196 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45197 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55198 return false;
199
arthursonzogni7a8243682017-12-14 16:41:42200 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28201 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42202 return false;
203
ananta3bdd8ae2016-12-22 17:11:55204 // We treat (PAGE_TRANSITION_RELOAD | PAGE_TRANSITION_FROM_ADDRESS_BAR),
205 // PAGE_TRANSITION_TYPED or PAGE_TRANSITION_LINK transitions as navigations
206 // which should be treated as reloads.
clamy0a656e42018-02-06 18:18:28207 bool transition_type_can_be_converted = false;
208 if (ui::PageTransitionCoreTypeIs(transition_type,
209 ui::PAGE_TRANSITION_RELOAD) &&
210 (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)) {
211 transition_type_can_be_converted = true;
ananta3bdd8ae2016-12-22 17:11:55212 }
clamy0a656e42018-02-06 18:18:28213 if (ui::PageTransitionCoreTypeIs(transition_type,
ananta3bdd8ae2016-12-22 17:11:55214 ui::PAGE_TRANSITION_TYPED)) {
clamy0a656e42018-02-06 18:18:28215 transition_type_can_be_converted = true;
216 }
217 if (ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_LINK))
218 transition_type_can_be_converted = true;
219 if (!transition_type_can_be_converted)
220 return false;
221
222 // This check is required for cases like view-source:, etc. Here the URL of
223 // the navigation entry would contain the url of the page, while the virtual
224 // URL contains the full URL including the view-source prefix.
225 if (virtual_url != last_committed_entry->GetVirtualURL())
226 return false;
227
Fergal Daly766177d2020-07-07 07:54:04228 // Check that the URLs match.
229 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
230 // If there's no frame entry then by definition the URLs don't match.
231 if (!frame_entry)
232 return false;
233
234 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28235 return false;
236
237 // This check is required for Android WebView loadDataWithBaseURL. Apps
238 // can pass in anything in the base URL and we need to ensure that these
239 // match before classifying it as a reload.
240 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
241 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
242 return false;
ananta3bdd8ae2016-12-22 17:11:55243 }
244
clamy0a656e42018-02-06 18:18:28245 // Skip entries with SSL errors.
246 if (last_committed_entry->ssl_error())
247 return false;
248
249 // Don't convert to a reload when the last navigation was a POST or the new
250 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04251 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28252 return false;
253
254 return true;
ananta3bdd8ae2016-12-22 17:11:55255}
256
Anton Bikineevf62d1bf2021-05-15 17:56:07257absl::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12258 const mojom::DidCommitProvisionalLoadParams& params,
259 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32260 // Error pages commit in an opaque origin, yet have the real URL that resulted
261 // in an error as the |params.url|. Since successful reload of an error page
262 // should commit in the correct origin, setting the opaque origin on the
263 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17264 if (request && request->DidEncounterError())
Anton Bikineevf62d1bf2021-05-15 17:56:07265 return absl::nullopt;
Nasko Oskov03912102019-01-11 00:21:32266
Anton Bikineevf62d1bf2021-05-15 17:56:07267 return absl::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32268}
269
Alex Moshchuk99242832023-05-22 17:21:44270bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42271 const GURL& virtual_url,
272 const GURL& dest_url) {
273 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44274 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
275 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42276 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
277 << virtual_url.possibly_invalid_spec();
278 return false;
279 }
280
281 // Don't attempt to navigate to non-empty invalid URLs.
282 if (!dest_url.is_valid() && !dest_url.is_empty()) {
283 LOG(WARNING) << "Refusing to load invalid URL: "
284 << dest_url.possibly_invalid_spec();
285 return false;
286 }
287
288 // The renderer will reject IPC messages with URLs longer than
289 // this limit, so don't attempt to navigate with a longer URL.
290 if (dest_url.spec().size() > url::kMaxURLChars) {
291 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
292 << " characters.";
293 return false;
294 }
295
Aaron Colwell33109c592020-04-21 21:31:19296 // Reject renderer debug URLs because they should have been handled before
297 // we get to this point. This check handles renderer debug URLs
298 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
299 // provides defense-in-depth if a renderer debug URL manages to get here via
300 // some other path. We want to reject the navigation here so it doesn't
301 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30302 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19303 LOG(WARNING) << "Refusing to load renderer debug URL: "
304 << dest_url.possibly_invalid_spec();
305 return false;
306 }
307
Alex Moshchuk99242832023-05-22 17:21:44308 // Guests only support navigations to known-safe schemes. This check already
309 // exists in the extensions layer, where it also dispatches proper events to
310 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
311 // for defense-in-depth to ensure that no other places in the codebase
312 // accidentally navigate guests to schemes such as WebUI, which is not
313 // supported. See https://crbug.com/1444221.
314 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
315 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
316 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
317 !dest_url.SchemeIs(url::kAboutScheme)) {
318 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
319 << dest_url.possibly_invalid_spec();
320 return false;
321 }
322 }
323
Camille Lamy5193caa2018-10-12 11:59:42324 return true;
325}
326
Mikel Astizba9cf2fd2017-12-17 10:38:10327// See replaced_navigation_entry_data.h for details: this information is meant
328// to ensure |*output_entry| keeps track of its original URL (landing page in
329// case of server redirects) as it gets replaced (e.g. history.replaceState()),
330// without overwriting it later, for main frames.
331void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57332 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10333 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17334 if (output_entry->GetReplacedEntryData().has_value() ||
335 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10336 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17337 }
Mikel Astizba9cf2fd2017-12-17 10:38:10338
339 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57340 data.first_committed_url = replaced_entry->GetURL();
341 data.first_timestamp = replaced_entry->GetTimestamp();
342 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29343 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10344}
345
Minggang Wangb9f3fa92021-07-01 15:30:31346blink::mojom::NavigationType GetNavigationType(
347 const GURL& old_url,
348 const GURL& new_url,
349 ReloadType reload_type,
350 NavigationEntryImpl* entry,
351 const FrameNavigationEntry& frame_entry,
352 bool has_pending_cross_document_commit,
353 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49354 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13355 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49356 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23357 // Reload navigations
358 switch (reload_type) {
359 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31360 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23361 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31362 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23363 case ReloadType::ORIGINAL_REQUEST_URL:
Minggang Wangb9f3fa92021-07-01 15:30:31364 return blink::mojom::NavigationType::RELOAD_ORIGINAL_REQUEST_URL;
clamyea99ea12018-05-28 13:54:23365 case ReloadType::NONE:
366 break; // Fall through to rest of function.
367 }
368
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08369 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31370 return entry->GetHasPostData()
371 ? blink::mojom::NavigationType::RESTORE_WITH_POST
372 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23373 }
374
danakjb952ef12021-01-14 19:58:49375 const bool can_be_same_document =
376 // A pending cross-document commit means this navigation will not occur in
377 // the current document, as that document would end up being replaced in
378 // the meantime.
379 !has_pending_cross_document_commit &&
380 // If the current document is an error page, we should always treat it as
381 // a different-document navigation so that we'll attempt to load the
382 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49383 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13384 // If the navigation is an embedder-initiated navigation of a fenced
385 // frame root (i.e. enters a fenced frame tree from outside),
386 // same-document navigations should be disabled because we don't want to
387 // allow information to be joined across multiple embedder-initiated
388 // fenced frame navigations (which may contain separate cross-site data).
389 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49390 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
391 // same-document navigations should be disabled because we want to force
392 // the creation of a new browsing context group.
393 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12394
clamyea99ea12018-05-28 13:54:23395 // History navigations.
396 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12397 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31398 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
399 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23400 }
401 DCHECK(!is_same_document_history_load);
402
403 // A same-document fragment-navigation happens when the only part of the url
404 // that is modified is after the '#' character.
405 //
406 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12407 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23408 //
409 // Note: this check is only valid for navigations that are not history
410 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
411 // history navigation from 'A#foo' to 'A#bar' is not a same-document
412 // navigation, but a different-document one. This is why history navigation
413 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47414 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
415 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12416
417 // The one case where we do the wrong thing here and incorrectly choose
418 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
419 // the renderer is a frameset. All frameset navigations should be
420 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
421 // navigation would do the right thing, as it would send it to the browser and
422 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
423 // into this method). But since we can't tell that case here for browser-
424 // initiated navigations, we have to get the renderer involved. In that case
425 // the navigation would be restarted due to the renderer spending a reply of
426 // mojom::CommitResult::RestartCrossDocument.
427
428 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31429 ? blink::mojom::NavigationType::SAME_DOCUMENT
430 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23431}
432
Camille Lamy5193caa2018-10-12 11:59:42433// Adjusts the original input URL if needed, to get the URL to actually load and
434// the virtual URL, which may differ.
435void RewriteUrlForNavigation(const GURL& original_url,
436 BrowserContext* browser_context,
437 GURL* url_to_load,
438 GURL* virtual_url,
439 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42440 // Allow the browser URL handler to rewrite the URL. This will, for example,
441 // remove "view-source:" from the beginning of the URL to get the URL that
442 // will actually be loaded. This real URL won't be shown to the user, just
443 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31444 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42445 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
446 url_to_load, browser_context, reverse_on_redirect);
447}
448
449#if DCHECK_IS_ON()
450// Helper sanity check function used in debug mode.
451void ValidateRequestMatchesEntry(NavigationRequest* request,
452 NavigationEntryImpl* entry) {
453 if (request->frame_tree_node()->IsMainFrame()) {
454 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
455 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31456 ui::PageTransitionFromInt(request->common_params().transition),
457 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42458 }
Nasko Oskovc36327d2019-01-03 23:23:04459 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42460 entry->should_clear_history_list());
461 DCHECK_EQ(request->common_params().has_user_gesture,
462 entry->has_user_gesture());
463 DCHECK_EQ(request->common_params().base_url_for_data_url,
464 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04465 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42466 entry->GetCanLoadLocalResources());
467 DCHECK_EQ(request->common_params().started_from_context_menu,
468 entry->has_started_from_context_menu());
469
470 FrameNavigationEntry* frame_entry =
471 entry->GetFrameEntry(request->frame_tree_node());
472 if (!frame_entry) {
473 NOTREACHED();
474 return;
475 }
476
Camille Lamy5193caa2018-10-12 11:59:42477 DCHECK_EQ(request->common_params().method, frame_entry->method());
478
Nasko Oskovc36327d2019-01-03 23:23:04479 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42480 if (redirect_size == frame_entry->redirect_chain().size()) {
481 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04482 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42483 frame_entry->redirect_chain()[i]);
484 }
485 } else {
486 NOTREACHED();
487 }
488}
489#endif // DCHECK_IS_ON()
490
Dave Tapuska8bfd84c2019-03-26 20:47:16491// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20492// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16493bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20494 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16495 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20496 DCHECK(sandboxed_initiator_rfh);
497 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
498 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16499 for (auto& item : navigations) {
500 bool within_subtree = false;
501 // Check whether this NavigationRequest affects a frame within the
502 // sandboxed frame's subtree by walking up the tree looking for the
503 // sandboxed frame.
504 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03505 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20506 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16507 within_subtree = true;
508 break;
509 }
510 }
511 if (!within_subtree)
512 return false;
513 }
514 return true;
515}
516
[email protected]e9ba4472008-09-14 15:42:43517} // namespace
518
arthursonzogni66f711c2019-10-08 14:40:36519// NavigationControllerImpl::PendingEntryRef------------------------------------
520
521NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
522 base::WeakPtr<NavigationControllerImpl> controller)
523 : controller_(controller) {}
524
525NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
526 if (!controller_) // Can be null with interstitials.
527 return;
528
529 controller_->PendingEntryRefDeleted(this);
530}
531
[email protected]d202a7c2012-01-04 07:53:47532// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29533
[email protected]23a918b2014-07-15 09:51:36534const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23535
[email protected]765b35502008-08-21 00:51:20536// static
[email protected]d202a7c2012-01-04 07:53:47537size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23538 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20539
[email protected]e6fec472013-05-14 05:29:02540// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20541// when testing.
542static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29543
[email protected]71fde352011-12-29 03:29:56544// static
dcheng9bfa5162016-04-09 01:00:57545std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
546 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10547 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07548 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21549 absl::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10550 ui::PageTransition transition,
551 bool is_renderer_initiated,
552 const std::string& extra_headers,
553 BrowserContext* browser_context,
554 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
555 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21556 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Sharon Yang242ef822023-05-15 21:07:32557 absl::nullopt /* source_process_site_url */, transition,
558 is_renderer_initiated, extra_headers, browser_context,
559 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10560}
561
562// static
563std::unique_ptr<NavigationEntryImpl>
564NavigationControllerImpl::CreateNavigationEntry(
565 const GURL& url,
566 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07567 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21568 absl::optional<GURL> initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:32569 absl::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57570 ui::PageTransition transition,
571 bool is_renderer_initiated,
572 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09573 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17574 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
575 bool rewrite_virtual_urls) {
576 GURL url_to_load = url;
577 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56578 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17579 if (rewrite_virtual_urls) {
580 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
581 &reverse_on_redirect);
582 }
Lukasz Anforowicz641234d52019-11-07 21:07:10583 // Let the NTP override the navigation params and pretend that this is a
584 // browser-initiated, bookmark-like navigation.
585 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32586 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21587 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10588
Patrick Monettef507e982019-06-19 20:18:06589 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28590 nullptr, // The site instance for tabs is sent on navigation
591 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21592 url_to_load, referrer, initiator_origin, initiator_base_url,
593 std::u16string(), transition, is_renderer_initiated,
594 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17595 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42596 entry->SetVirtualURL(virtual_url);
597 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56598 entry->set_update_virtual_url_with_url(reverse_on_redirect);
599 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06600 return entry;
[email protected]71fde352011-12-29 03:29:56601}
602
[email protected]cdcb1dee2012-01-04 00:46:20603// static
604void NavigationController::DisablePromptOnRepost() {
605 g_check_for_repost = false;
606}
607
[email protected]c5b88d82012-10-06 17:03:33608base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
609 base::Time t) {
610 // If |t| is between the water marks, we're in a run of duplicates
611 // or just getting out of it, so increase the high-water mark to get
612 // a time that probably hasn't been used before and return it.
613 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35614 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33615 return high_water_mark_;
616 }
617
618 // Otherwise, we're clear of the last duplicate run, so reset the
619 // water marks.
620 low_water_mark_ = high_water_mark_ = t;
621 return t;
622}
623
ckitagawa0faa5e42020-06-17 17:30:54624NavigationControllerImpl::ScopedShowRepostDialogForTesting::
625 ScopedShowRepostDialogForTesting()
626 : was_disallowed_(g_check_for_repost) {
627 g_check_for_repost = true;
628}
629
630NavigationControllerImpl::ScopedShowRepostDialogForTesting::
631 ~ScopedShowRepostDialogForTesting() {
632 g_check_for_repost = was_disallowed_;
633}
634
Nate Chapin9eb16be72022-09-23 22:54:31635NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
636 base::SafeRef<NavigationControllerImpl> controller)
637 : controller_(controller) {
638 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
639 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
640 frame_tree_node_id_to_keys_.insert(
641 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
642 if (auto* frame_entry = frame_tree_node->current_frame_host()
643 ->last_committed_frame_entry()) {
644 frame_tree_node_id_to_doc_seq_nos_.insert(
645 {frame_tree_node->frame_tree_node_id(),
646 frame_entry->document_sequence_number()});
647 }
648 }
649 PopulateKeySet(Direction::kBack);
650 PopulateKeySet(Direction::kForward);
651}
652
653void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
654 Direction direction) {
655 // Keep track of which FrameTreeNodes may still have relevant API keys in
656 // additional FrameNavigationEntries.
657 std::set<FrameTreeNode*> nodes_to_process;
658 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
659 nodes_to_process.insert(node);
660 }
661
662 const int offset = direction == Direction::kForward ? 1 : -1;
663 const int start = direction == Direction::kForward
664 ? controller_->GetLastCommittedEntryIndex()
665 : controller_->GetLastCommittedEntryIndex() - 1;
666 for (int i = start;
667 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
668 i += offset) {
669 std::set<FrameTreeNode*> nodes_to_continue_processing;
670
671 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
672 entry->ForEachFrameEntry([this, &nodes_to_process,
673 &nodes_to_continue_processing,
674 &entry](FrameNavigationEntry* frame_entry) {
675 // Find the |node| that matches |frame_entry|, if any.
676 FrameTreeNode* node = nullptr;
677 if (frame_entry == entry->root_node()->frame_entry) {
678 node = controller_->frame_tree().root();
679 } else {
680 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
681 if (it == names_to_nodes_.end())
682 return;
683 node = it->second;
684 }
685
686 // Skip this node if a previous step determine there are no longer
687 // relevant navigation API keys in this direction.
688 if (nodes_to_process.find(node) == nodes_to_process.end())
689 return;
690
691 // Stop processing |node| if we reach a point where it's cross-origin.
692 // See also PopulateSingleNavigationApiHistoryEntryVector().
693 url::Origin frame_entry_origin =
694 frame_entry->committed_origin().value_or(url::Origin::Resolve(
695 frame_entry->url(),
696 frame_entry->initiator_origin().value_or(url::Origin())));
697 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
698 return;
699
700 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
701 frame_entry->navigation_api_key());
702 // Mark |node| as needing more processing for the next entry.
703 nodes_to_continue_processing.insert(node);
704
705 // Check whether |node| went cross-document. If so, its children are
706 // no longer the same conceptual iframe as the current one, and
707 // should no longer be processed. This check is intentionally done
708 // after processing the current |node|, which may still have relevant
709 // discarded API keys.
710 if (frame_entry->document_sequence_number() !=
711 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50712 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31713 nodes_to_process.erase(descendant);
714 }
715 });
716
717 nodes_to_process.swap(nodes_to_continue_processing);
718 }
719}
720
721NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
722 std::set<std::string> all_keys;
723 // Find all remaining navigation API keys after some entries have been
724 // removed.
725 for (auto& entry : controller_->entries_) {
726 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
727 all_keys.insert(frame_entry->navigation_api_key());
728 });
729 }
730
731 // Notify each frame in the renderer of any disposed navigation API keys.
732 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
733 std::vector<std::string> disposed_keys;
734 for (const auto& key : id_to_keys.second) {
735 if (all_keys.find(key) == all_keys.end())
736 disposed_keys.push_back(key);
737 }
738 if (disposed_keys.empty())
739 continue;
740
741 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
742 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
743 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
744 }
745}
746
[email protected]d202a7c2012-01-04 07:53:47747NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00748 BrowserContext* browser_context,
749 FrameTree& frame_tree,
750 NavigationControllerDelegate* delegate)
751 : frame_tree_(frame_tree),
752 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57753 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22754 ssl_manager_(this),
Lei Zhang96031532019-10-10 19:05:47755 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)) {
[email protected]3d7474ff2011-07-27 17:47:37756 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29757}
758
[email protected]d202a7c2012-01-04 07:53:47759NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00760 // The NavigationControllerImpl might be called inside its delegate
761 // destructor. Calling it is not valid anymore.
762 delegate_ = nullptr;
763 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29764}
765
Matt Falkenhagen548ed1562021-07-06 01:38:26766WebContents* NavigationControllerImpl::DeprecatedGetWebContents() {
767 return delegate_->DeprecatedGetWebContents();
[email protected]fbc5e5f92012-01-02 06:08:32768}
769
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57770BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55771 return browser_context_;
772}
773
[email protected]d202a7c2012-01-04 07:53:47774void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30775 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36776 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57777 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47778 // Note that it's possible for `entries_` to contain multiple entries at this
779 // point, as Restore() might be called on a NavigationController that is
780 // already used (e.g. due to WebView's restoreState() API), not only for fresh
781 // NavigationControllers. These entries are not cleared to preserve legacy
782 // behavior and also because `pending_entry_` might point to one of the
783 // pre-existing entries. An exception for this is when `entries_` contains
784 // only the initial NavigationEntry, which must be removed.
785
786 // Do not proceed if selected_navigation will be out of bounds for the updated
787 // entries_ list, since it will be assigned to last_committed_entry_index_ and
788 // used to index entries_.
789 // TODO(https://crbug.com/1287624): Consider also returning early if entries
790 // is empty, since there should be no work to do (rather than marking the
791 // existing entries as needing reload). Also consider returning early if the
792 // selected index is -1, which represents a no-committed-entry state.
793 if (selected_navigation < -1 ||
794 selected_navigation >=
795 base::checked_cast<int>(entries->size() + entries_.size())) {
796 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24797 }
Charlie Reis23c26da2022-01-29 00:57:47798
Rakina Zata Amni46087a12022-11-11 08:28:38799 // There will always be at least one entry (new NavigationControllers will
800 // have the initial NavigationEntry).
801 if (selected_navigation == -1)
802 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47803
Rakina Zata Amni46087a12022-11-11 08:28:38804 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
805 // If we are on the initial NavigationEntry, it must be the only entry in
806 // the list. Since it's impossible to do a history navigation to the
807 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
808 // `pending_entry` might be set for a new non-history navigation).
809 // Note that we should not clear `entries_` if `entries` is empty (when
810 // InitialNavigationEntry mode is enabled), since that would leave us
811 // without any NavigationEntry.
812 CHECK_EQ(1, GetEntryCount());
813 CHECK_EQ(-1, pending_entry_index_);
814 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47815 }
[email protected]ce3fa3c2009-04-20 19:55:57816
[email protected]ce3fa3c2009-04-20 19:55:57817 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44818 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03819 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47820 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43821 if (entry->GetURL().is_empty()) {
822 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01823 // persisting the initial NavigationEntry [which is no longer possible but
824 // some old persisted sessions might still contain it] or when the
825 // serializer failed to write the URL because it's too long). Trying to
826 // restore and navigate to an entry with an empty URL will result in
827 // crashes, so change the URL to about:blank. See also
828 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43829 entry->SetURL(GURL(url::kAboutBlankURL));
830 }
dcheng36b6aec92015-12-26 06:16:36831 entries_.push_back(
832 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47833 }
avif16f85a72015-11-13 18:25:03834
835 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
836 // cleared out safely.
837 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57838
839 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36840 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57841}
842
toyoshim6142d96f2016-12-19 09:07:25843void NavigationControllerImpl::Reload(ReloadType reload_type,
844 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03845 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
846 (int)reload_type);
847 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
848 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28849 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28850 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32851 int current_index = -1;
852
Carlos IL42b416592019-10-07 23:10:36853 if (entry_replaced_by_post_commit_error_) {
854 // If there is an entry that was replaced by a currently active post-commit
855 // error navigation, this can't be the initial navigation.
856 DCHECK(!IsInitialNavigation());
857 // If the current entry is a post commit error, we reload the entry it
858 // replaced instead. We leave the error entry in place until a commit
859 // replaces it, but the pending entry points to the original entry in the
860 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
861 // case that pending_entry_ != entries_[pending_entry_index_].
862 entry = entry_replaced_by_post_commit_error_.get();
863 current_index = GetCurrentEntryIndex();
864 } else if (IsInitialNavigation() && pending_entry_) {
865 // If we are reloading the initial navigation, just use the current
866 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32867 entry = pending_entry_;
868 // The pending entry might be in entries_ (e.g., after a Clone), so we
869 // should also update the current_index.
870 current_index = pending_entry_index_;
871 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00872 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32873 current_index = GetCurrentEntryIndex();
874 if (current_index != -1) {
creis3da03872015-02-20 21:12:32875 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32876 }
[email protected]979a4bc2013-04-24 01:27:15877 }
[email protected]241db352013-04-22 18:04:05878
[email protected]59167c22013-06-03 18:07:32879 // If we are no where, then we can't reload. TODO(darin): We should add a
880 // CanReload method.
881 if (!entry)
882 return;
883
Rakina Zata Amnif297a802022-01-18 03:53:43884 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
885 // We should never navigate to an existing initial NavigationEntry that is
886 // the initial NavigationEntry for the initial empty document that hasn't
887 // been overridden by the synchronous about:blank commit, to preserve
888 // legacy behavior where trying to reload when the main frame is on the
889 // initial empty document won't result in a navigation. See also
890 // https://crbug.com/1277414.
891 return;
892 }
893
Aran Gilman37d11632019-10-08 23:07:15894 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30895 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07896 // they really want to do this. If they do, the dialog will call us back
897 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57898 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02899
[email protected]106a0812010-03-18 00:15:12900 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57901 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47902 return;
initial.commit09911bf2008-07-26 23:55:29903 }
Lei Zhang96031532019-10-10 19:05:47904
Wang Huia25efabc2022-09-24 17:27:22905 // Set ReloadType for |entry|.
906 entry->set_reload_type(reload_type);
907
Lei Zhang96031532019-10-10 19:05:47908 if (!IsInitialNavigation())
909 DiscardNonCommittedEntries();
910
911 pending_entry_ = entry;
912 pending_entry_index_ = current_index;
913 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
914
Nate Chapin45f620582021-09-30 17:45:43915 // location.reload() goes through BeginNavigation, so all reloads triggered
916 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13917 NavigateToExistingPendingEntry(
918 reload_type,
919 /*initiator_rfh=*/nullptr,
920 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
921 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29922}
923
[email protected]d202a7c2012-01-04 07:53:47924void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48925 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12926}
927
[email protected]d202a7c2012-01-04 07:53:47928void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49929 // If the pending reload type has been cleared by another navigation
930 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48931 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49932 return;
[email protected]106a0812010-03-18 00:15:12933 }
Wang Hui96ab1012022-10-11 02:05:49934 Reload(pending_reload_, false);
935 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12936}
937
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57938bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09939 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11940}
941
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57942bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38943 // Check that we're on the initial NavigationEntry and that this is not a
944 // cloned tab.
945 return IsInitialNavigation() && GetEntryCount() == 1 &&
946 GetLastCommittedEntry()->IsInitialEntry() &&
947 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40948}
949
Aran Gilman37d11632019-10-08 23:07:15950NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
951 int nav_entry_id) const {
avi254eff02015-07-01 08:27:58952 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:03953 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:58954}
955
Adithya Srinivasan9b0c99c2021-08-10 15:19:45956NavigationEntryImpl*
957NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
958 int nav_entry_id) const {
959 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
960 if (entry)
961 return entry;
962 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:52963 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:45964 : nullptr;
965}
966
W. James MacLeanc07dc41b2022-07-25 18:52:16967void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:57968 const url::Origin& origin) {
969 for (int i = 0; i < GetEntryCount(); i++) {
970 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:16971 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57972 }
973 if (entry_replaced_by_post_commit_error_) {
974 // It's possible we could come back to this entry if the error
975 // page/interstitial goes away.
976 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:16977 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57978 }
W. James MacLean1c40862c2020-04-27 21:05:57979}
980
avi25764702015-06-23 15:43:37981void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:57982 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:00983 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:37984 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:27985 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:20986}
987
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57988NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:47989 if (pending_entry_)
990 return pending_entry_;
991 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:20992}
993
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57994NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:32995 // The pending entry is safe to return for new (non-history), browser-
996 // initiated navigations. Most renderer-initiated navigations should not
997 // show the pending entry, to prevent URL spoof attacks.
998 //
999 // We make an exception for renderer-initiated navigations in new tabs, as
1000 // long as no other page has tried to access the initial empty document in
1001 // the new tab. If another page modifies this blank page, a URL spoof is
1002 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321003 bool safe_to_show_pending =
1004 pending_entry_ &&
1005 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091006 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321007 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461008 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321009
1010 // Also allow showing the pending entry for history navigations in a new tab,
1011 // such as Ctrl+Back. In this case, no existing page is visible and no one
1012 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151013 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1014 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321015 safe_to_show_pending = true;
1016
1017 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191018 return pending_entry_;
1019 return GetLastCommittedEntry();
1020}
1021
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571022int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201023 if (pending_entry_index_ != -1)
1024 return pending_entry_index_;
1025 return last_committed_entry_index_;
1026}
1027
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571028NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381029 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031030 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201031}
1032
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571033bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351034 const std::string& mime_type = frame_tree_->root()
1035 ->current_frame_host()
1036 ->GetPage()
1037 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531038 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1039 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271040 NavigationEntry* visible_entry = GetVisibleEntry();
1041 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391042 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161043}
1044
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571045int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271046 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451047 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271048 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551049 return last_committed_entry_index_;
1050}
1051
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571052int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451053 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291054 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551055 return static_cast<int>(entries_.size());
1056}
1057
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571058NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371059 if (index < 0 || index >= GetEntryCount())
1060 return nullptr;
1061
avif16f85a72015-11-13 18:25:031062 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251063}
1064
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571065NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471066 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201067}
1068
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571069int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461070 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031071}
1072
Kevin McNee3b3a56192023-03-17 14:40:591073absl::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031074 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591075 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1076 return index;
1077 }
Shivani Sharma298d12852019-01-22 20:04:031078 }
Kevin McNee3b3a56192023-03-17 14:40:591079 return absl::nullopt;
1080}
1081
1082bool NavigationControllerImpl::CanGoBack() {
1083 return GetIndexForGoBack().has_value();
1084}
1085
1086absl::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
1087 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1088 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1089 return index;
1090 }
1091 }
1092 return absl::nullopt;
[email protected]765b35502008-08-21 00:51:201093}
1094
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571095bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591096 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201097}
1098
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571099bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031100 int index = GetIndexForOffset(offset);
1101 return index >= 0 && index < GetEntryCount();
1102}
1103
Xiaohan Wang7f8052e02022-01-14 18:44:281104#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151105bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151106 if (offset == 0)
1107 return true;
1108 int increment = offset > 0 ? 1 : -1;
1109 int non_skippable_entries = 0;
1110 for (int index = GetIndexForOffset(increment);
1111 index >= 0 && index < GetEntryCount(); index += increment) {
1112 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1113 non_skippable_entries++;
1114
1115 if (non_skippable_entries == std::abs(offset))
1116 return true;
1117 }
1118 return false;
1119}
1120#endif
1121
[email protected]d202a7c2012-01-04 07:53:471122void NavigationControllerImpl::GoBack() {
Kevin McNee3b3a56192023-03-17 14:40:591123 const absl::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061124
Kevin McNeeedc481c2023-04-27 22:30:581125 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211126
Kevin McNee3b3a56192023-03-17 14:40:591127 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201128}
1129
[email protected]d202a7c2012-01-04 07:53:471130void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161131 // Note that at least one entry (the last one) will be non-skippable since
1132 // entries are marked skippable only when they add another entry because of
1133 // redirect or pushState.
Kevin McNee3b3a56192023-03-17 14:40:591134 const absl::optional<int> target_index = GetIndexForGoForward();
1135
Kevin McNeeedc481c2023-04-27 22:30:581136 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591137
1138 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201139}
1140
[email protected]d202a7c2012-01-04 07:53:471141void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131142 GoToIndex(index, /*initiator_rfh=*/nullptr,
1143 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
1144 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161145}
1146
Nate Chapinbf682fa32022-09-26 22:41:201147void NavigationControllerImpl::GoToIndex(
1148 int index,
1149 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131150 absl::optional<blink::scheduler::TaskAttributionId>
1151 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201152 const std::string* navigation_api_key) {
sunjian30574a62017-03-21 21:39:441153 TRACE_EVENT0("browser,navigation,benchmark",
1154 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501155 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1156 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1157 entries_.size());
1158 // Indices should have have been validated by the caller.
1159 CHECK_GE(index, 0);
1160 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201161
Rakina Zata Amnif297a802022-01-18 03:53:431162 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1163 // We should never navigate to an existing initial NavigationEntry that is
1164 // the initial NavigationEntry for the initial empty document that hasn't
1165 // been overridden by the synchronous about:blank commit, to preserve
1166 // legacy behavior where trying to reload when the main frame is on the
1167 // initial empty document won't result in a navigation. See also
1168 // https://crbug.com/1277414.
1169 return;
1170 }
1171
[email protected]cbab76d2008-10-13 22:42:471172 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201173
arthursonzogni5c4c202d2017-04-25 23:41:271174 DCHECK_EQ(nullptr, pending_entry_);
1175 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431176
arthursonzogni5c4c202d2017-04-25 23:41:271177 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201178 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271179 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1180 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201181 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131182 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201183 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201184}
1185
[email protected]d202a7c2012-01-04 07:53:471186void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121187 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031188 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201189 return;
1190
[email protected]9ba14052012-06-22 23:50:031191 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201192}
1193
Nate Chapinbf682fa32022-09-26 22:41:201194void NavigationControllerImpl::GoToOffsetFromRenderer(
1195 int offset,
Yoav Weiss8c573952022-11-17 17:35:131196 RenderFrameHostImpl* initiator_rfh,
1197 absl::optional<blink::scheduler::TaskAttributionId>
1198 soft_navigation_heuristics_task_id) {
Nate Chapin758e5e482023-05-02 00:22:551199 // If the renderer sent an out-of-bounds offset, cancel and notify the
1200 // renderer.
1201 if (!CanGoToOffset(offset)) {
1202 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
1203 /*navigation_api_key=*/std::string(),
1204 blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapin45f620582021-09-30 17:45:431205 return;
Nate Chapin758e5e482023-05-02 00:22:551206 }
Nate Chapin45f620582021-09-30 17:45:431207
Nate Chapinbf682fa32022-09-26 22:41:201208 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131209 soft_navigation_heuristics_task_id,
1210 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431211}
1212
Xiaohan Wang7f8052e02022-01-14 18:44:281213#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151214void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1215 // Note: This is actually reached in unit tests.
1216 if (!CanGoToOffsetWithSkipping(offset))
1217 return;
1218
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421219 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151220 GoToIndex(GetIndexForOffset(offset));
1221 return;
1222 }
1223 int increment = offset > 0 ? 1 : -1;
1224 // Find the offset without counting skippable entries.
1225 int target_index = GetIndexForOffset(increment);
1226 int non_skippable_entries = 0;
1227 for (int index = target_index; index >= 0 && index < GetEntryCount();
1228 index += increment) {
1229 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1230 non_skippable_entries++;
1231
1232 if (non_skippable_entries == std::abs(offset)) {
1233 target_index = index;
1234 break;
1235 }
1236 }
1237
1238 GoToIndex(target_index);
1239}
1240#endif
1241
[email protected]41374f12013-07-24 02:49:281242bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151243 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281244 return false;
[email protected]6a13a6c2011-12-20 21:47:121245
[email protected]43032342011-03-21 14:10:311246 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281247 return true;
[email protected]cbab76d2008-10-13 22:42:471248}
1249
Michael Thiessen9b14d512019-09-23 21:19:471250void NavigationControllerImpl::PruneForwardEntries() {
1251 DiscardNonCommittedEntries();
1252 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471253 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471254 if (num_removed <= 0)
1255 return;
Nate Chapin9eb16be72022-09-23 22:54:311256 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471257 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1258 NotifyPrunedEntries(this, remove_start_index /* start index */,
1259 num_removed /* count */);
1260}
1261
Aran Gilman37d11632019-10-08 23:07:151262void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1263 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321264 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311265 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511266 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1267 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321268 }
1269}
1270
Harkiran Bolariaba823e42021-05-21 18:30:361271base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1272 const GURL& url,
1273 const Referrer& referrer,
1274 ui::PageTransition transition,
1275 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471276 LoadURLParams params(url);
1277 params.referrer = referrer;
1278 params.transition_type = transition;
1279 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361280 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471281}
1282
Harkiran Bolariaba823e42021-05-21 18:30:361283base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1284 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061285 if (params.is_renderer_initiated)
1286 DCHECK(params.initiator_origin.has_value());
1287
naskob8744d22014-08-28 17:07:431288 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151289 "NavigationControllerImpl::LoadURLWithParams", "url",
1290 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291291 bool is_explicit_navigation =
1292 GetContentClient()->browser()->IsExplicitNavigation(
1293 params.transition_type);
1294 if (HandleDebugURL(params.url, params.transition_type,
1295 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431296 // If Telemetry is running, allow the URL load to proceed as if it's
1297 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491298 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431299 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361300 return nullptr;
[email protected]47752982014-07-29 08:01:431301 }
[email protected]8bf1048012012-02-08 01:22:181302
[email protected]cf002332012-08-14 19:17:471303 // Checks based on params.load_type.
1304 switch (params.load_type) {
1305 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431306 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471307 break;
1308 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261309 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471310 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361311 return nullptr;
[email protected]cf002332012-08-14 19:17:471312 }
1313 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461314 }
[email protected]e47ae9472011-10-13 19:48:341315
[email protected]e47ae9472011-10-13 19:48:341316 // The user initiated a load, we don't need to reload anymore.
1317 needs_reload_ = false;
1318
Harkiran Bolariaba823e42021-05-21 18:30:361319 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441320}
1321
Mohamed Abdelhalim833de902019-09-16 17:41:451322bool NavigationControllerImpl::PendingEntryMatchesRequest(
1323 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191324 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451325 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191326}
1327
[email protected]d202a7c2012-01-04 07:53:471328bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321329 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071330 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331331 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441332 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251333 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471334 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131335 NavigationRequest* navigation_request) {
1336 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331337
1338 // Note: validation checks and renderer kills due to invalid commit messages
1339 // must happen before getting here, in
1340 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1341 // effects of the navigation have already occurred.
1342
[email protected]cd2e15742013-03-08 04:08:311343 is_initial_navigation_ = false;
1344
Wang Hui96ab1012022-10-11 02:05:491345 // Any pending request to repost a form submission is no longer valid, since a
1346 // different NavigationEntry is committing.
1347 pending_reload_ = ReloadType::NONE;
1348
[email protected]0e8db942008-09-24 21:21:481349 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431350 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451351 if (entry_replaced_by_post_commit_error_) {
1352 // Same document navigation events with a post-commit error should already
1353 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1354 // reaching here.
1355 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331356
Rakina Zata Amnie2d31312022-11-18 03:38:451357 // Any commit while a post-commit error page is showing should put the
1358 // original entry back, replacing the error page's entry. This includes
1359 // reloads, where the original entry was used as the pending entry and
1360 // should now be at the correct index at commit time.
1361 entries_[last_committed_entry_index_] =
1362 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481363 }
Rakina Zata Amnie2d31312022-11-18 03:38:451364 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1365 details->previous_entry_index = GetLastCommittedEntryIndex();
1366 if (PendingEntryMatchesRequest(navigation_request) &&
1367 pending_entry_->GetIsOverridingUserAgent() !=
1368 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1369 overriding_user_agent_changed = true;
1370 }
1371#if BUILDFLAG(IS_ANDROID)
1372 // TODO(crbug.com/1266277): Clean up the logic of setting
1373 // |overriding_user_agent_changed| post-launch.
Shu Yang7a3ec532023-06-21 17:49:001374 // Must honor user agent overrides in the |navigation_request|, such as
1375 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1376 // result, besides comparing |pending_entry_|'s user agent against
1377 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1378 // agent against LastCommittedEntry's.
1379 if (navigation_request->is_overriding_user_agent() !=
1380 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1381 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451382 }
1383#endif // BUILDFLAG(IS_ANDROID)
[email protected]ecd9d8702008-08-28 22:10:171384
Dave Tapuskaa2ab4f252021-07-08 21:31:281385 bool is_main_frame_navigation = !rfh->GetParent();
1386
Alexander Timind2f2e4f22019-04-02 20:04:531387 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1388 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281389 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141390 // BackForwardCacheMetrics to be associated with the new navigation's
1391 // NavigationEntry, by either creating a new object or reusing the previous
1392 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281393 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Arthur Sonzognif6785ec2022-12-05 10:11:501394 if (navigation_request->frame_tree_node()->frame_tree().type() ==
Dave Tapuskaa2ab4f252021-07-08 21:31:281395 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141396 back_forward_cache_metrics = BackForwardCacheMetrics::
1397 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281398 GetLastCommittedEntry(), is_main_frame_navigation,
1399 params.document_sequence_number);
1400 }
Yuzu Saijo29f96ca92022-12-08 04:54:121401
Alexander Timind2f2e4f22019-04-02 20:04:531402 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281403 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451404 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1405 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531406 }
1407 }
1408
Rakina Zata Amnifd8370b2022-11-14 13:32:251409 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1410 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091411 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251412 details->did_replace_entry =
1413 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091414
fdegans9caf66a2015-07-30 21:10:421415 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111416 // except for restored entries. This should be true even if the current commit
1417 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291418 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481419 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081420 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111421
1422 // Only make changes based on the pending entry if the NavigationRequest
1423 // matches it. Otherwise, the pending entry may be for a different request
1424 // (e.g., if a slow history navigation is pending while an auto-subframe
1425 // commit occurs).
1426 if (PendingEntryMatchesRequest(navigation_request)) {
1427 // It is no longer necessary to consider the pending entry as restored.
1428 if (pending_entry_->IsRestored()) {
1429 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1430 was_restored = true;
1431 }
[email protected]e9ba4472008-09-14 15:42:431432
Charlie Reisf8cde712022-10-20 16:25:091433 // If the SiteInstance has changed from the matching pending entry, this
1434 // must be treated as a new navigation with replacement. Set the replacement
1435 // bit here and ClassifyNavigation will identify this case and return
1436 // NEW_ENTRY.
1437 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1438 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1439 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251440 // TODO(nasko,creis,rakina): Move this to happen before committing the
1441 // navigation. This is a bit complicated because we don't currently
1442 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091443 details->did_replace_entry = true;
1444 }
Nasko Oskovaee2f862018-06-15 00:05:521445 }
[email protected]bcd904482012-02-01 01:54:221446
[email protected]e9ba4472008-09-14 15:42:431447 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101448 NavigationType navigation_type =
1449 ClassifyNavigation(rfh, params, navigation_request);
1450 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451451
Rakina Zata Amnie2d31312022-11-18 03:38:451452 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451453 // Ensure that this navigation does not add a navigation entry, since
1454 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1455 // beyond the last committed one. Therefore, `should_replace_current_entry`
1456 // should be set, which replaces the current entry, or this should be a
1457 // reload, which does not create a new entry.
1458 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1459 // navigation that is restored will not be creating a new entry anyways, so
1460 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1461 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1462 // pointed out in the issue.
Rakina Zata Amnifd8370b2022-11-14 13:32:251463 DCHECK(navigation_request->common_params().should_replace_current_entry ||
shivanigithub189833f2022-04-27 18:08:451464 navigation_request->GetReloadType() != ReloadType::NONE ||
Miyoung Shin3299cbf2022-11-22 01:41:101465 navigation_type == NAVIGATION_TYPE_AUTO_SUBFRAME);
shivanigithub189833f2022-04-27 18:08:451466 }
1467
Rakina Zata Amnie2d31312022-11-18 03:38:451468 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551469 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241470 // This is a subframe navigation on the initial empty document, which used
1471 // to not have a NavigationEntry to attach to. Now it can attach to the
1472 // initial NavigationEntry, and we must ensure that its NavigationEntry
1473 // will keep the "initial NavigationEntry" status and won't append a new
1474 // NavigationEntry (it should always do replacement instead).
1475 // See also https://crbug.com/1277414.
1476 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551477 // Subframe navigation on initial NavigationEntry must not append a new
1478 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1479 // means every subframe navigation that happens while we're on the initial
1480 // NavigationEntry will always reuse the existing NavigationEntry and
1481 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101482 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1483 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551484 // This is a navigation that modifies the initial NavigationEntry, either
1485 // for a replacement or a reload. The initial NavigationEntry should
1486 // retain its "initial NavigationEntry" status in this case.
1487 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241488 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251489 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1490 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241491 // This is a synchronous about:blank navigation on the main frame, which
1492 // used to not create a NavigationEntry when we have no NavigationEntry on
1493 // FrameTree creation. We now have the initial NavigationEntry and are on
1494 // the initial NavigationEntry. To preserve old behavior, we should still
1495 // keep the "initial" status for the new NavigationEntry that we will
1496 // create for this navigation, so that subframe navigations under the
1497 // synchronously committed about:blank document will never append new
1498 // NavigationEntry, and instead will just reuse the initial
1499 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1500 // See also https://crbug.com/1277414.
1501 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551502 }
1503 }
1504 DCHECK(!details->should_stay_as_initial_entry ||
1505 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201506
eugenebutee08663a2017-04-27 17:43:121507 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441508 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121509
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071510 details->is_prerender_activation =
1511 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241512 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1513 ->GetOutermostMainFrame()
1514 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071515
Peter Boströmd7592132019-01-30 04:50:311516 // Make sure we do not discard the pending entry for a different ongoing
1517 // navigation when a same document commit comes in unexpectedly from the
1518 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1519 // other navigation types. See https://crbug.com/900036.
1520 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061521 bool keep_pending_entry =
1522 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101523 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061524 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311525
Miyoung Shin3299cbf2022-11-22 01:41:101526 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061527 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491528 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051529 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;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061532 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491533 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1534 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001535 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431536 break;
[email protected]8ff00d72012-10-23 19:12:211537 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471538 RendererDidNavigateNewSubframe(
1539 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001540 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431541 break;
[email protected]8ff00d72012-10-23 19:12:211542 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391543 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251544 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001545 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081546 // We don't send a notification about auto-subframe PageState during
1547 // UpdateStateForFrame, since it looks like nothing has changed. Send
1548 // it here at commit time instead.
1549 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431550 return false;
creis59d5a47cb2016-08-24 23:57:191551 }
[email protected]e9ba4472008-09-14 15:42:431552 break;
Aran Gilman37d11632019-10-08 23:07:151553 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431554 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151555 break;
[email protected]765b35502008-08-21 00:51:201556 }
1557
[email protected]688aa65c62012-09-28 04:32:221558 // At this point, we know that the navigation has just completed, so
1559 // record the time.
1560 //
1561 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261562 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331563 base::Time timestamp =
1564 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1565 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131566 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221567
Peter Boströmd7592132019-01-30 04:50:311568 // If we aren't keeping the pending entry, there shouldn't be one at this
1569 // point. Clear it again in case any error cases above forgot to do so.
1570 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1571 // been cleared instead of protecting against it.
1572 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551573 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141574
[email protected]e9ba4472008-09-14 15:42:431575 // All committed entries should have nonempty content state so WebKit doesn't
1576 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471577 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321578 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221579 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441580 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141581
Alexander Timind2f2e4f22019-04-02 20:04:531582 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1583 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281584 if (back_forward_cache_metrics &&
1585 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531586 active_entry->set_back_forward_cache_metrics(
1587 std::move(back_forward_cache_metrics));
1588 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281589
1590 // `back_forward_cache_metrics()` may return null as we do not record
1591 // back-forward cache metrics for navigations in non-primary frame trees.
1592 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141593 // TODO(https://crbug.com/1338089): Remove this.
1594 // These are both only available from details at this point, so we capture
1595 // them here.
1596 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101597 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141598 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1599 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281600 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1601 navigation_request,
1602 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1603 }
naskoc7533512016-05-06 17:01:121604
Charles Reisc0507202017-09-21 00:40:021605 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1606 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1607 // A mismatch can occur if the renderer lies or due to a unique name collision
1608 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121609 FrameNavigationEntry* frame_entry =
1610 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021611 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1612 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031613 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081614 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1615 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031616 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201617
1618 // Remember the bindings the renderer process has at this point, so that
1619 // we do not grant this entry additional bindings if we come back to it.
1620 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301621 }
[email protected]132e281a2012-07-31 18:32:441622
[email protected]97d8f0d2013-10-29 16:49:211623 // Once it is committed, we no longer need to track several pieces of state on
1624 // the entry.
naskoc7533512016-05-06 17:01:121625 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131626
[email protected]49bd30e62011-03-22 20:12:591627 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221628 // TODO(creis): This check won't pass for subframes until we create entries
1629 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001630 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421631 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591632
[email protected]e9ba4472008-09-14 15:42:431633 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001634 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001635 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311636 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531637
arthursonzogni7ddc6542021-04-09 09:16:501638 active_entry->SetIsOverridingUserAgent(
1639 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031640
[email protected]93f230e02011-06-01 14:40:001641 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291642
aelias100c9192017-01-13 00:01:431643 if (overriding_user_agent_changed)
1644 delegate_->UpdateOverridingUserAgent();
1645
creis03b48002015-11-04 00:54:561646 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1647 // one knows the latest NavigationEntry it is showing (whether it has
1648 // committed anything in this navigation or not). This allows things like
1649 // state and title updates from RenderFrames to apply to the latest relevant
1650 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381651 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031652 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381653 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431654
1655 if (navigation_request->IsPrerenderedPageActivation()) {
1656 BroadcastHistoryOffsetAndLength();
1657 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1658 // is activated. As a result, a "prerenderingchange" event listener sees the
1659 // history.length which is not updated yet. We should guarantee that
1660 // history's length and offset should be updated before a
1661 // "prerenderingchange" event listener runs. One possible approach is to use
1662 // the same IPC which "prerenderingchange" uses, and propagate history's
1663 // length and offset together with that.
1664 }
1665
[email protected]e9ba4472008-09-14 15:42:431666 return true;
initial.commit09911bf2008-07-26 23:55:291667}
1668
[email protected]8ff00d72012-10-23 19:12:211669NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321670 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101671 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241672 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591673 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511674 "ClassifyNavigation");
1675
avi7c6f35e2015-05-08 17:52:381676 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241677 // A new entry. We may or may not have a corresponding pending entry, and
1678 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001679 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491680 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061681 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381682 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241683 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511684 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381685 return NAVIGATION_TYPE_NEW_SUBFRAME;
1686 }
1687
Charlie Reisc0f17d2d2021-01-12 18:52:491688 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381689 DCHECK(!params.history_list_was_cleared);
1690
avi39c1edd32015-06-04 20:06:001691 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381692 // All manual subframes would be did_create_new_entry and handled above, so
1693 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081694 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1695 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381696 }
1697
Rakina Zata Amnif6950d552020-11-24 03:26:101698 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1699 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381700 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1701 // create a new page.
1702
Hayato Ito2ae49442021-07-02 02:59:251703 // This main frame navigation is not a history navigation (since
1704 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1705 // reload or a replacement navigation, which will modify the existing entry.
1706 //
Nasko Oskov332593c2018-08-16 17:21:341707 // TODO(nasko): With error page isolation, reloading an existing session
1708 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491709 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341710 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511711 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491712 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061713 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381714 }
1715
Charlie Reisf8cde712022-10-20 16:25:091716 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521717 // If the SiteInstance of the |pending_entry_| does not match the
1718 // SiteInstance that got committed, treat this as a new navigation with
1719 // replacement. This can happen if back/forward/reload encounters a server
1720 // redirect to a different site or an isolated error page gets successfully
1721 // reloaded into a different SiteInstance.
1722 if (pending_entry_->site_instance() &&
1723 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491724 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061725 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521726 }
creis77c9aa32015-09-25 19:59:421727
Nasko Oskovaee2f862018-06-15 00:05:521728 if (pending_entry_index_ == -1) {
1729 // In this case, we have a pending entry for a load of a new URL but Blink
1730 // didn't do a new navigation (params.did_create_new_entry). First check
1731 // to make sure Blink didn't treat a new cross-process navigation as
1732 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161733 // we must treat it as NEW rather than the converted reload case below,
1734 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451735 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161736 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061737 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521738 }
1739
1740 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161741 // We will create a pending entry, but NavigateWithoutEntry will convert
1742 // it to a reload since it's the same page and not create a new entry for
1743 // it. (The user doesn't want to have a new back/forward entry when they
1744 // do this.) Therefore we want to just ignore the pending entry and go
1745 // back to where we were (the "existing entry").
1746 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061747 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521748 }
avi7c6f35e2015-05-08 17:52:381749 }
1750
Rakina Zata Amni153d5702021-09-13 22:48:001751 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381752 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491753 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1754 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161755 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061756 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381757 }
1758
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121759 if (navigation_request->DidEncounterError() &&
1760 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101761 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381762 // If the renderer was going to a new pending entry that got cleared because
1763 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491764 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381765 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511766 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491767 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061768 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381769 }
1770
Charlie Reisc0f17d2d2021-01-12 18:52:491771 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101772 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511773 trace_return.traced_value()->SetInteger("existing_entry_index",
1774 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381775 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441776 // The renderer has committed a navigation to an entry that no longer
1777 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491778 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061779 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381780 }
1781
avi7c6f35e2015-05-08 17:52:381782 // Since we weeded out "new" navigations above, we know this is an existing
1783 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491784 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061785 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381786}
1787
Rakina Zata Amni3460d382021-10-29 00:43:371788void NavigationControllerImpl::UpdateNavigationEntryDetails(
1789 NavigationEntryImpl* entry,
1790 RenderFrameHostImpl* rfh,
1791 const mojom::DidCommitProvisionalLoadParams& params,
1792 NavigationRequest* request,
1793 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001794 bool is_new_entry,
1795 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371796 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171797 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371798 entry->AddOrUpdateFrameEntry(
1799 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571800 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371801 rfh->GetSiteInstance(), nullptr, params.url,
1802 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171803 Referrer(*params.referrer),
1804 request ? request->common_params().initiator_origin : params.origin,
W. James MacLean23e90a12022-12-21 04:38:211805 request ? request->common_params().initiator_base_url : absl::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171806 request ? request->GetRedirectChain() : redirects, params.page_state,
1807 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371808 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171809 rfh, request && request->IsSameDocument(),
1810 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371811
1812 if (rfh->GetParent()) {
1813 // Only modify the NavigationEntry for main frame navigations.
1814 return;
1815 }
1816 if (entry->update_virtual_url_with_url())
1817 UpdateVirtualURLToURL(entry, params.url);
1818 // Don't use the page type from the pending entry. Some interstitial page
1819 // may have set the type to interstitial. Once we commit, however, the page
1820 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171821 entry->set_page_type((request && request->DidEncounterError())
1822 ? PAGE_TYPE_ERROR
1823 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431824 if (commit_details && commit_details->should_stay_as_initial_entry) {
1825 // Retain the "initial NavigationEntry" status.
1826 if (request->IsSameDocument()) {
1827 // If this is for a same-document navigation, the NavigationEntry must be
1828 // reused and should already be marked as the initial NavigationEntry.
1829 DCHECK(entry->IsInitialEntry());
1830 } else {
1831 // If this is for a cross-document navigation, it can be caused by a
1832 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1833 // "for synchronous about:blank" in the latter case, and also when it is
1834 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1835 // is not for a synchronous about:blank commit.
1836 NavigationEntryImpl::InitialNavigationEntryState new_state =
1837 NavigationEntryImpl::InitialNavigationEntryState::
1838 kInitialNotForSynchronousAboutBlank;
1839 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1840 request->is_synchronous_renderer_commit()) {
1841 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1842 kInitialForSynchronousAboutBlank;
1843 }
1844 entry->set_initial_navigation_entry_state(new_state);
1845 }
1846 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1847 // Remove the "initial NavigationEntry" status.
1848 entry->set_initial_navigation_entry_state(
1849 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001850 }
Rakina Zata Amniddf10502022-01-15 02:56:551851
Rakina Zata Amni3460d382021-10-29 00:43:371852 if (is_new_entry) {
1853 // Some properties of the NavigationEntry are only set when the entry is
1854 // new (we aren't reusing it).
1855 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171856 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1857 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371858 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1859 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1860 } else {
1861 // We are reusing the NavigationEntry. The site instance will normally be
1862 // the same except for a few cases:
1863 // 1) session restore, when no site instance will be assigned or
1864 // 2) redirect, when the site instance is reset.
1865 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1866 entry->site_instance() == rfh->GetSiteInstance());
1867 }
1868}
1869
Rakina Zata Amniafd3c6582021-11-30 06:19:171870void NavigationControllerImpl::CreateInitialEntry() {
1871 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031872 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171873 auto params = mojom::DidCommitProvisionalLoadParams::New();
1874 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1875 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1876 // before we have initial NavigationEntries.
1877 params->url = GURL::EmptyGURL();
1878 params->http_status_code = 0;
1879 params->url_is_unreachable = false;
1880 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171881 params->post_id = -1;
1882 params->embedding_token = base::UnguessableToken::Create();
1883 params->navigation_token = base::UnguessableToken::Create();
1884 params->did_create_new_entry = true;
1885 params->origin = rfh->GetLastCommittedOrigin();
1886 params->should_update_history = true;
1887 params->item_sequence_number = 0;
1888 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151889 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171890 params->transition = is_in_fenced_frame_tree
1891 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1892 : ui::PAGE_TRANSITION_LINK;
1893 params->referrer = blink::mojom::Referrer::New();
1894
Rakina Zata Amniafd3c6582021-11-30 06:19:171895 auto new_entry = std::make_unique<NavigationEntryImpl>(
1896 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381897 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211898 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1899 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1900 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171901 UpdateNavigationEntryDetails(
1902 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001903 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1904 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171905
1906 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1907 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001908 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171909}
1910
Charlie Reisc0f17d2d2021-01-12 18:52:491911void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321912 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071913 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361914 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441915 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471916 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001917 NavigationRequest* request,
1918 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571919 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071920 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451921 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:521922 absl::optional<GURL> initiator_base_url;
1923 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
1924 initiator_base_url = request->common_params().initiator_base_url;
1925 }
Lukasz Anforowicz435bcb582019-07-12 20:50:061926
creisf49dfc92016-07-26 17:05:181927 // First check if this is an in-page navigation. If so, clone the current
1928 // entry instead of looking at the pending entry, because the pending entry
1929 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451930 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301931 FrameNavigationEntry* previous_frame_entry =
1932 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451933 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481934 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571935 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:081936 rfh->GetSiteInstance(), nullptr, params.url,
1937 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:211938 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:091939 request->GetRedirectChain(), params.page_state, params.method,
1940 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:391941 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301942 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:571943 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:301944 // FrameNavigationEntry.
1945 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:571946 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:031947
creisf49dfc92016-07-26 17:05:181948 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:031949 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:521950 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1951 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571952 // TODO(jam): we had one report of this with a URL that was redirecting to
1953 // only tildes. Until we understand that better, don't copy the cert in
1954 // this case.
1955 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571956 }
creisf49dfc92016-07-26 17:05:181957
Patrick Monette50e8bd82019-06-13 22:40:451958 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1959 // that |frame_entry| should now have a reference count of exactly 2: one
1960 // due to the local variable |frame_entry|, and another due to |new_entry|
1961 // also retaining one. This should never fail, because it's the main frame.
1962 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181963 }
1964
Harkiran Bolaria59290d62021-03-17 01:53:011965 // If this is an activation navigation from a prerendered page, transfer the
1966 // new entry from an entry already created and stored in the
1967 // NavigationRequest. |new_entry| will not have been set prior to this as
1968 // |is_same_document| is mutually exclusive with
1969 // |IsPrerenderedPageActivation|.
1970 if (request->IsPrerenderedPageActivation()) {
1971 DCHECK(!is_same_document);
1972 DCHECK(!new_entry);
1973 new_entry = request->TakePrerenderNavigationEntry();
1974 DCHECK(new_entry);
1975 }
1976
Charlie Reisc0f17d2d2021-01-12 18:52:491977 // Only make a copy of the pending entry if it is appropriate for the new
1978 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451979 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041980 // 1. The SiteInstance hasn't been assigned to something else.
1981 // 2. The pending entry was intended as a new entry, rather than being a
1982 // history navigation that was interrupted by an unrelated,
1983 // renderer-initiated navigation.
1984 // TODO(csharrison): Investigate whether we can remove some of the coarser
1985 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451986 if (!new_entry && PendingEntryMatchesRequest(request) &&
1987 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:341988 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:431989 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:351990 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:431991
Camille Lamy62b826012019-02-26 09:15:471992 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451993 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:181994 }
1995
Charlie Reisc0f17d2d2021-01-12 18:52:491996 // For cross-document commits with no matching pending entry, create a new
1997 // entry.
creisf49dfc92016-07-26 17:05:181998 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061999 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072000 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212001 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582002 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452003 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172004 nullptr, // blob_url_loader_factory
2005 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242006
2007 // Find out whether the new entry needs to update its virtual URL on URL
2008 // change and set up the entry accordingly. This is needed to correctly
2009 // update the virtual URL when replaceState is called after a pushState.
2010 GURL url = params.url;
2011 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492012 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412013 // update the virtual URL based on the new URL. For example, this is needed
2014 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2015 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372016 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2017 &url, browser_context_, &needs_update);
2018 new_entry->set_update_virtual_url_with_url(needs_update);
2019
Camille Lamy62b826012019-02-26 09:15:472020 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452021 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432022 }
2023
Harkiran Bolaria59290d62021-03-17 01:53:012024 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
2025 // for prerendered contents, if any. This is because prerendering/activation
2026 // technically won't be creating a new document. Unlike BFCache, prerendering
2027 // creates a new NavigationEntry rather than using an existing one.
2028 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372029 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2030 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002031 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082032
Harkiran Bolaria59290d62021-03-17 01:53:012033 // history.pushState() is classified as a navigation to a new page, but sets
2034 // is_same_document to true. In this case, we already have the title and
2035 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452036 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012037 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2038 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2039 }
[email protected]3a868f212014-08-09 10:41:192040 }
[email protected]ff64b3e2014-05-31 04:07:332041
[email protected]60d6cca2013-04-30 08:47:132042 DCHECK(!params.history_list_was_cleared || !replace_entry);
2043 // The browser requested to clear the session history when it initiated the
2044 // navigation. Now we know that the renderer has updated its state accordingly
2045 // and it is safe to also clear the browser side history.
2046 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552047 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132048 entries_.clear();
2049 last_committed_entry_index_ = -1;
2050 }
2051
Nasko Oskovaee2f862018-06-15 00:05:522052 // If this is a new navigation with replacement and there is a
2053 // pending_entry_ which matches the navigation reported by the renderer
2054 // process, then it should be the one replaced, so update the
2055 // last_committed_entry_index_ to use it.
2056 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092057 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522058 last_committed_entry_index_ = pending_entry_index_;
2059 }
2060
Alexander Timine3ec4192020-04-20 16:39:402061 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412062 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402063 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052064
Yuzu Saijoa725585f2022-11-28 04:14:032065 // If this is a history navigation and the old entry has an existing
2066 // back/forward cache metrics object, keep using the old one so that the
2067 // reasons logged from the last time the page navigated gets preserved.
2068 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2069 request)) {
2070 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2071 // because some tests do not have a pending entry.
2072 NavigationEntryImpl* entry =
2073 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2074 if (entry && entry->back_forward_cache_metrics()) {
2075 scoped_refptr<BackForwardCacheMetrics> metrics =
2076 entry->TakeBackForwardCacheMetrics();
2077 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2078 }
2079 }
2080
Carlos IL42b416592019-10-07 23:10:362081 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312082 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152083 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432084}
2085
Charlie Reisc0f17d2d2021-01-12 18:52:492086void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322087 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072088 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362089 bool is_same_document,
jam48cea9082017-02-15 06:13:292090 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452091 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002092 bool keep_pending_entry,
2093 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562094 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2095 << "that a last committed entry exists.";
2096
[email protected]e9ba4472008-09-14 15:42:432097 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002098 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432099
Charlie Reis7e2cb6d2021-01-26 01:27:162100 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002101 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162102 // We're guaranteed to have a last committed entry if intended_as_new_entry
2103 // is true.
avicbdc4c12015-07-01 16:07:112104 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162105
2106 // If the NavigationRequest matches a new pending entry and is classified as
2107 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2108 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092109 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162110 // Note: The pending entry will usually have a real ReloadType here, but
2111 // it can still be ReloadType::NONE in cases that
2112 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2113
2114 // If we classified this correctly, the SiteInstance should not have
2115 // changed.
2116 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2117
2118 // For converted reloads, we assign the entry's unique ID to be that of
2119 // the new one. Since this is always the result of a user action, we want
2120 // to dismiss infobars, etc. like a regular user-initiated navigation.
2121 entry->set_unique_id(pending_entry_->GetUniqueID());
2122
2123 // The extra headers may have changed due to reloading with different
2124 // headers.
2125 entry->set_extra_headers(pending_entry_->extra_headers());
2126 }
2127 // Otherwise, this was intended as a new entry but the pending entry was
2128 // lost in the meantime and no new entry was created. We are stuck at the
2129 // last committed entry.
2130
2131 // Even if this is a converted reload from pressing enter in the omnibox,
2132 // the server could redirect, requiring an update to the SSL status. If this
2133 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452134 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162135 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472136 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452137 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162138 }
Rakina Zata Amnif6950d552020-11-24 03:26:102139 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112140 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102141 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b90ce2016-09-01 16:58:162142
eugenebut604866f2017-05-10 21:35:362143 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452144 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362145 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2146 // this was a restored same document navigation entry, then it won't have
2147 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2148 // navigated it.
jam48cea9082017-02-15 06:13:292149 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522150 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2151 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292152 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2153 was_restored) {
2154 entry->GetSSL() = last_entry->GetSSL();
2155 }
2156 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452157 // In rapid back/forward navigations |request| sometimes won't have a cert
2158 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192159 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452160 if (request->GetSSLInfo().has_value() &&
2161 request->GetSSLInfo()->is_valid()) {
2162 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522163 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2164 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192165 entry->GetSSL() = SSLStatus();
2166 }
jam48cea9082017-02-15 06:13:292167 }
avicbdc4c12015-07-01 16:07:112168 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272169 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572170 // navigations that are EXISTING_ENTRY are same-document navigations that
2171 // result in replacement (e.g. history.replaceState(), location.replace(),
2172 // forced replacements for trivial session history contexts). For these
2173 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112174 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102175
Mikel Astizba9cf2fd2017-12-17 10:38:102176 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2177 // to avoid misleading interpretations (e.g. URLs paired with
2178 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2179 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2180 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2181
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572182 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102183
eugenebut604866f2017-05-10 21:35:362184 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452185 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362186 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472187 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452188 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112189 }
2190 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432191
Rakina Zata Amni3460d382021-10-29 00:43:372192 UpdateNavigationEntryDetails(entry, rfh, params, request,
2193 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002194 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302195
[email protected]5ccd4dc2012-10-24 02:28:142196 // The redirected to page should not inherit the favicon from the previous
2197 // page.
eugenebut604866f2017-05-10 21:35:362198 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482199 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142200
Charlie Reis951f43372023-05-05 00:30:072201 // Update the last committed index to reflect the committed entry. Do this
2202 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2203 // delegate sees the correct committed index when notified of navigation
2204 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2205 // https://crbug.com/1439948.)
2206 if (base::FeatureList::IsEnabled(
2207 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2208 last_committed_entry_index_ = GetIndexOfEntry(entry);
2209 }
2210
Peter Boströmd7592132019-01-30 04:50:312211 // We should also usually discard the pending entry if it corresponds to a
2212 // different navigation, since that one is now likely canceled. In rare
2213 // cases, we leave the pending entry for another navigation in place when we
2214 // know it is still ongoing, to avoid a flicker in the omnibox (see
2215 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432216 //
2217 // Note that we need to use the "internal" version since we don't want to
2218 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312219 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002220 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392221
Charlie Reis951f43372023-05-05 00:30:072222 if (!base::FeatureList::IsEnabled(
2223 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2224 // Update the last committed index to reflect the committed entry.
2225 // (This is legacy behavior, in case the kill-switch needs to be used.)
2226 last_committed_entry_index_ = GetIndexOfEntry(entry);
2227 }
[email protected]e9ba4472008-09-14 15:42:432228}
2229
[email protected]d202a7c2012-01-04 07:53:472230void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322231 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072232 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362233 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472234 bool replace_entry,
2235 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002236 NavigationRequest* request,
2237 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262238 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2239 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552240 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2241 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112242
[email protected]e9ba4472008-09-14 15:42:432243 // Manual subframe navigations just get the current entry cloned so the user
2244 // can go back or forward to it. The actual subframe information will be
2245 // stored in the page state for each of those entries. This happens out of
2246 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092247 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2248 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382249
Mikel Astizba9cf2fd2017-12-17 10:38:102250 // The DCHECK below documents the fact that we don't know of any situation
2251 // where |replace_entry| is true for subframe navigations. This simplifies
2252 // reasoning about the replacement struct for subframes (see
2253 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2254 DCHECK(!replace_entry);
2255
Patrick Monette50e8bd82019-06-13 22:40:452256 // This FrameNavigationEntry might not end up being used in the
2257 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072258 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452259 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:522260 absl::optional<GURL> initiator_base_url;
2261 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2262 initiator_base_url = request->common_params().initiator_base_url;
2263 }
Nate Chapin63db0d12022-01-20 22:03:302264 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2265 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2266 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572267 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302268 if (is_same_document) {
2269 FrameNavigationEntry* previous_frame_entry =
2270 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572271 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302272 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572273 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302274 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572275 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302276 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572277 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302278 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572279 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302280 policy_container_policies->referrer_policy);
2281 }
2282
Patrick Monette50e8bd82019-06-13 22:40:452283 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482284 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572285 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082286 rfh->GetSiteInstance(), nullptr, params.url,
2287 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212288 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2289 request->GetRedirectChain(), params.page_state, params.method,
2290 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572291 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032292
creisce0ef3572017-01-26 17:53:082293 std::unique_ptr<NavigationEntryImpl> new_entry =
2294 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452295 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032296 frame_tree_->root());
creise062d542015-08-25 02:01:552297
Alexander Timine3ec4192020-04-20 16:39:402298 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412299 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402300 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472301
creisce0ef3572017-01-26 17:53:082302 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452303 // to replace, which can happen due to a unique name change. See
2304 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2305 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382306
Dave Tapuska87696ae2021-11-18 18:48:312307 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152308 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432309}
2310
[email protected]d202a7c2012-01-04 07:53:472311bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322312 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072313 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392314 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252315 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002316 NavigationRequest* request,
2317 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292318 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2319 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2320
[email protected]e9ba4472008-09-14 15:42:432321 // We're guaranteed to have a previously committed entry, and we now need to
2322 // handle navigation inside of a subframe in it without creating a new entry.
2323 DCHECK(GetLastCommittedEntry());
2324
creis913c63ce2016-07-16 19:52:522325 // For newly created subframes, we don't need to send a commit notification.
2326 // This is only necessary for history navigations in subframes.
2327 bool send_commit_notification = false;
2328
Rakina Zata Amnif6950d552020-11-24 03:26:102329 // If |nav_entry_id| is non-zero and matches an existing entry, this
2330 // is a history navigation. Update the last committed index accordingly. If
2331 // we don't recognize the |nav_entry_id|, it might be a recently
2332 // pruned entry. We'll handle it below.
2333 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2334 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472335 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062336 // Make sure that a subframe commit isn't changing the main frame's
2337 // origin. Otherwise the renderer process may be confused, leading to a
2338 // URL spoof. We can't check the path since that may change
2339 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572340 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2341 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242342 // We should use checks similar to RenderFrameHostImpl's
2343 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2344 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572345 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2346 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2347 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2348 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522349 current_top_url.DeprecatedGetOriginAsURL() !=
2350 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442351 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512352 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062353 }
creis3cdc3b02015-05-29 23:00:472354
creis913c63ce2016-07-16 19:52:522355 // We only need to discard the pending entry in this history navigation
2356 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062357 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002358 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522359
2360 // History navigations should send a commit notification.
2361 send_commit_notification = true;
avi98405c22015-05-21 20:47:062362 }
[email protected]e9ba4472008-09-14 15:42:432363 }
[email protected]f233e4232013-02-23 00:55:142364
creisce0ef3572017-01-26 17:53:082365 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2366 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372367 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2368 // exists), or we may want to clobber it and create a new one. We update in
2369 // cases where the corresponding FrameNavigationEntry is conceptually similar
2370 // to the document described by the commit params: same-document
2371 // navigations, history traversal to an existing entry, and reloads (including
2372 // a "soft reload" where we navigate to the same url without flagging it as a
2373 // reload). But in the case of a different document that is not logically
2374 // related to the committed FrameNavigationEntry's document (cross-document,
2375 // not same url, not a reload, not a history traversal), we replace rather
2376 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252377 //
Nate Chapin9f169072021-06-09 19:32:372378 // In the case where we update, the FrameNavigationEntry will potentially be
2379 // shared across multiple NavigationEntries, and any updates will be reflected
2380 // in all of those NavigationEntries. In the replace case, any existing
2381 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252382 //
2383 // When navigating away from the initial empty document, we also update rather
2384 // than replace. Either update or replace will overwrite the initial empty
2385 // document state for |last_committed|, but if the FrameNavigationEntry for
2386 // the initial empty document is shared across multiple NavigationEntries (due
2387 // to a navigation in another frame), we want to make sure we overwrite the
2388 // initial empty document state everywhere this FrameNavigationEntry is used,
2389 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452390 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372391 FrameNavigationEntry* last_committed_frame_entry =
2392 last_committed->GetFrameEntry(rfh->frame_tree_node());
2393 NavigationEntryImpl::UpdatePolicy update_policy =
2394 NavigationEntryImpl::UpdatePolicy::kUpdate;
2395 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312396 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372397 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252398 last_committed_frame_entry->url() != params.url &&
2399 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372400 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2401 }
2402
Rakina Zata Amni3460d382021-10-29 00:43:372403 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002404 update_policy, false /* is_new_entry */,
2405 commit_details);
creis625a0c7d2015-03-24 23:17:122406
creis913c63ce2016-07-16 19:52:522407 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432408}
2409
[email protected]d202a7c2012-01-04 07:53:472410int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232411 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032412 for (size_t i = 0; i < entries_.size(); ++i) {
2413 if (entries_[i].get() == entry)
2414 return i;
2415 }
2416 return -1;
[email protected]765b35502008-08-21 00:51:202417}
2418
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572419void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242420 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572421 NavigationControllerImpl* source =
2422 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572423 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382424 DCHECK_EQ(1, GetEntryCount());
2425 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472426 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172427 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572428
Francois Dorayeaace782017-06-21 16:37:242429 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442430 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572431 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572432
Fergal Dalya1d569972021-03-16 03:24:532433 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302434 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532435 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2436 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302437 }
[email protected]4e6419c2010-01-15 04:50:342438
Lukasz Anforowicz0de0f452020-12-02 19:57:152439 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572440}
2441
Aran Gilman37d11632019-10-08 23:07:152442void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2443 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162444 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012445 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162446
[email protected]d202a7c2012-01-04 07:53:472447 NavigationControllerImpl* source =
2448 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252449
avi2b177592014-12-10 02:08:022450 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012451 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252452
[email protected]474f8512013-05-31 22:31:162453 // We now have one entry, possibly with a new pending entry. Ensure that
2454 // adding the entries from source won't put us over the limit.
2455 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572456 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572457 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252458
Carlos IL4dea8902020-05-26 15:14:292459 // Insert the entries from source. Ignore any pending entry, since it has not
2460 // committed in source.
[email protected]474f8512013-05-31 22:31:162461 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172462 DCHECK_NE(max_source_index, -1);
2463 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572464
2465 // Ignore the source's current entry if merging with replacement.
2466 // TODO(davidben): This should preserve entries forward of the current
2467 // too. http://crbug.com/317872
2468 if (replace_entry && max_source_index > 0)
2469 max_source_index--;
2470
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572471 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252472
2473 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552474 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142475
Hayato Ito2c8c08d02021-06-23 03:38:432476 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252477}
2478
[email protected]79368982013-11-13 01:11:012479bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162480 // If there is no last committed entry, we cannot prune. Even if there is a
2481 // pending entry, it may not commit, leaving this WebContents blank, despite
2482 // possibly giving it new entries via CopyStateFromAndPrune.
2483 if (last_committed_entry_index_ == -1)
2484 return false;
[email protected]9350602e2013-02-26 23:27:442485
[email protected]474f8512013-05-31 22:31:162486 // We cannot prune if there is a pending entry at an existing entry index.
2487 // It may not commit, so we have to keep the last committed entry, and thus
2488 // there is no sensible place to keep the pending entry. It is ok to have
2489 // a new pending entry, which can optionally commit as a new navigation.
2490 if (pending_entry_index_ != -1)
2491 return false;
2492
[email protected]474f8512013-05-31 22:31:162493 return true;
2494}
2495
[email protected]79368982013-11-13 01:11:012496void NavigationControllerImpl::PruneAllButLastCommitted() {
2497 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162498
avi2b177592014-12-10 02:08:022499 DCHECK_EQ(0, last_committed_entry_index_);
2500 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442501
Hayato Ito2c8c08d02021-06-23 03:38:432502 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442503}
2504
[email protected]79368982013-11-13 01:11:012505void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162506 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012507 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262508
Nate Chapin9eb16be72022-09-23 22:54:312509 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2510
[email protected]474f8512013-05-31 22:31:162511 // Erase all entries but the last committed entry. There may still be a
2512 // new pending entry after this.
2513 entries_.erase(entries_.begin(),
2514 entries_.begin() + last_committed_entry_index_);
2515 entries_.erase(entries_.begin() + 1, entries_.end());
2516 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262517}
2518
Christian Dullweber1af31e62018-02-22 11:49:482519void NavigationControllerImpl::DeleteNavigationEntries(
2520 const DeletionPredicate& deletionPredicate) {
2521 // It is up to callers to check the invariants before calling this.
2522 CHECK(CanPruneAllButLastCommitted());
2523 std::vector<int> delete_indices;
2524 for (size_t i = 0; i < entries_.size(); i++) {
2525 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572526 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482527 delete_indices.push_back(i);
2528 }
2529 }
2530 if (delete_indices.empty())
2531 return;
2532
2533 if (delete_indices.size() == GetEntryCount() - 1U) {
2534 PruneAllButLastCommitted();
2535 } else {
2536 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382537 for (const auto& index : base::Reversed(delete_indices)) {
2538 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482539 }
Hayato Ito2c8c08d02021-06-23 03:38:432540 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482541 }
2542 delegate()->NotifyNavigationEntriesDeleted();
2543}
2544
Shivani Sharma883f5f32019-02-12 18:20:012545bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2546 auto* entry = GetEntryAtIndex(index);
2547 return entry && entry->should_skip_on_back_forward_ui();
2548}
2549
Carlos Caballero35ce710c2019-09-19 10:59:452550BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2551 return back_forward_cache_;
2552}
2553
William Liu055a3542023-04-02 17:21:192554NavigationEntryScreenshotCache*
2555NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
2556 CHECK_EQ(frame_tree_->type(), FrameTree::Type::kPrimary);
2557 if (!nav_entry_screenshot_cache_ && AreBackForwardTransitionsEnabled()) {
2558 nav_entry_screenshot_cache_ =
2559 std::make_unique<NavigationEntryScreenshotCache>(
2560 BrowserContextImpl::From(browser_context_)
2561 ->GetNavigationEntryScreenshotManager()
2562 ->GetSafeRef(),
2563 this);
2564 }
2565 return nav_entry_screenshot_cache_.get();
2566}
2567
clamy987a3752018-05-03 17:36:262568void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2569 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2570 // progress, since this will cause a use-after-free. (We only allow this
2571 // when the tab is being destroyed for shutdown, since it won't return to
2572 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032573 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262574
2575 if (was_failure && pending_entry_) {
2576 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2577 } else {
2578 failed_pending_entry_id_ = 0;
2579 }
2580
2581 if (pending_entry_) {
2582 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332583 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262584 pending_entry_index_ = -1;
2585 pending_entry_ = nullptr;
2586 }
arthursonzogni66f711c2019-10-08 14:40:362587
2588 // Ensure any refs to the current pending entry are ignored if they get
2589 // deleted, by clearing the set of known refs. All future pending entries will
2590 // only be affected by new refs.
2591 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262592}
2593
2594void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2595 if (pending_entry_)
2596 pending_entry_->set_ssl_error(error);
2597}
2598
Xiaohan Wang7f8052e02022-01-14 18:44:282599#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422600// static
2601bool NavigationControllerImpl::ValidateDataURLAsString(
2602 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2603 if (!data_url_as_string)
2604 return false;
2605
2606 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2607 return false;
2608
2609 // The number of characters that is enough for validating a data: URI.
2610 // From the GURL's POV, the only important part here is scheme, it doesn't
2611 // check the actual content. Thus we can take only the prefix of the url, to
2612 // avoid unneeded copying of a potentially long string.
2613 const size_t kDataUriPrefixMaxLen = 64;
2614 GURL data_url(
2615 std::string(data_url_as_string->front_as<char>(),
2616 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2617 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2618 return false;
2619
2620 return true;
2621}
2622#endif
2623
Shivani Sharma194877032019-03-07 17:52:472624void NavigationControllerImpl::NotifyUserActivation() {
2625 // When a user activation occurs, ensure that all adjacent entries for the
2626 // same document clear their skippable bit, so that the history manipulation
2627 // intervention does not apply to them.
shivanigithub99368382021-06-16 18:33:372628 if (base::FeatureList::IsEnabled(
2629 features::kDebugHistoryInterventionNoUserActivation)) {
2630 return;
2631 }
2632
Shivani Sharmac4cc8922019-04-18 03:11:172633 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472634}
2635
clamy987a3752018-05-03 17:36:262636bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2637 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332638 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2639 blink::LocalFrameToken initiator_frame_token,
2640 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262641 NavigationEntryImpl* entry =
2642 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2643 if (!entry)
2644 return false;
2645
2646 FrameNavigationEntry* frame_entry =
2647 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2648 if (!frame_entry)
2649 return false;
2650
Camille Lamy5193caa2018-10-12 11:59:422651 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572652 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232653 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332654 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2655 initiator_process_id);
clamyea99ea12018-05-28 13:54:232656
2657 if (!request)
2658 return false;
2659
arthursonzognif046d4a2019-12-12 19:08:102660 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412661
Rakina Zata Amni1c83b082023-02-08 01:09:002662 SCOPED_CRASH_KEY_STRING256(
2663 "Bug1400009", "req_url",
2664 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2665 SCOPED_CRASH_KEY_NUMBER(
2666 "Bug1400009", "nav_entry_si",
2667 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2668 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2669 frame_entry->site_instance()
2670 ? ((int)frame_entry->site_instance()->GetId())
2671 : -1);
2672 bool has_sig =
2673 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2674 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2675 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2676 has_sig ? (!!frame_tree_->GetRenderViewHost(
2677 frame_entry->site_instance()->group()))
2678 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052679 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2680 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232681
2682 return true;
clamy987a3752018-05-03 17:36:262683}
2684
Tsuyoshi Horo52fd08e2020-07-07 07:03:452685bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2686 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2687 if (!entry)
2688 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432689
2690 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2691 // We should never navigate to an existing initial NavigationEntry that is
2692 // the initial NavigationEntry for the initial empty document that hasn't
2693 // been overridden by the synchronous about:blank commit, to preserve
2694 // legacy behavior where trying to reload when the main frame is on the
2695 // initial empty document won't result in a navigation. See also
2696 // https://crbug.com/1277414.
2697 return false;
2698 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452699 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2700 if (!frame_entry)
2701 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142702 ReloadType reload_type = ReloadType::NORMAL;
2703 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452704 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142705 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452706 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432707 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332708 absl::nullopt /* initiator_frame_token */,
2709 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452710 if (!request)
2711 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052712 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452713 return true;
2714}
2715
clamy987a3752018-05-03 17:36:262716void NavigationControllerImpl::NavigateFromFrameProxy(
2717 RenderFrameHostImpl* render_frame_host,
2718 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022719 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452720 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072721 const absl::optional<url::Origin>& initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212722 const absl::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262723 bool is_renderer_initiated,
2724 SiteInstance* source_site_instance,
2725 const Referrer& referrer,
2726 ui::PageTransition page_transition,
2727 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252728 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262729 const std::string& method,
2730 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092731 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142732 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212733 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502734 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392735 const absl::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292736 blink::mojom::NavigationInitiatorActivationAndAdStatus
2737 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222738 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492739 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462740 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452741 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582742 bool is_container_initiated,
2743 absl::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582744 if (is_renderer_initiated)
2745 DCHECK(initiator_origin.has_value());
2746
clamy987a3752018-05-03 17:36:262747 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582748
Rakina Zata Amni2322f4f82022-01-24 13:24:242749 // Don't allow an entry replacement if there is no entry to replace.
2750 // http://crbug.com/457149
2751 if (GetEntryCount() == 0)
2752 should_replace_current_entry = false;
2753
clamy987a3752018-05-03 17:36:262754 // Create a NavigationEntry for the transfer, without making it the pending
2755 // entry. Subframe transfers should have a clone of the last committed entry
2756 // with a FrameNavigationEntry for the target frame. Main frame transfers
2757 // should have a new NavigationEntry.
2758 // TODO(creis): Make this unnecessary by creating (and validating) the params
2759 // directly, passing them to the destination RenderFrameHost. See
2760 // https://crbug.com/536906.
2761 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262762 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262763 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452764 DCHECK(GetLastCommittedEntry());
2765 entry = GetLastCommittedEntry()->Clone();
2766 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172767 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2768 // Renderer-initiated navigation that target a remote frame are currently
2769 // classified as browser-initiated when this one has already navigated.
2770 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372771 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2772 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2773 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2774 // same-document navigation), they will still be present in the
2775 // committed NavigationEntry that will be referenced to construct the new
2776 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262777 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082778 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582779 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072780 absl::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212781 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152782 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262783 } else {
2784 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172785 // If `node` is the outermost main frame, it rewrites a virtual url in order
2786 // to adjust the original input url if needed. For inner frames such as
2787 // fenced frames or subframes, they don't rewrite urls as the urls are not
2788 // input urls by users.
2789 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:322790 absl::optional<GURL> source_process_site_url = absl::nullopt;
2791 if (source_site_instance && source_site_instance->HasProcess()) {
2792 source_process_site_url =
2793 source_site_instance->GetProcess()->GetProcessLock().site_url();
2794 }
clamy987a3752018-05-03 17:36:262795 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212796 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322797 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212798 extra_headers, browser_context_, blob_url_loader_factory,
2799 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262800 entry->root_node()->frame_entry->set_source_site_instance(
2801 static_cast<SiteInstanceImpl*>(source_site_instance));
2802 entry->root_node()->frame_entry->set_method(method);
2803 }
clamy987a3752018-05-03 17:36:262804
Camille Lamy5193caa2018-10-12 11:59:422805 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452806 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262807 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422808 override_user_agent = true;
clamy987a3752018-05-03 17:36:262809 }
2810 // TODO(creis): Set user gesture and intent received timestamp on Android.
2811
2812 // We may not have successfully added the FrameNavigationEntry to |entry|
2813 // above (per https://crbug.com/608402), in which case we create it from
2814 // scratch. This works because we do not depend on |frame_entry| being inside
2815 // |entry| during NavigateToEntry. This will go away when we shortcut this
2816 // further in https://crbug.com/536906.
2817 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2818 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452819 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082820 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582821 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072822 absl::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212823 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152824 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572825 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262826 }
2827
Camille Lamy5193caa2018-10-12 11:59:422828 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022829 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452830 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292831 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212832 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422833 params.source_site_instance = source_site_instance;
2834 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2835 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032836 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422837 params.referrer = referrer;
2838 /* params.redirect_chain: skip */
2839 params.extra_headers = extra_headers;
2840 params.is_renderer_initiated = is_renderer_initiated;
2841 params.override_user_agent = UA_OVERRIDE_INHERIT;
2842 /* params.base_url_for_data_url: skip */
2843 /* params.virtual_url_for_data_url: skip */
2844 /* params.data_url_as_string: skip */
2845 params.post_data = post_body;
2846 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582847 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422848 /* params.frame_name: skip */
2849 // TODO(clamy): See if user gesture should be propagated to this function.
2850 params.has_user_gesture = false;
2851 params.should_clear_history_list = false;
2852 params.started_from_context_menu = false;
2853 /* params.navigation_ui_data: skip */
2854 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222855 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542856 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212857 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412858 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502859 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292860 params.initiator_activation_and_ad_status =
2861 initiator_activation_and_ad_status;
Camille Lamy5193caa2018-10-12 11:59:422862
2863 std::unique_ptr<NavigationRequest> request =
2864 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032865 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142866 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392867 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492868 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582869 is_unfenced_top_navigation, is_container_initiated,
2870 embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232871
2872 if (!request)
2873 return;
2874
Garrett Tanzerbb8db412022-09-27 21:59:462875 // Force the navigation to take place in a new browsing instance.
2876 // This is used by _unfencedTop in fenced frames to ensure that navigations
2877 // leaving the fenced context create a new browsing instance.
2878 if (force_new_browsing_instance) {
2879 request->coop_status().ForceBrowsingInstanceSwap();
2880 }
2881
Arthur Hemery948742762019-09-18 10:06:242882 // At this stage we are proceeding with this navigation. If this was renderer
2883 // initiated with user gesture, we need to make sure we clear up potential
2884 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2885 DiscardNonCommittedEntries();
2886
Lukasz Anforowicz9ee83c272020-12-01 20:14:052887 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262888}
2889
[email protected]d1198fd2012-08-13 22:50:192890void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252891 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212892 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192893 if (!session_storage_namespace)
2894 return;
2895
2896 // We can't overwrite an existing SessionStorage without violating spec.
2897 // Attempts to do so may give a tab access to another tab's session storage
2898 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152899 bool successful_insert =
2900 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252901 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052902 static_cast<SessionStorageNamespaceImpl*>(
2903 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302904 .second;
2905 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192906}
2907
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572908bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452909 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032910 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462911}
2912
Aran Gilman37d11632019-10-08 23:07:152913SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252914 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302915 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252916 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032917 DOMStorageContextWrapper* context_wrapper =
2918 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2919
2920 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252921 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032922 if (it != session_storage_namespace_map_.end()) {
2923 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152924 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2925 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472926
michaelnbacbcbd2016-02-09 00:32:032927 return it->second.get();
2928 }
2929
2930 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102931 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2932 SessionStorageNamespaceImpl::Create(context_wrapper);
2933 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2934 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252935 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102936 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302937
Daniel Murphy31bbb8b12018-02-07 21:44:102938 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302939}
2940
2941SessionStorageNamespace*
2942NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252943 return GetSessionStorageNamespace(
2944 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302945}
2946
2947const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572948NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302949 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552950}
[email protected]d202a7c2012-01-04 07:53:472951
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572952bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562953 return needs_reload_;
2954}
[email protected]a26023822011-12-29 00:23:552955
[email protected]46bb5e9c2013-10-03 22:16:472956void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412957 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2958}
2959
2960void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472961 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412962 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542963
2964 if (last_committed_entry_index_ != -1) {
2965 entries_[last_committed_entry_index_]->SetTransitionType(
2966 ui::PAGE_TRANSITION_RELOAD);
2967 }
[email protected]46bb5e9c2013-10-03 22:16:472968}
2969
[email protected]d202a7c2012-01-04 07:53:472970void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572971 DCHECK_LT(index, GetEntryCount());
2972 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312973 DiscardNonCommittedEntries();
2974
Nate Chapin9eb16be72022-09-23 22:54:312975 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:312976 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122977 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312978 last_committed_entry_index_--;
2979}
2980
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572981NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272982 // If there is no pending_entry_, there should be no pending_entry_index_.
2983 DCHECK(pending_entry_ || pending_entry_index_ == -1);
2984
2985 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:362986 // at that index. An exception is while a reload of a post commit error page
2987 // is ongoing; in that case pending entry will point to the entry replaced
2988 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:272989 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:362990 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
2991 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:272992
[email protected]022af742011-12-28 18:37:252993 return pending_entry_;
2994}
2995
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572996int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:272997 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:272998 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:552999 return pending_entry_index_;
3000}
3001
avi25764702015-06-23 15:43:373002void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573003 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363004 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313005 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003006 bool in_fenced_frame_tree,
3007 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313008 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3009 // set because:
3010 // 1) They don't influence the history of the outer page.
3011 // 2) They are always replace only navigation (there is always only one entry
3012 // in their history stack).
3013 // 3) Are not top level navigations and appear similar to iframes.
3014 // Navigations of the fenced frame might create a new NavigationEntry, which
3015 // will call this function. Non fenced frame navigations will never have
3016 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3017 // InsertOrReplaceEntry.
3018 DCHECK_EQ(in_fenced_frame_tree,
3019 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3020 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203021
avi5cad4912015-06-19 05:25:443022 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3023 // need to keep continuity with the pending entry, so copy the pending entry's
3024 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3025 // then the renderer navigated on its own, independent of the pending entry,
3026 // so don't copy anything.
3027 if (pending_entry_ && pending_entry_index_ == -1)
3028 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203029
Rakina Zata Amnia4e27222021-12-22 01:05:003030 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203031
creisee17e932015-07-17 17:56:223032 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453033 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103034 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573035 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363036 // If the new entry is a post-commit error page, we store the current last
3037 // committed entry to the side so that we can put it back when navigating
3038 // away from the error.
3039 if (was_post_commit_error) {
3040 DCHECK(!entry_replaced_by_post_commit_error_);
3041 entry_replaced_by_post_commit_error_ =
3042 std::move(entries_[last_committed_entry_index_]);
3043 }
dcheng36b6aec92015-12-26 06:16:363044 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223045 return;
3046 }
[email protected]765b35502008-08-21 00:51:203047
creis37979a62015-08-04 19:48:183048 // We shouldn't see replace == true when there's no committed entries.
3049 DCHECK(!replace);
3050
Michael Thiessen9b14d512019-09-23 21:19:473051 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203052
Shivani Sharmad8c8d652019-02-13 17:27:573053 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203054
dcheng36b6aec92015-12-26 06:16:363055 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203056 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293057}
3058
Shivani Sharmad8c8d652019-02-13 17:27:573059void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163060 if (entries_.size() < max_entry_count())
3061 return;
3062
3063 DCHECK_EQ(max_entry_count(), entries_.size());
3064 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573065 CHECK_EQ(pending_entry_index_, -1);
3066
3067 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423068 // Retrieve the oldest skippable entry.
3069 for (; index < GetEntryCount(); index++) {
3070 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3071 break;
Shivani Sharmad8c8d652019-02-13 17:27:573072 }
3073
3074 // If there is no skippable entry or if it is the last committed entry then
3075 // fall back to pruning the oldest entry. It is not safe to prune the last
3076 // committed entry.
3077 if (index == GetEntryCount() || index == last_committed_entry_index_)
3078 index = 0;
3079
3080 bool should_succeed = RemoveEntryAtIndex(index);
3081 DCHECK_EQ(true, should_succeed);
3082
3083 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253084}
3085
clamy3cb9bea92018-07-10 12:42:023086void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163087 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203088 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:133089 absl::optional<blink::scheduler::TaskAttributionId>
3090 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203091 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503092 TRACE_EVENT0("navigation",
3093 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273094 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023095 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363096 if (pending_entry_index_ != -1) {
3097 // The pending entry may not be in entries_ if a post-commit error page is
3098 // showing.
3099 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3100 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3101 }
Gyuyoung Kim107c2a02021-04-13 01:49:303102 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573103 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013104 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033105 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573106 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133107 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3108 // the same as the top level frame being navigated.
3109 if (root->current_frame_host() != initiator_rfh) {
3110 soft_navigation_heuristics_task_id = absl::nullopt;
3111 }
Arthur Sonzogni620cec62018-12-13 13:08:573112
[email protected]83c2e232011-10-07 21:36:463113 // If we were navigating to a slow-to-commit page, and the user performs
3114 // a session history navigation to the last committed page, RenderViewHost
3115 // will force the throbber to start, but WebKit will essentially ignore the
3116 // navigation, and won't send a message to stop the throbber. To prevent this
3117 // from happening, we drop the navigation here and stop the slow-to-commit
3118 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023119 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083120 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273121 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033122 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123123
[email protected]83c2e232011-10-07 21:36:463124 DiscardNonCommittedEntries();
3125 return;
3126 }
3127
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333128 absl::optional<blink::LocalFrameToken> initiator_frame_token;
3129 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3130 if (initiator_rfh) {
3131 initiator_frame_token = initiator_rfh->GetFrameToken();
3132 initiator_process_id = initiator_rfh->GetProcess()->GetID();
3133 DCHECK(initiator_frame_token);
3134 }
3135
creisce0ef3572017-01-26 17:53:083136 // Compare FrameNavigationEntries to see which frames in the tree need to be
3137 // navigated.
clamy3cb9bea92018-07-10 12:42:023138 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3139 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333140 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3141 initiator_process_id, soft_navigation_heuristics_task_id,
3142 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303143
3144 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573145 // We were unable to match any frames to navigate. This can happen if a
3146 // history navigation targets a subframe that no longer exists
3147 // (https://crbug.com/705550). In this case, we need to update the current
3148 // history entry to the pending one but keep the main document loaded. We
3149 // also need to ensure that observers are informed about the updated
3150 // current history entry (e.g., for greying out back/forward buttons), and
3151 // that renderer processes update their history offsets. The easiest way
3152 // to do all that is to schedule a "redundant" same-document navigation in
3153 // the main frame.
3154 //
3155 // Note that we don't want to remove this history entry, as it might still
3156 // be valid later, since a frame that it's targeting may be recreated.
3157 //
3158 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3159 // need to repeat history navigations until finding the one that works.
3160 // Consider changing this behavior to keep looking for the first valid
3161 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023162 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423163 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573164 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573165 ReloadType::NONE /* reload_type */,
3166 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433167 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333168 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023169 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573170 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023171 DiscardPendingEntry(false);
3172 return;
3173 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573174 same_document_loads.push_back(std::move(navigation_request));
3175
3176 // Sanity check that we never take this branch for any kinds of reloads,
3177 // as those should've queued a different-document load in the main frame.
3178 DCHECK(!is_forced_reload);
3179 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303180 }
3181
Nate Chapinbf682fa32022-09-26 22:41:203182 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163183 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203184 if (initiator_rfh && initiator_rfh->IsSandboxed(
3185 network::mojom::WebSandboxFlags::kTopNavigation)) {
3186 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3187 initiator_rfh, same_document_loads) &&
3188 DoesSandboxNavigationStayWithinSubtree(
3189 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503190 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163191 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203192 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3193 initiator_rfh,
3194 navigates_inside_tree
3195 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3196 : blink::mojom::WebFeature::
3197 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523198
3199 // If the navigation occurred outside the tree discard it because
3200 // the sandboxed frame didn't have permission to navigate outside
3201 // its tree. If it is possible that the navigation is both inside and
3202 // outside the frame tree and we discard it entirely because we don't
3203 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143204 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203205 // If a |navigation_api_key| was provided, this navigation originated from
3206 // the navigation API. Notify the renderer that the navigation was
3207 // cancelled so the navigation API can fire an error event and reject the
3208 // relevant promise.
3209 if (navigation_api_key) {
3210 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3211 *navigation_api_key,
3212 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3213 }
Dave Tapuska855c1e12019-08-23 20:45:523214 DiscardPendingEntry(false);
3215 return;
3216 }
Dave Tapuska8bfd84c2019-03-26 20:47:163217 }
3218
Nate Chapin6c43c022023-02-13 23:32:423219 // If it is possible that this traverse may involve a same-document navigation
3220 // in the initiator and there is a Navigation API key involved, then we may
3221 // need to notify the initiator if it fails. (The early returns above either
3222 // do not involve these cases or already notify the initiator.)
3223 // The event only needs to fire for the initiator, and only if the initiator
3224 // itself is performing a same-document navigation (because the event will not
3225 // fire if it navigates cross-document).
3226 if (navigation_api_key) {
3227 for (auto& item : same_document_loads) {
3228 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3229 item->set_pending_navigation_api_key(*navigation_api_key);
3230 break;
3231 }
3232 }
3233 }
3234
Carlos Caballero539a421c2020-07-06 10:25:573235 // BackForwardCache:
3236 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563237 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573238 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3239 DCHECK_EQ(reload_type, ReloadType::NONE);
3240 auto navigation_request = CreateNavigationRequestFromEntry(
3241 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3242 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333243 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3244 initiator_process_id);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053245 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573246
3247 return;
3248 }
3249
3250 // History navigation might try to reuse a specific BrowsingInstance, already
3251 // used by a page in the cache. To avoid having two different main frames that
3252 // live in the same BrowsingInstance, evict the all pages with this
3253 // BrowsingInstance from the cache.
3254 //
3255 // For example, take the following scenario:
3256 //
3257 // A1 = Some page on a.com
3258 // A2 = Some other page on a.com
3259 // B3 = An uncacheable page on b.com
3260 //
3261 // Then the following navigations occur:
3262 // A1->A2->B3->A1
3263 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3264 // take its place) and A1 will be created in the same BrowsingInstance (and
3265 // SiteInstance), as A2.
3266 //
3267 // If we didn't do anything, both A1 and A2 would remain alive in the same
3268 // BrowsingInstance/SiteInstance, which is unsupported by
3269 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3270 // A2 from the cache.
3271 if (pending_entry_->site_instance()) {
3272 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3273 pending_entry_->site_instance());
3274 }
3275
Rakina Zata Amnid605d462022-06-01 10:17:033276 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3277 pending_entry_ && pending_entry_->IsRestored());
3278 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3279 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3280 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3281 pending_entry_index_);
3282 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3283 last_committed_entry_index_);
3284 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3285 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3286 pending_entry_ && pending_entry_->IsInitialEntry());
3287 SCOPED_CRASH_KEY_BOOL(
3288 "nav_reentrancy", "pending_entry_initial2",
3289 pending_entry_ &&
3290 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3291 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3292 IsInitialNavigation());
3293 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3294 IsInitialBlankNavigation());
3295 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3296 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3297 (int)pending_reload_);
3298
clamy3cb9bea92018-07-10 12:42:023299 // This call does not support re-entrancy. See http://crbug.com/347742.
3300 CHECK(!in_navigate_to_pending_entry_);
3301 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303302
Rakina Zata Amnid605d462022-06-01 10:17:033303 // If the navigation-reentrancy is caused by calling
3304 // NavigateToExistingPendingEntry twice, this will note the previous call's
3305 // pending entry's ID.
3306 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3307 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3308
arthursonzogni66f711c2019-10-08 14:40:363309 // It is not possible to delete the pending NavigationEntry while navigating
3310 // to it. Grab a reference to delay potential deletion until the end of this
3311 // function.
3312 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3313
Nate Chapin154b14b2023-02-17 18:28:163314 // If there is a main-frame same-document history navigation, we may defer
3315 // the subframe history navigations in order to give JS in the main frame the
3316 // opportunity to cancel the entire traverse via the navigate event. In that
3317 // case, we need to stash the main frame request's navigation token on the
3318 // subframes, so they can look up the main frame request and defer themselves
3319 // until it completes.
3320 if (!same_document_loads.empty() &&
3321 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3322 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3323 // The token will only be returned in cases where deferring the navigation
3324 // is necessary.
3325 if (auto main_frame_same_document_token =
3326 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3327 for (auto& item : same_document_loads) {
3328 if (item.get() != main_frame_request) {
3329 item->set_main_frame_same_document_history_token(
3330 main_frame_same_document_token);
3331 }
3332 }
3333 for (auto& item : different_document_loads) {
3334 item->set_main_frame_same_document_history_token(
3335 main_frame_same_document_token);
3336 }
3337 }
3338 }
3339
creis4e2ecb72015-06-20 00:46:303340 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023341 for (auto& item : same_document_loads) {
3342 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053343 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303344 }
clamy3cb9bea92018-07-10 12:42:023345 for (auto& item : different_document_loads) {
3346 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053347 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303348 }
clamy3cb9bea92018-07-10 12:42:023349
3350 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303351}
3352
Alex Moshchuk3a4e77a2020-05-29 21:32:573353NavigationControllerImpl::HistoryNavigationAction
3354NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303355 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573356 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423357 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583358 // Only active and prerendered documents are allowed to navigate in their
3359 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423360 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013361 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583362 // - If the document is in pending deletion, the browser already committed
3363 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3364 // - If the document is in back-forward cache, it's not allowed to navigate
3365 // as it should remain frozen. Ignore the request and evict the document
3366 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423367 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583368 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423369 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113370 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3371 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423372 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113373 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423374 }
arthursonzogni03f76152019-02-12 10:35:203375
Alex Moshchuk3a4e77a2020-05-29 21:32:573376 // Reloads should result in a different-document load. Note that reloads may
3377 // also happen via the |needs_reload_| mechanism where the reload_type is
3378 // NONE, so detect this by comparing whether we're going to the same
3379 // entry that we're currently on. Similarly to above, only main frames
3380 // should reach this. Note that subframes support reloads, but that's done
3381 // via a different path that doesn't involve FindFramesToNavigate (see
3382 // RenderFrameHost::Reload()).
3383 if (reload_type != ReloadType::NONE ||
3384 pending_entry_index_ == last_committed_entry_index_) {
3385 DCHECK(frame->IsMainFrame());
3386 return HistoryNavigationAction::kDifferentDocument;
3387 }
3388
Alex Moshchuk47d1a4bd2020-06-01 22:15:343389 // If there is no new FrameNavigationEntry for the frame, ignore the
3390 // load. For example, this may happen when going back to an entry before a
3391 // frame was created. Suppose we commit a same-document navigation that also
3392 // results in adding a new subframe somewhere in the tree. If we go back,
3393 // the new subframe will be missing a FrameNavigationEntry in the previous
3394 // NavigationEntry, but we shouldn't delete or change what's loaded in
3395 // it.
3396 //
Alex Moshchuke65c39272020-06-03 17:55:373397 // Note that in this case, there is no need to keep looking for navigations
3398 // in subframes, which would be missing FrameNavigationEntries as well.
3399 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343400 // It's important to check this before checking |old_item| below, since both
3401 // might be null, and in that case we still shouldn't change what's loaded in
3402 // this frame. Note that scheduling any loads assumes that |new_item| is
3403 // non-null. See https://crbug.com/1088354.
3404 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3405 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373406 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343407
Charlie Reisa474fb62022-03-17 02:31:363408 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3409 // which history item it is currently on, since this may be different than the
3410 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3411 // (e.g., if a history navigation is targeting multiple frames and only some
3412 // have committed so far).
creis4e2ecb72015-06-20 00:46:303413 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363414 frame->current_frame_host()->last_committed_frame_entry();
3415 if (!old_item) {
3416 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3417 // fall back to the last committed NavigationEntry's record for this frame.
3418 // This may happen in cases like the initial state of the RenderFrameHost.
3419 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3420 // accurate FrameNavigationEntry and eliminate this case.
3421 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3422 }
3423 // If neither approach finds a FrameNavigationEntry, schedule a
3424 // different-document load.
3425 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573426 if (!old_item)
3427 return HistoryNavigationAction::kDifferentDocument;
3428
Alex Moshchuk3a4e77a2020-05-29 21:32:573429 // If the new item is not in the same SiteInstance, schedule a
3430 // different-document load. Newly restored items may not have a SiteInstance
3431 // yet, in which case it will be assigned on first commit.
3432 if (new_item->site_instance() &&
3433 new_item->site_instance() != old_item->site_instance())
3434 return HistoryNavigationAction::kDifferentDocument;
3435
3436 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313437 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3438 // that we do this even if the history navigation would not be modifying this
3439 // frame were it live.
3440 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573441 return HistoryNavigationAction::kDifferentDocument;
3442
3443 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313444 // Starting a navigation after a crash early-promotes the speculative
3445 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3446 // committed yet, so we can not possibly perform a same-document history
3447 // navigation. The frame would need to be reloaded with a cross-document
3448 // navigation.
3449 if (!frame->current_frame_host()->has_committed_any_navigation())
3450 return HistoryNavigationAction::kDifferentDocument;
3451
creis54131692016-08-12 18:32:253452 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493453 // sequence number but different item sequence number.
3454 if (new_item->document_sequence_number() ==
3455 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573456 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493457 }
avib48cb312016-05-05 21:35:003458
Alex Moshchuk3a4e77a2020-05-29 21:32:573459 // Otherwise, if both item and document sequence numbers differ, this
3460 // should be a different document load.
3461 return HistoryNavigationAction::kDifferentDocument;
3462 }
3463
3464 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373465 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573466 DCHECK_EQ(new_item->document_sequence_number(),
3467 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373468 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573469}
3470
3471void NavigationControllerImpl::FindFramesToNavigate(
3472 FrameTreeNode* frame,
3473 ReloadType reload_type,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333474 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
3475 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133476 absl::optional<blink::scheduler::TaskAttributionId>
3477 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573478 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3479 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3480 DCHECK(pending_entry_);
3481 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3482
3483 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3484
3485 if (action == HistoryNavigationAction::kSameDocument) {
3486 std::unique_ptr<NavigationRequest> navigation_request =
3487 CreateNavigationRequestFromEntry(
3488 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133489 /*is_same_document_history_load=*/true,
3490 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333491 initiator_frame_token, initiator_process_id,
3492 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573493 if (navigation_request) {
3494 // Only add the request if was properly created. It's possible for the
3495 // creation to fail in certain cases, e.g. when the URL is invalid.
3496 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303497 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573498 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473499 std::unique_ptr<NavigationRequest> navigation_request =
3500 CreateNavigationRequestFromEntry(
3501 frame, pending_entry_, new_item, reload_type,
3502 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433503 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333504 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473505 if (navigation_request) {
3506 // Only add the request if was properly created. It's possible for the
3507 // creation to fail in certain cases, e.g. when the URL is invalid.
3508 different_document_loads->push_back(std::move(navigation_request));
3509 }
3510 // For a different document, the subframes will be destroyed, so there's
3511 // no need to consider them.
3512 return;
Alex Moshchuke65c39272020-06-03 17:55:373513 } else if (action == HistoryNavigationAction::kStopLooking) {
3514 return;
creis4e2ecb72015-06-20 00:46:303515 }
3516
Yoav Weiss8c573952022-11-17 17:35:133517 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3518 // we currently only support soft navigation heuristics for the top level
3519 // frame.
creis4e2ecb72015-06-20 00:46:303520 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333521 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3522 initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133523 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
Nate Chapin45f620582021-09-30 17:45:433524 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303525 }
3526}
3527
Harkiran Bolariaba823e42021-05-21 18:30:363528base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243529 const LoadURLParams& params) {
3530 // Find the appropriate FrameTreeNode.
3531 FrameTreeNode* node = nullptr;
3532 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3533 !params.frame_name.empty()) {
3534 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033535 ? frame_tree_->FindByID(params.frame_tree_node_id)
3536 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503537 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243538 }
3539
3540 // If no FrameTreeNode was specified, navigate the main frame.
3541 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033542 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243543
Camille Lamy5193caa2018-10-12 11:59:423544 // Compute overrides to the LoadURLParams for |override_user_agent|,
3545 // |should_replace_current_entry| and |has_user_gesture| that will be used
3546 // both in the creation of the NavigationEntry and the NavigationRequest.
3547 // Ideally, the LoadURLParams themselves would be updated, but since they are
3548 // passed as a const reference, this is not possible.
3549 // TODO(clamy): When we only create a NavigationRequest, move this to
3550 // CreateNavigationRequestFromLoadURLParams.
3551 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3552 GetLastCommittedEntry());
3553
Rakina Zata Amnie2d31312022-11-18 03:38:453554 // An entry replacement must happen if the current browsing context should
3555 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333556 bool should_replace_current_entry =
3557 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453558 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423559
clamy21718cc22018-06-13 13:34:243560 // Javascript URLs should not create NavigationEntries. All other navigations
3561 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243562 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373563 std::unique_ptr<NavigationEntryImpl> entry =
3564 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3565 should_replace_current_entry,
3566 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243567 DiscardPendingEntry(false);
3568 SetPendingEntry(std::move(entry));
3569 }
3570
Tim Judkins59548192023-05-17 17:51:203571 // Renderer-debug URLs are sent to the current renderer process immediately
3572 // for processing and don't need to create a NavigationRequest. Note: this
3573 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243574 // renderer-debug URLs.
3575 // Note: we intentionally leave the pending entry in place for renderer debug
3576 // URLs, unlike the cases below where we clear it if the navigation doesn't
3577 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303578 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483579 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3580 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153581 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203582 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483583 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363584 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483585 }
3586
clamy21718cc22018-06-13 13:34:243587 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363588 return nullptr;
clamy21718cc22018-06-13 13:34:243589 }
3590
Antonio Sartori78a749f2020-11-30 12:03:393591 DCHECK(pending_entry_);
3592
clamy21718cc22018-06-13 13:34:243593 // Convert navigations to the current URL to a reload.
3594 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3595 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3596 // DevTools sometimes issues navigations to main frames that they do not
3597 // expect to see treated as reload, and it only works because they pass a
3598 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3599 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543600 ReloadType reload_type = params.reload_type;
3601 if (reload_type == ReloadType::NONE &&
3602 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043603 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243604 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243605 params.load_type ==
3606 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543607 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243608 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473609 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393610
3611 // If this is a reload of an existing FrameNavigationEntry and we had a
3612 // policy container for it, then we should copy it into the pending entry,
3613 // so that it is copied to the navigation request in
3614 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453615 FrameNavigationEntry* previous_frame_entry =
3616 GetLastCommittedEntry()->GetFrameEntry(node);
3617 if (previous_frame_entry &&
3618 previous_frame_entry->policy_container_policies()) {
3619 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3620 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393621 }
3622 }
3623
3624 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173625 // document, then we should copy the document polices from RenderFrameHost's
3626 // PolicyContainerHost. The NavigationRequest will create a new
3627 // PolicyContainerHost with the document policies from the |pending_entry_|,
3628 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3629 // the navigation. This way, we ensure that we keep enforcing the right
3630 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453631 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393632 if (node->current_frame_host() &&
3633 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193634 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163635 node->current_frame_host()
3636 ->policy_container_host()
3637 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233638 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393639 }
clamy21718cc22018-06-13 13:34:243640 }
3641
3642 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263643 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243644
Tsuyoshi Horo167ca6432022-03-09 05:16:393645 // This will be used to set the Navigation Timing API navigationStart
3646 // parameter for browser navigations in new tabs (intents, tabs opened through
3647 // "Open link in new tab"). If the navigation must wait on the current
3648 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3649 // will be updated when the BeforeUnload ack is received.
3650 const auto navigation_start_time = base::TimeTicks::Now();
3651
Camille Lamy5193caa2018-10-12 11:59:423652 std::unique_ptr<NavigationRequest> request =
3653 CreateNavigationRequestFromLoadParams(
3654 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143655 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393656 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3657 navigation_start_time);
clamy21718cc22018-06-13 13:34:243658
3659 // If the navigation couldn't start, return immediately and discard the
3660 // pending NavigationEntry.
3661 if (!request) {
3662 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363663 return nullptr;
clamy21718cc22018-06-13 13:34:243664 }
3665
Camille Lamy5193caa2018-10-12 11:59:423666#if DCHECK_IS_ON()
3667 // Safety check that NavigationRequest and NavigationEntry match.
3668 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3669#endif
3670
clamy21718cc22018-06-13 13:34:243671 // This call does not support re-entrancy. See http://crbug.com/347742.
3672 CHECK(!in_navigate_to_pending_entry_);
3673 in_navigate_to_pending_entry_ = true;
3674
arthursonzogni66f711c2019-10-08 14:40:363675 // It is not possible to delete the pending NavigationEntry while navigating
3676 // to it. Grab a reference to delay potential deletion until the end of this
3677 // function.
3678 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3679
Harkiran Bolariaba823e42021-05-21 18:30:363680 base::WeakPtr<NavigationHandle> created_navigation_handle(
3681 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053682 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243683
3684 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363685 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243686}
3687
clamyea99ea12018-05-28 13:54:233688void NavigationControllerImpl::HandleRendererDebugURL(
3689 FrameTreeNode* frame_tree_node,
3690 const GURL& url) {
3691 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243692 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3693 // the renderer process is not live, unless it is the initial navigation
3694 // of the tab.
clamyea99ea12018-05-28 13:54:233695 if (!IsInitialNavigation()) {
3696 DiscardNonCommittedEntries();
3697 return;
3698 }
Fergal Dalyecd3b0202020-06-25 01:57:373699 // The current frame is always a main frame. If IsInitialNavigation() is
3700 // true then there have been no navigations and any frames of this tab must
3701 // be in the same renderer process. If that has crashed then the only frame
3702 // that can be revived is the main frame.
3703 frame_tree_node->render_manager()
3704 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233705 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223706
3707 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3708 // notification, so set is loading to true here to properly surface it when
3709 // the renderer process is done handling the URL.
3710 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3711 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223712 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223713 }
clamyea99ea12018-05-28 13:54:233714 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3715}
3716
clamy21718cc22018-06-13 13:34:243717std::unique_ptr<NavigationEntryImpl>
3718NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3719 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423720 const LoadURLParams& params,
3721 bool override_user_agent,
3722 bool should_replace_current_entry,
3723 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393724 // Browser initiated navigations might not have a blob_url_loader_factory set
3725 // in params even if the navigation is to a blob URL. If that happens, lookup
3726 // the correct url loader factory to use here.
3727 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483728 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473729 // Resolve the blob URL in the storage partition associated with the target
3730 // frame. This is the storage partition the URL will be loaded in, and only
3731 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393732 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473733 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393734 }
3735
clamy21718cc22018-06-13 13:34:243736 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443737 // extra_headers in params are \n separated; navigation entries want \r\n.
3738 std::string extra_headers_crlf;
3739 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243740
3741 // For subframes, create a pending entry with a corresponding frame entry.
3742 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453743 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243744 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083745 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243746 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073747 params.url, absl::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213748 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3749 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393750 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163751 // a conversion of a new navigation into a reload, we will set the right
3752 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193753 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243754 } else {
3755 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173756 // If `node` is the outermost main frame, it rewrites a virtual url in order
3757 // to adjust the original input url if needed. For inner frames such as
3758 // fenced frames or subframes, they don't rewrite urls as the urls are not
3759 // input urls by users.
3760 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323761 scoped_refptr<SiteInstance> source_site_instance =
3762 params.source_site_instance;
3763 absl::optional<GURL> source_process_site_url = absl::nullopt;
3764 if (source_site_instance && source_site_instance->HasProcess()) {
3765 source_process_site_url =
3766 source_site_instance->GetProcess()->GetProcessLock().site_url();
3767 }
clamy21718cc22018-06-13 13:34:243768 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063769 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323770 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213771 params.transition_type, params.is_renderer_initiated,
3772 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3773 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243774 entry->set_source_site_instance(
3775 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3776 entry->SetRedirectChain(params.redirect_chain);
3777 }
3778
3779 // Set the FTN ID (only used in non-site-per-process, for tests).
3780 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243781 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423782 entry->SetIsOverridingUserAgent(override_user_agent);
3783 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543784 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243785
clamy21718cc22018-06-13 13:34:243786 switch (params.load_type) {
3787 case LOAD_TYPE_DEFAULT:
3788 break;
3789 case LOAD_TYPE_HTTP_POST:
3790 entry->SetHasPostData(true);
3791 entry->SetPostData(params.post_data);
3792 break;
3793 case LOAD_TYPE_DATA:
3794 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3795 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283796#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243797 entry->SetDataURLAsString(params.data_url_as_string);
3798#endif
3799 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3800 break;
clamy21718cc22018-06-13 13:34:243801 }
3802
3803 // TODO(clamy): NavigationEntry is meant for information that will be kept
3804 // after the navigation ended and therefore is not appropriate for
3805 // started_from_context_menu. Move started_from_context_menu to
3806 // NavigationUIData.
3807 entry->set_started_from_context_menu(params.started_from_context_menu);
3808
3809 return entry;
3810}
3811
clamyea99ea12018-05-28 13:54:233812std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423813NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3814 FrameTreeNode* node,
3815 const LoadURLParams& params,
3816 bool override_user_agent,
3817 bool should_replace_current_entry,
3818 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143819 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423820 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573821 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393822 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223823 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493824 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453825 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583826 bool is_container_initiated,
3827 absl::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573828 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283829 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533830 // All renderer-initiated navigations must have an initiator_origin.
3831 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513832
Camille Lamy5193caa2018-10-12 11:59:423833 GURL url_to_load;
3834 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323835
Camille Lamy2baa8022018-10-19 16:43:173836 // For main frames, rewrite the URL if necessary and compute the virtual URL
3837 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263838 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423839 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173840 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423841 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423842
Camille Lamy2baa8022018-10-19 16:43:173843 // For DATA loads, override the virtual URL.
3844 if (params.load_type == LOAD_TYPE_DATA)
3845 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423846
Camille Lamy2baa8022018-10-19 16:43:173847 if (virtual_url.is_empty())
3848 virtual_url = url_to_load;
3849
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573850 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283851
Aran Gilman249eb122019-12-02 23:32:463852 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3853 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3854 // return different results, leading to a different URL in the
3855 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3856 // pending NavigationEntry, as we'll only make one call to
3857 // RewriteUrlForNavigation.
3858 VLOG_IF(1, (url_to_load != frame_entry->url()))
3859 << "NavigationRequest and FrameEntry have different URLs: "
3860 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283861
Camille Lamy2baa8022018-10-19 16:43:173862 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423863 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173864 // NavigationRequest.
3865 } else {
3866 url_to_load = params.url;
3867 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243868 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173869 }
Camille Lamy5193caa2018-10-12 11:59:423870
Ehsan Karamad44fc72112019-02-26 18:15:473871 if (node->render_manager()->is_attaching_inner_delegate()) {
3872 // Avoid starting any new navigations since this node is now preparing for
3873 // attaching an inner delegate.
3874 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203875 }
Camille Lamy5193caa2018-10-12 11:59:423876
Alex Moshchuk99242832023-05-22 17:21:443877 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:423878 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:443879 }
Camille Lamy5193caa2018-10-12 11:59:423880
danakjd83d706d2020-11-25 22:11:123881 // Look for a pending commit that is to another document in this
3882 // FrameTreeNode. If one exists, then the last committed URL will not be the
3883 // current URL by the time this navigation commits.
3884 bool has_pending_cross_document_commit =
3885 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213886 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123887
Minggang Wangb9f3fa92021-07-01 15:30:313888 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493889 /*old_url=*/node->current_url(),
3890 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3891 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133892 /*is_same_document_history_load=*/false,
3893 is_embedder_initiated_fenced_frame_navigation,
3894 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423895
3896 // Create the NavigationParams based on |params|.
3897
Hiroki Nakagawa4ed61282021-06-18 05:37:233898 bool is_view_source_mode = entry->IsViewSourceMode();
3899 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293900
Antonio Sartori6984c742021-08-26 08:03:413901 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:293902
Hiroki Nakagawa4ed61282021-06-18 05:37:233903 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293904 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253905 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293906
Minggang Wangb9f3fa92021-07-01 15:30:313907 blink::mojom::CommonNavigationParamsPtr common_params =
3908 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:213909 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513910 blink::mojom::Referrer::New(params.referrer.url,
3911 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213912 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513913 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393914 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513915 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143916 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413917 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273918 false /* has_text_fragment_token */,
3919 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3920 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513921 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:053922 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423923
Minggang Wangb9f3fa92021-07-01 15:30:313924 blink::mojom::CommitNavigationParamsPtr commit_params =
3925 blink::mojom::CommitNavigationParams::New(
Rakina Zata Amnic7367852022-11-07 17:10:403926 absl::nullopt,
Ari Chivukula43d2cf82023-01-24 03:16:073927 // The correct storage key and session storage key will be computed
3928 // before committing the navigation.
3929 blink::StorageKey(), blink::StorageKey(), override_user_agent,
3930 params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323931 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503932 std::vector<net::RedirectInfo>(), params.post_content_type,
3933 common_params->url, common_params->method,
3934 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313935 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133936 entry->GetSubframeUniqueNames(node),
3937 /*intended_as_new_entry=*/true,
3938 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143939 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3940 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:133941 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313942 params.should_clear_history_list,
3943 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223944 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:133945 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:513946 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283947#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:133948 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143949#endif
Yoav Weiss8c573952022-11-17 17:35:133950 /*is_browser_initiated=*/!params.is_renderer_initiated,
Yoav Weiss8c573952022-11-17 17:35:133951 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:073952 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133953 /*force_enabled_origin_trials=*/std::vector<std::string>(),
3954 /*origin_agent_cluster=*/false,
3955 /*origin_agent_cluster_left_as_default=*/true,
3956 /*enabled_client_hints=*/
3957 std::vector<network::mojom::WebClientHintsType>(),
3958 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
3959 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:013960 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:133961 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:583962 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:133963 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:133964 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:283965 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:133966 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:443967 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:423968 network::mojom::NavigationDeliveryType::kDefault,
Yoav Weiss8c573952022-11-17 17:35:133969 /*view_transition_state=*/absl::nullopt,
sbinglera07ae732022-12-02 20:49:053970 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
3971 /*modified_runtime_features=*/
Garrett Tanzer29de7112022-12-06 21:26:323972 base::flat_map<::blink::mojom::RuntimeFeatureState, bool>(),
Yuzu Saijo29f96ca92022-12-08 04:54:123973 /*fenced_frame_properties=*/absl::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:053974 /*not_restored_reasons=*/nullptr,
Arthur Hemeryd51484b2023-06-02 15:50:003975 /*load_with_storage_access=*/false,
Kouhei Uenoa0297b0b2023-06-15 05:39:483976 /*browsing_context_group_info=*/absl::nullopt,
3977 /*lcpp_hint=*/nullptr);
Xiaohan Wang7f8052e02022-01-14 18:44:283978#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423979 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143980 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423981 }
3982#endif
3983
Lucas Furukawa Gadania9c45682019-07-31 22:05:143984 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:073985 commit_params->navigation_timing->system_entropy_at_navigation_start =
3986 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
3987 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:423988
Camille Lamy5193caa2018-10-12 11:59:423989 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3990 std::string extra_headers_crlf;
3991 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:093992
Alex Moshchuk9321e6a2022-12-07 21:58:313993 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143994 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:083995 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:093996 params.initiator_frame_token, params.initiator_process_id,
3997 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:213998 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:293999 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454000 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584001 is_container_initiated, embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:094002 navigation_request->set_from_download_cross_origin_redirect(
4003 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554004 navigation_request->set_force_new_browsing_instance(
4005 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:094006 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424007}
4008
4009std::unique_ptr<NavigationRequest>
4010NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234011 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574012 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234013 FrameNavigationEntry* frame_entry,
4014 ReloadType reload_type,
4015 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434016 bool is_history_navigation_in_new_child_frame,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334017 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
4018 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:134019 absl::optional<blink::scheduler::TaskAttributionId>
4020 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344021 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234022 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434023 // We should never navigate to an existing initial NavigationEntry that is the
4024 // initial NavigationEntry for the initial empty document that hasn't been
4025 // overridden by the synchronous about:blank commit, to preserve previous
4026 // behavior where trying to reload when the main frame is on the initial empty
4027 // document won't result in a navigation.
4028 // See also https://crbug.com/1277414.
4029 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324030
clamyea99ea12018-05-28 13:54:234031 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:014032 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574033 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:234034 // We may have been redirected when navigating to the current URL.
4035 // Use the URL the user originally intended to visit as signaled by the
4036 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:014037 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574038 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:234039 dest_referrer = Referrer();
clamyea99ea12018-05-28 13:54:234040 }
4041
Ehsan Karamad44fc72112019-02-26 18:15:474042 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4043 // Avoid starting any new navigations since this node is now preparing for
4044 // attaching an inner delegate.
4045 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204046 }
4047
Alex Moshchuk99242832023-05-22 17:21:444048 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4049 dest_url)) {
clamyea99ea12018-05-28 13:54:234050 return nullptr;
4051 }
4052
clamyea99ea12018-05-28 13:54:234053 // This will be used to set the Navigation Timing API navigationStart
4054 // parameter for browser navigations in new tabs (intents, tabs opened through
4055 // "Open link in new tab"). If the navigation must wait on the current
4056 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4057 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074058
clamyea99ea12018-05-28 13:54:234059 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074060 const auto navigation_start_system_entropy =
4061 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4062 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234063
danakjd83d706d2020-11-25 22:11:124064 // Look for a pending commit that is to another document in this
4065 // FrameTreeNode. If one exists, then the last committed URL will not be the
4066 // current URL by the time this navigation commits.
4067 bool has_pending_cross_document_commit =
4068 frame_tree_node->render_manager()
4069 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494070 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214071 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124072
Minggang Wangb9f3fa92021-07-01 15:30:314073 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124074 /*old_url=*/frame_tree_node->current_url(),
4075 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:494076 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494077 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134078 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494079 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424080
4081 // A form submission may happen here if the navigation is a
4082 // back/forward/reload navigation that does a form resubmission.
4083 scoped_refptr<network::ResourceRequestBody> request_body;
4084 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:504085 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
4086 // entry. This way, it could be directly retrieved here. Right now, it is only
4087 // partially recovered when request.method == "POST" and request.body exists.
4088 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424089 if (frame_entry->method() == "POST") {
4090 request_body = frame_entry->GetPostData(&post_content_type);
4091 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304092 post_content_type = std::string(
4093 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504094 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424095 }
4096
4097 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314098 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514099 entry->ConstructCommonNavigationParams(
4100 *frame_entry, request_body, dest_url,
4101 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384102 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534103 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514104 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554105 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424106
4107 // TODO(clamy): |intended_as_new_entry| below should always be false once
4108 // Reload no longer leads to this being called for a pending NavigationEntry
4109 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314110 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144111 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404112 *frame_entry, common_params->url, common_params->method,
4113 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144114 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534115 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484116 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134117 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074118 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144119 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074120 commit_params->navigation_timing->system_entropy_at_navigation_start =
4121 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4122 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Camille Lamy5193caa2018-10-12 11:59:424123
W. James MacLeanb7d6092682022-10-05 15:23:264124 if (common_params->url.IsAboutSrcdoc()) {
4125 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4126 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594127 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264128 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334129 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314130 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144131 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434132 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334133 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4134 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
4135 absl::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294136 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4137 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474138 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234139}
4140
[email protected]d202a7c2012-01-04 07:53:474141void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214142 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274143 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404144
Takashi Toyoshimaea534ef22021-07-21 03:27:594145 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404146 // location bar will have up-to-date information about the security style
4147 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134148 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404149
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374150 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574151 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:464152
[email protected]b0f724c2013-09-05 04:21:134153 // TODO(avi): Remove. http://crbug.com/170921
4154 NotificationDetails notification_details =
4155 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154156 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4157 Source<NavigationController>(this),
4158 notification_details);
initial.commit09911bf2008-07-26 23:55:294159}
4160
initial.commit09911bf2008-07-26 23:55:294161// static
[email protected]d202a7c2012-01-04 07:53:474162size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234163 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154164 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214165 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234166}
4167
[email protected]d202a7c2012-01-04 07:53:474168void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224169 if (is_active && needs_reload_)
4170 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294171}
4172
[email protected]d202a7c2012-01-04 07:53:474173void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034174 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4175 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294176 if (!needs_reload_)
4177 return;
4178
Bo Liucdfa4b12018-11-06 00:21:444179 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4180 needs_reload_type_);
4181
initial.commit09911bf2008-07-26 23:55:294182 // Calling Reload() results in ignoring state, and not loading.
4183 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4184 // cached state.
avicc872d7242015-08-19 21:26:344185 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134186 NavigateToExistingPendingEntry(
4187 ReloadType::NONE,
4188 /*initiator_rfh=*/nullptr,
4189 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4190 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454191 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434192 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274193 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344194 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134195 NavigateToExistingPendingEntry(
4196 ReloadType::NONE,
4197 /*initiator_rfh=*/nullptr,
4198 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4199 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344200 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434201 // We should never navigate to an existing initial NavigationEntry that is
4202 // the initial NavigationEntry for the initial empty document that hasn't
4203 // been overridden by the synchronous about:blank commit, to preserve
4204 // legacy behavior where trying to reload when the main frame is on the
4205 // initial empty document won't result in a navigation. See also
4206 // https://crbug.com/1277414. If there is something to reload, the
4207 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4208 // it here.
avicc872d7242015-08-19 21:26:344209 needs_reload_ = false;
4210 }
initial.commit09911bf2008-07-26 23:55:294211}
4212
Kevin McNeeccca6172021-10-19 17:11:144213base::WeakPtr<NavigationHandle>
4214NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364215 RenderFrameHost* render_frame_host,
4216 const GURL& url,
4217 const std::string& error_page_html,
4218 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134219 RenderFrameHostImpl* rfhi =
4220 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584221
4222 // Only active documents can load post-commit error pages:
4223 // - If the document is in pending deletion, the browser already committed to
4224 // destroying this RenderFrameHost so ignore loading the error page.
4225 // - If the document is in back-forward cache, it's not allowed to navigate as
4226 // it should remain frozen. Ignore the request and evict the document from
4227 // back-forward cache.
4228 // - If the document is prerendering, it can navigate but when loading error
4229 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114230 if (rfhi->IsInactiveAndDisallowActivation(
4231 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144232 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114233 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584234
Rakina Zata Amni919b7922020-12-11 09:03:134235 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414236
Minggang Wangb9f3fa92021-07-01 15:30:314237 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434238 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594239 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4240 // the frame actually committed (e.g. iframe with "src" set to a
4241 // slow-responding URL). We should rewrite the URL to about:blank in this
4242 // case, as the renderer will only think a page is an error page if it has a
4243 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134244 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314245 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434246 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334247 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414248
Mike Jacksone2aa7af2023-05-17 06:45:074249 commit_params->navigation_timing->system_entropy_at_navigation_start =
4250 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4251 node, blink::mojom::SystemEntropy::kNormal);
4252
arthursonzogni70ac7302020-05-28 08:49:054253 // Error pages have a fully permissive FramePolicy.
4254 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4255 // error pages.
4256 commit_params->frame_policy = blink::FramePolicy();
4257
John Delaney131ad362019-08-08 21:57:414258 std::unique_ptr<NavigationRequest> navigation_request =
4259 NavigationRequest::CreateBrowserInitiated(
4260 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094261 false /* was_opener_suppressed */, "" /* extra_headers */,
4262 nullptr /* frame_entry */, nullptr /* entry */,
4263 false /* is_form_submission */, nullptr /* navigation_ui_data */,
4264 absl::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364265 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414266 navigation_request->set_net_error(error);
Charlie Reis09952ee2022-12-08 16:35:074267 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414268 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144269
4270 // Calling BeginNavigation may destroy the NavigationRequest.
4271 base::WeakPtr<NavigationRequest> created_navigation_request(
4272 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414273 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144274 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414275}
4276
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574277void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214278 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094279 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154280 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144281 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294282}
4283
[email protected]d202a7c2012-01-04 07:53:474284void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364285 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474286 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4287 // represent a no-committed-entry state.
4288 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364289 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474290 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4291 // if `entries_` contains pre-existing entries from the NavigationController
4292 // before restore, which would not be removed and will be at the front of the
4293 // entries list, causing the index to be off by the amount of pre-existing
4294 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294295 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294296}
[email protected]765b35502008-08-21 00:51:204297
arthursonzogni69a6a1b2019-09-17 09:23:004298void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004299 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4300}
4301
4302void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4303 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474304 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104305 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4306 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294307 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474308 return;
Michael Thiessenc5676d22019-09-25 22:32:104309 }
avi45a72532015-04-07 21:01:454310 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314311
4312 if (!delegate_)
4313 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374314 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484315}
4316
avi7c6f35e2015-05-08 17:52:384317int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4318 int nav_entry_id) const {
4319 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4320 if (entries_[i]->GetUniqueID() == nav_entry_id)
4321 return i;
4322 }
4323 return -1;
4324}
4325
[email protected]d202a7c2012-01-04 07:53:474326void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574327 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254328 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574329 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574330 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4331 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254332 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374333 // Normally, cloning a NavigationEntryImpl results in sharing
4334 // FrameNavigationEntries between the original and the clone. However, when
4335 // cloning from a different NavigationControllerImpl, we want to fork the
4336 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374337 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574338 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254339 }
Rakina Zata Amnie2d31312022-11-18 03:38:454340 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274341 DCHECK(pending_entry_index_ == -1 ||
4342 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254343}
[email protected]c5b88d82012-10-06 17:03:334344
4345void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184346 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334347 get_timestamp_callback_ = get_timestamp_callback;
4348}
[email protected]8ff00d72012-10-23 19:12:214349
Shivani Sharmaffb32b82019-04-09 16:58:474350// History manipulation intervention:
4351void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474352 bool replace_entry,
4353 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404354 bool is_renderer_initiated,
4355 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454356 // Note that for a subframe, previous_document_was_activated is true if the
4357 // gesture happened in any subframe (propagated to main frame) or in the main
4358 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474359 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274360 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474361 return;
4362 }
4363 if (last_committed_entry_index_ == -1)
4364 return;
4365
Shivani Sharmac4cc8922019-04-18 03:11:174366 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474367
Alexander Timine3ec4192020-04-20 16:39:404368 // Log UKM with the URL we are navigating away from.
4369 ukm::builders::HistoryManipulationIntervention(
4370 previous_page_load_ukm_source_id)
4371 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474372}
4373
Shivani Sharmac4cc8922019-04-18 03:11:174374void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4375 int reference_index,
4376 bool skippable) {
4377 auto* reference_entry = GetEntryAtIndex(reference_index);
4378 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4379
4380 int64_t document_sequence_number =
4381 reference_entry->root_node()->frame_entry->document_sequence_number();
4382 for (int index = 0; index < GetEntryCount(); index++) {
4383 auto* entry = GetEntryAtIndex(index);
4384 if (entry->root_node()->frame_entry->document_sequence_number() ==
4385 document_sequence_number) {
4386 entry->set_should_skip_on_back_forward_ui(skippable);
4387 }
4388 }
4389}
4390
arthursonzogni66f711c2019-10-08 14:40:364391std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4392NavigationControllerImpl::ReferencePendingEntry() {
4393 DCHECK(pending_entry_);
4394 auto pending_entry_ref =
4395 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4396 pending_entry_refs_.insert(pending_entry_ref.get());
4397 return pending_entry_ref;
4398}
4399
4400void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4401 // Ignore refs that don't correspond to the current pending entry.
4402 auto it = pending_entry_refs_.find(ref);
4403 if (it == pending_entry_refs_.end())
4404 return;
4405 pending_entry_refs_.erase(it);
4406
4407 if (!pending_entry_refs_.empty())
4408 return;
4409
4410 // The pending entry may be deleted before the last PendingEntryRef.
4411 if (!pending_entry_)
4412 return;
4413
4414 // We usually clear the pending entry when the matching NavigationRequest
4415 // fails, so that an arbitrary URL isn't left visible above a committed page.
4416 //
4417 // However, we do preserve the pending entry in some cases, such as on the
4418 // initial navigation of an unmodified blank tab. We also allow the delegate
4419 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4420 // user edit the URL and try again. This may be useful in cases that the
4421 // committed page cannot be attacker-controlled. In these cases, we still
4422 // allow the view to clear the pending entry and typed URL if the user
4423 // requests (e.g., hitting Escape with focus in the address bar).
4424 //
4425 // Do not leave the pending entry visible if it has an invalid URL, since this
4426 // might be formatted in an unexpected or unsafe way.
4427 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364428 bool should_preserve_entry =
4429 (pending_entry_ == GetVisibleEntry()) &&
4430 pending_entry_->GetURL().is_valid() &&
4431 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4432 if (should_preserve_entry)
4433 return;
4434
4435 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374436 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364437}
4438
Titouan Rigoudy6ec70402021-02-02 15:42:194439std::unique_ptr<PolicyContainerPolicies>
4440NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394441 RenderFrameHostImpl* rfh,
4442 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174443 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394444 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454445 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394446 FrameNavigationEntry* previous_frame_entry =
4447 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4448
4449 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4450 // ensure we always have a FrameNavigationEntry here.
4451 if (!previous_frame_entry)
4452 return nullptr;
4453
Titouan Rigoudy6ec70402021-02-02 15:42:194454 const PolicyContainerPolicies* previous_policies =
4455 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394456
Titouan Rigoudy6ec70402021-02-02 15:42:194457 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394458 return nullptr;
4459
4460 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234461 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394462 }
4463
Titouan Rigoudy72f892d2022-05-02 18:21:234464 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394465}
4466
Hayato Ito2c8c08d02021-06-23 03:38:434467void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504468 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434469 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4470 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4471 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504472
4473 auto callback = base::BindRepeating(
4474 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4475 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4476 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4477 }
4478 },
Hayato Ito2c8c08d02021-06-23 03:38:434479 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034480 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504481}
4482
4483void NavigationControllerImpl::DidAccessInitialMainDocument() {
4484 // We may have left a failed browser-initiated navigation in the address bar
4485 // to let the user edit it and try again. Clear it now that content might
4486 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034487 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504488 DiscardPendingEntry(false);
4489
4490 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374491 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504492}
4493
4494void NavigationControllerImpl::UpdateStateForFrame(
4495 RenderFrameHostImpl* rfhi,
4496 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564497 OPTIONAL_TRACE_EVENT1("content",
4498 "NavigationControllerImpl::UpdateStateForFrame",
4499 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504500 // The state update affects the last NavigationEntry associated with the given
4501 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4502 // in the case of an UpdateState from a frame being swapped out). We track
4503 // which entry this is in the RenderFrameHost's nav_entry_id.
4504 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4505 if (!entry)
4506 return;
4507
4508 FrameNavigationEntry* frame_entry =
4509 entry->GetFrameEntry(rfhi->frame_tree_node());
4510 if (!frame_entry)
4511 return;
4512
4513 // The SiteInstance might not match if we do a cross-process navigation with
4514 // replacement (e.g., auto-subframe), in which case the swap out of the old
4515 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4516 // has already been replaced and destroyed.
4517 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4518 return;
4519
4520 if (page_state == frame_entry->page_state())
4521 return; // Nothing to update.
4522
4523 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4524
4525 // The document_sequence_number and item_sequence_number recorded in the
4526 // FrameNavigationEntry should not differ from the one coming with the update,
4527 // since it must come from the same document. Do not update it if a difference
4528 // is detected, as this indicates that |frame_entry| is not the correct one.
4529 blink::ExplodedPageState exploded_state;
4530 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4531 return;
4532
4533 if (exploded_state.top.document_sequence_number !=
4534 frame_entry->document_sequence_number() ||
4535 exploded_state.top.item_sequence_number !=
4536 frame_entry->item_sequence_number()) {
4537 return;
4538 }
4539
4540 frame_entry->SetPageState(page_state);
4541 NotifyEntryChanged(entry);
4542}
4543
Domenic Denicolacd30f5f82022-03-16 21:48:014544std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4545NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574546 Direction direction,
4547 int entry_index,
4548 const url::Origin& pending_origin,
4549 FrameTreeNode* node,
4550 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304551 int64_t pending_item_sequence_number,
4552 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014553 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454554 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174555 // Don't process the initial entry.
4556 DCHECK_EQ(GetEntryCount(), 1);
4557 return entries;
4558 }
Nate Chapind1fe3612021-04-16 20:45:574559 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304560 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574561 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4562 i += offset) {
4563 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414564 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574565 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014566 // An entry should only appear in the navigation API entries if it is for
4567 // the same origin as the document being committed. Check the committed
4568 // origin, or if that is not available (during restore), check against the
4569 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414570 url::Origin frame_entry_origin =
4571 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4572 frame_entry->url(),
4573 frame_entry->initiator_origin().value_or(url::Origin())));
4574 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574575 break;
4576 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4577 continue;
4578 blink::ExplodedPageState exploded_page_state;
4579 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4580 &exploded_page_state)) {
4581 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304582
4583 // If the document represented by this FNE hid its full url from appearing
4584 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014585 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304586 // document).
4587 std::u16string url;
4588 if (pending_document_sequence_number ==
4589 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574590 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304591 url = frame_state.url_string.value_or(std::u16string());
4592 }
4593
Domenic Denicolacd30f5f82022-03-16 21:48:014594 blink::mojom::NavigationApiHistoryEntryPtr entry =
4595 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574596 frame_state.navigation_api_key.value_or(std::u16string()),
4597 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094598 frame_state.item_sequence_number,
4599 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304600 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174601
Nate Chapin63db0d12022-01-20 22:03:304602 DCHECK(entry->url.empty() ||
4603 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574604 entries.push_back(std::move(entry));
4605 previous_item_sequence_number = frame_entry->item_sequence_number();
4606 }
4607 }
4608 // If |entries| was constructed by iterating backwards from
4609 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4610 // earliest-at-the-front. Reverse it.
4611 if (direction == Direction::kBack)
4612 std::reverse(entries.begin(), entries.end());
4613 return entries;
4614}
4615
Domenic Denicolacd30f5f82022-03-16 21:48:014616blink::mojom::NavigationApiHistoryEntryArraysPtr
4617NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554618 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574619 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404620 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444621 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404622 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574623
Nate Chapind1fe3612021-04-16 20:45:574624 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554625 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574626
Nate Chapine82339d02022-05-03 23:48:254627 // NOTE: |entry_index| is the index where this entry will commit if no
4628 // modifications are made between now and DidCommitNavigation. This is used to
4629 // walk |entries_| and determine which entries should be exposed by the
4630 // navigation API. It is important to calculate this correctly, because blink
4631 // will cancel a same-document history commit if it's not present in the
4632 // entries blink knows about.
4633 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574634 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304635 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254636 bool will_create_new_entry = false;
4637 if (GetPendingEntryIndex() != -1) {
4638 entry_index = GetPendingEntryIndex();
4639 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4640 pending_item_sequence_number = frame_entry->item_sequence_number();
4641 pending_document_sequence_number =
4642 frame_entry->document_sequence_number();
4643 }
4644 } else if (request &&
4645 !NavigationTypeUtils::IsReload(
4646 request->common_params().navigation_type) &&
4647 !NavigationTypeUtils::IsHistory(
4648 request->common_params().navigation_type) &&
4649 !request->common_params().should_replace_current_entry &&
4650 !request->common_params()
4651 .is_history_navigation_in_new_child_frame) {
4652 will_create_new_entry = true;
4653 entry_index = GetLastCommittedEntryIndex() + 1;
4654 // Don't set pending_item_sequence_number or
4655 // pending_document_sequence_number in this case - a new unique isn/dsn will
4656 // be calculated in the renderer later.
4657 } else if (GetLastCommittedEntryIndex() != -1) {
4658 entry_index = GetLastCommittedEntryIndex();
4659 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574660 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304661 pending_document_sequence_number =
4662 frame_entry->document_sequence_number();
4663 }
Nate Chapind1fe3612021-04-16 20:45:574664 }
4665
Domenic Denicolacd30f5f82022-03-16 21:48:014666 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254667 if (entry_index == -1) {
4668 // TODO(rakina): Exit early when there is no last committed entry.
4669 // Remove when InitialNavigationEntry ships.
4670 return entry_arrays;
4671 }
4672
Domenic Denicolacd30f5f82022-03-16 21:48:014673 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574674 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374675 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574676
4677 // Don't populate forward entries if they will be truncated by a new entry.
4678 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014679 entry_arrays->forward_entries =
4680 PopulateSingleNavigationApiHistoryEntryVector(
4681 Direction::kForward, entry_index, pending_origin, node,
4682 site_instance.get(), pending_item_sequence_number,
4683 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574684 }
Nate Chapin4e657a472022-02-06 03:38:374685 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574686}
4687
Nate Chapinfbfe5af2021-06-10 17:22:084688NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574689NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084690 FrameNavigationEntry* current_entry,
4691 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574692 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084693 if (!target_entry || !target_entry->committed_origin())
4694 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084695 if (!current_entry->committed_origin()->IsSameOriginWith(
4696 *target_entry->committed_origin())) {
4697 return HistoryNavigationAction::kStopLooking;
4698 }
4699
4700 // NOTE: We don't actually care between kSameDocument and
4701 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574702 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084703 return HistoryNavigationAction::kDifferentDocument;
4704 return HistoryNavigationAction::kKeepLooking;
4705}
4706
Domenic Denicolacc094fb2022-03-16 23:40:574707void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204708 RenderFrameHostImpl* initiator_rfh,
Yoav Weissa7449c3b2022-11-22 15:15:144709 absl::optional<blink::scheduler::TaskAttributionId>
4710 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574711 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204712 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084713 FrameNavigationEntry* current_entry =
4714 GetLastCommittedEntry()->GetFrameEntry(node);
4715 if (!current_entry)
4716 return;
4717
Yoav Weiss8c573952022-11-17 17:35:134718 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4719 // when `navigation.traverseTo()` is called.
4720
Nate Chapinfbfe5af2021-06-10 17:22:084721 // We want to find the nearest matching entry that is contiguously
4722 // same-instance and same-origin. Check back first, then forward.
4723 // TODO(japhet): Link spec here once it exists.
4724 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574725 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084726 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4727 if (result == HistoryNavigationAction::kStopLooking)
4728 break;
4729 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144730 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084731 return;
4732 }
4733 }
4734 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574735 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084736 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4737 if (result == HistoryNavigationAction::kStopLooking)
4738 break;
4739 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144740 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084741 return;
4742 }
4743 }
Nate Chapinbf682fa32022-09-26 22:41:204744
4745 // If we fall through to here, a matching NavigationEntry couldn't be found.
4746 // Notify the renderer that the navigation was cancelled.
4747 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4748 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084749}
4750
Domenic Denicolacc094fb2022-03-16 23:40:574751bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304752 network::mojom::ReferrerPolicy referrer_policy) {
4753 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4754 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4755}
4756
shivanigithubf405bf0d2021-11-05 17:58:334757bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4758 const FrameTreeNode* frame_tree_node) const {
4759 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4760 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544761 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Ali Hijazid87307d2022-11-07 20:15:034762 return frame_tree_->is_prerendering() ||
shivanigithubf405bf0d2021-11-05 17:58:334763 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544764}
4765
Julie Jeongeun Kim0e242242022-11-30 10:45:094766void NavigationControllerImpl::DidChangeReferrerPolicy(
4767 FrameTreeNode* node,
4768 network::mojom::ReferrerPolicy referrer_policy) {
4769 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4770 if (!entry)
4771 return;
4772
4773 // The FrameNavigationEntry may want to change whether to protect its url
4774 // in the navigation API when the referrer policy changes.
4775 entry->set_protect_url_in_navigation_api(
4776 ShouldProtectUrlInNavigationApi(referrer_policy));
4777}
4778
[email protected]8ff00d72012-10-23 19:12:214779} // namespace content