blob: ccff4174ed0d931f8734a248d6dbd74010ef46c3 [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.
1374 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1375 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
1376 // Must honor user agent overrides in the |navigation_request|, such as
1377 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1378 // result, besides comparing |pending_entry_|'s user agent against
1379 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1380 // agent against LastCommittedEntry's.
1381 if (navigation_request->is_overriding_user_agent() !=
1382 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1383 overriding_user_agent_changed = true;
1384 }
1385 }
1386#endif // BUILDFLAG(IS_ANDROID)
[email protected]ecd9d8702008-08-28 22:10:171387
Dave Tapuskaa2ab4f252021-07-08 21:31:281388 bool is_main_frame_navigation = !rfh->GetParent();
1389
Alexander Timind2f2e4f22019-04-02 20:04:531390 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1391 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281392 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141393 // BackForwardCacheMetrics to be associated with the new navigation's
1394 // NavigationEntry, by either creating a new object or reusing the previous
1395 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281396 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Arthur Sonzognif6785ec2022-12-05 10:11:501397 if (navigation_request->frame_tree_node()->frame_tree().type() ==
Dave Tapuskaa2ab4f252021-07-08 21:31:281398 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141399 back_forward_cache_metrics = BackForwardCacheMetrics::
1400 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281401 GetLastCommittedEntry(), is_main_frame_navigation,
1402 params.document_sequence_number);
1403 }
Yuzu Saijo29f96ca92022-12-08 04:54:121404
Alexander Timind2f2e4f22019-04-02 20:04:531405 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281406 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451407 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1408 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531409 }
1410 }
1411
Rakina Zata Amnifd8370b2022-11-14 13:32:251412 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1413 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091414 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251415 details->did_replace_entry =
1416 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091417
fdegans9caf66a2015-07-30 21:10:421418 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111419 // except for restored entries. This should be true even if the current commit
1420 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291421 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481422 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081423 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111424
1425 // Only make changes based on the pending entry if the NavigationRequest
1426 // matches it. Otherwise, the pending entry may be for a different request
1427 // (e.g., if a slow history navigation is pending while an auto-subframe
1428 // commit occurs).
1429 if (PendingEntryMatchesRequest(navigation_request)) {
1430 // It is no longer necessary to consider the pending entry as restored.
1431 if (pending_entry_->IsRestored()) {
1432 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1433 was_restored = true;
1434 }
[email protected]e9ba4472008-09-14 15:42:431435
Charlie Reisf8cde712022-10-20 16:25:091436 // If the SiteInstance has changed from the matching pending entry, this
1437 // must be treated as a new navigation with replacement. Set the replacement
1438 // bit here and ClassifyNavigation will identify this case and return
1439 // NEW_ENTRY.
1440 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1441 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1442 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251443 // TODO(nasko,creis,rakina): Move this to happen before committing the
1444 // navigation. This is a bit complicated because we don't currently
1445 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091446 details->did_replace_entry = true;
1447 }
Nasko Oskovaee2f862018-06-15 00:05:521448 }
[email protected]bcd904482012-02-01 01:54:221449
[email protected]e9ba4472008-09-14 15:42:431450 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101451 NavigationType navigation_type =
1452 ClassifyNavigation(rfh, params, navigation_request);
1453 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451454
Rakina Zata Amnie2d31312022-11-18 03:38:451455 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451456 // Ensure that this navigation does not add a navigation entry, since
1457 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1458 // beyond the last committed one. Therefore, `should_replace_current_entry`
1459 // should be set, which replaces the current entry, or this should be a
1460 // reload, which does not create a new entry.
1461 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1462 // navigation that is restored will not be creating a new entry anyways, so
1463 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1464 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1465 // pointed out in the issue.
Rakina Zata Amnifd8370b2022-11-14 13:32:251466 DCHECK(navigation_request->common_params().should_replace_current_entry ||
shivanigithub189833f2022-04-27 18:08:451467 navigation_request->GetReloadType() != ReloadType::NONE ||
Miyoung Shin3299cbf2022-11-22 01:41:101468 navigation_type == NAVIGATION_TYPE_AUTO_SUBFRAME);
shivanigithub189833f2022-04-27 18:08:451469 }
1470
Rakina Zata Amnie2d31312022-11-18 03:38:451471 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551472 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241473 // This is a subframe navigation on the initial empty document, which used
1474 // to not have a NavigationEntry to attach to. Now it can attach to the
1475 // initial NavigationEntry, and we must ensure that its NavigationEntry
1476 // will keep the "initial NavigationEntry" status and won't append a new
1477 // NavigationEntry (it should always do replacement instead).
1478 // See also https://crbug.com/1277414.
1479 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551480 // Subframe navigation on initial NavigationEntry must not append a new
1481 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1482 // means every subframe navigation that happens while we're on the initial
1483 // NavigationEntry will always reuse the existing NavigationEntry and
1484 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101485 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1486 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551487 // This is a navigation that modifies the initial NavigationEntry, either
1488 // for a replacement or a reload. The initial NavigationEntry should
1489 // retain its "initial NavigationEntry" status in this case.
1490 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241491 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251492 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1493 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241494 // This is a synchronous about:blank navigation on the main frame, which
1495 // used to not create a NavigationEntry when we have no NavigationEntry on
1496 // FrameTree creation. We now have the initial NavigationEntry and are on
1497 // the initial NavigationEntry. To preserve old behavior, we should still
1498 // keep the "initial" status for the new NavigationEntry that we will
1499 // create for this navigation, so that subframe navigations under the
1500 // synchronously committed about:blank document will never append new
1501 // NavigationEntry, and instead will just reuse the initial
1502 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1503 // See also https://crbug.com/1277414.
1504 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551505 }
1506 }
1507 DCHECK(!details->should_stay_as_initial_entry ||
1508 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201509
eugenebutee08663a2017-04-27 17:43:121510 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441511 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121512
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071513 details->is_prerender_activation =
1514 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241515 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1516 ->GetOutermostMainFrame()
1517 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071518
Peter Boströmd7592132019-01-30 04:50:311519 // Make sure we do not discard the pending entry for a different ongoing
1520 // navigation when a same document commit comes in unexpectedly from the
1521 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1522 // other navigation types. See https://crbug.com/900036.
1523 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061524 bool keep_pending_entry =
1525 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101526 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061527 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311528
Miyoung Shin3299cbf2022-11-22 01:41:101529 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061530 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491531 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051532 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001533 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431534 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061535 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491536 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1537 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001538 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431539 break;
[email protected]8ff00d72012-10-23 19:12:211540 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471541 RendererDidNavigateNewSubframe(
1542 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001543 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431544 break;
[email protected]8ff00d72012-10-23 19:12:211545 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391546 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251547 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001548 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081549 // We don't send a notification about auto-subframe PageState during
1550 // UpdateStateForFrame, since it looks like nothing has changed. Send
1551 // it here at commit time instead.
1552 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431553 return false;
creis59d5a47cb2016-08-24 23:57:191554 }
[email protected]e9ba4472008-09-14 15:42:431555 break;
Aran Gilman37d11632019-10-08 23:07:151556 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431557 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151558 break;
[email protected]765b35502008-08-21 00:51:201559 }
1560
[email protected]688aa65c62012-09-28 04:32:221561 // At this point, we know that the navigation has just completed, so
1562 // record the time.
1563 //
1564 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261565 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331566 base::Time timestamp =
1567 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1568 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131569 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221570
Peter Boströmd7592132019-01-30 04:50:311571 // If we aren't keeping the pending entry, there shouldn't be one at this
1572 // point. Clear it again in case any error cases above forgot to do so.
1573 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1574 // been cleared instead of protecting against it.
1575 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551576 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141577
[email protected]e9ba4472008-09-14 15:42:431578 // All committed entries should have nonempty content state so WebKit doesn't
1579 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471580 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321581 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221582 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441583 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141584
Alexander Timind2f2e4f22019-04-02 20:04:531585 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1586 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281587 if (back_forward_cache_metrics &&
1588 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531589 active_entry->set_back_forward_cache_metrics(
1590 std::move(back_forward_cache_metrics));
1591 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281592
1593 // `back_forward_cache_metrics()` may return null as we do not record
1594 // back-forward cache metrics for navigations in non-primary frame trees.
1595 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141596 // TODO(https://crbug.com/1338089): Remove this.
1597 // These are both only available from details at this point, so we capture
1598 // them here.
1599 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101600 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141601 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1602 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281603 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1604 navigation_request,
1605 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1606 }
naskoc7533512016-05-06 17:01:121607
Charles Reisc0507202017-09-21 00:40:021608 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1609 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1610 // A mismatch can occur if the renderer lies or due to a unique name collision
1611 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121612 FrameNavigationEntry* frame_entry =
1613 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021614 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1615 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031616 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081617 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1618 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031619 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201620
1621 // Remember the bindings the renderer process has at this point, so that
1622 // we do not grant this entry additional bindings if we come back to it.
1623 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301624 }
[email protected]132e281a2012-07-31 18:32:441625
[email protected]97d8f0d2013-10-29 16:49:211626 // Once it is committed, we no longer need to track several pieces of state on
1627 // the entry.
naskoc7533512016-05-06 17:01:121628 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131629
[email protected]49bd30e62011-03-22 20:12:591630 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221631 // TODO(creis): This check won't pass for subframes until we create entries
1632 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001633 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421634 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591635
[email protected]e9ba4472008-09-14 15:42:431636 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001637 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001638 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311639 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531640
arthursonzogni7ddc6542021-04-09 09:16:501641 active_entry->SetIsOverridingUserAgent(
1642 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031643
[email protected]93f230e02011-06-01 14:40:001644 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291645
aelias100c9192017-01-13 00:01:431646 if (overriding_user_agent_changed)
1647 delegate_->UpdateOverridingUserAgent();
1648
creis03b48002015-11-04 00:54:561649 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1650 // one knows the latest NavigationEntry it is showing (whether it has
1651 // committed anything in this navigation or not). This allows things like
1652 // state and title updates from RenderFrames to apply to the latest relevant
1653 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381654 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031655 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381656 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431657
1658 if (navigation_request->IsPrerenderedPageActivation()) {
1659 BroadcastHistoryOffsetAndLength();
1660 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1661 // is activated. As a result, a "prerenderingchange" event listener sees the
1662 // history.length which is not updated yet. We should guarantee that
1663 // history's length and offset should be updated before a
1664 // "prerenderingchange" event listener runs. One possible approach is to use
1665 // the same IPC which "prerenderingchange" uses, and propagate history's
1666 // length and offset together with that.
1667 }
1668
[email protected]e9ba4472008-09-14 15:42:431669 return true;
initial.commit09911bf2008-07-26 23:55:291670}
1671
[email protected]8ff00d72012-10-23 19:12:211672NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321673 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101674 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241675 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591676 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511677 "ClassifyNavigation");
1678
avi7c6f35e2015-05-08 17:52:381679 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241680 // A new entry. We may or may not have a corresponding pending entry, and
1681 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001682 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491683 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061684 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381685 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241686 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511687 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381688 return NAVIGATION_TYPE_NEW_SUBFRAME;
1689 }
1690
Charlie Reisc0f17d2d2021-01-12 18:52:491691 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381692 DCHECK(!params.history_list_was_cleared);
1693
avi39c1edd32015-06-04 20:06:001694 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381695 // All manual subframes would be did_create_new_entry and handled above, so
1696 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081697 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1698 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381699 }
1700
Rakina Zata Amnif6950d552020-11-24 03:26:101701 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1702 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381703 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1704 // create a new page.
1705
Hayato Ito2ae49442021-07-02 02:59:251706 // This main frame navigation is not a history navigation (since
1707 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1708 // reload or a replacement navigation, which will modify the existing entry.
1709 //
Nasko Oskov332593c2018-08-16 17:21:341710 // TODO(nasko): With error page isolation, reloading an existing session
1711 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491712 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341713 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511714 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491715 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061716 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381717 }
1718
Charlie Reisf8cde712022-10-20 16:25:091719 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521720 // If the SiteInstance of the |pending_entry_| does not match the
1721 // SiteInstance that got committed, treat this as a new navigation with
1722 // replacement. This can happen if back/forward/reload encounters a server
1723 // redirect to a different site or an isolated error page gets successfully
1724 // reloaded into a different SiteInstance.
1725 if (pending_entry_->site_instance() &&
1726 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491727 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061728 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521729 }
creis77c9aa32015-09-25 19:59:421730
Nasko Oskovaee2f862018-06-15 00:05:521731 if (pending_entry_index_ == -1) {
1732 // In this case, we have a pending entry for a load of a new URL but Blink
1733 // didn't do a new navigation (params.did_create_new_entry). First check
1734 // to make sure Blink didn't treat a new cross-process navigation as
1735 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161736 // we must treat it as NEW rather than the converted reload case below,
1737 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451738 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161739 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061740 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521741 }
1742
1743 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161744 // We will create a pending entry, but NavigateWithoutEntry will convert
1745 // it to a reload since it's the same page and not create a new entry for
1746 // it. (The user doesn't want to have a new back/forward entry when they
1747 // do this.) Therefore we want to just ignore the pending entry and go
1748 // back to where we were (the "existing entry").
1749 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061750 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521751 }
avi7c6f35e2015-05-08 17:52:381752 }
1753
Rakina Zata Amni153d5702021-09-13 22:48:001754 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381755 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491756 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1757 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161758 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061759 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381760 }
1761
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121762 if (navigation_request->DidEncounterError() &&
1763 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101764 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381765 // If the renderer was going to a new pending entry that got cleared because
1766 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491767 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381768 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511769 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491770 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061771 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381772 }
1773
Charlie Reisc0f17d2d2021-01-12 18:52:491774 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101775 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511776 trace_return.traced_value()->SetInteger("existing_entry_index",
1777 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381778 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441779 // The renderer has committed a navigation to an entry that no longer
1780 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491781 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061782 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381783 }
1784
avi7c6f35e2015-05-08 17:52:381785 // Since we weeded out "new" navigations above, we know this is an existing
1786 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491787 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061788 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381789}
1790
Rakina Zata Amni3460d382021-10-29 00:43:371791void NavigationControllerImpl::UpdateNavigationEntryDetails(
1792 NavigationEntryImpl* entry,
1793 RenderFrameHostImpl* rfh,
1794 const mojom::DidCommitProvisionalLoadParams& params,
1795 NavigationRequest* request,
1796 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001797 bool is_new_entry,
1798 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371799 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171800 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371801 entry->AddOrUpdateFrameEntry(
1802 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571803 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371804 rfh->GetSiteInstance(), nullptr, params.url,
1805 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171806 Referrer(*params.referrer),
1807 request ? request->common_params().initiator_origin : params.origin,
W. James MacLean23e90a12022-12-21 04:38:211808 request ? request->common_params().initiator_base_url : absl::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171809 request ? request->GetRedirectChain() : redirects, params.page_state,
1810 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371811 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171812 rfh, request && request->IsSameDocument(),
1813 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371814
1815 if (rfh->GetParent()) {
1816 // Only modify the NavigationEntry for main frame navigations.
1817 return;
1818 }
1819 if (entry->update_virtual_url_with_url())
1820 UpdateVirtualURLToURL(entry, params.url);
1821 // Don't use the page type from the pending entry. Some interstitial page
1822 // may have set the type to interstitial. Once we commit, however, the page
1823 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171824 entry->set_page_type((request && request->DidEncounterError())
1825 ? PAGE_TYPE_ERROR
1826 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431827 if (commit_details && commit_details->should_stay_as_initial_entry) {
1828 // Retain the "initial NavigationEntry" status.
1829 if (request->IsSameDocument()) {
1830 // If this is for a same-document navigation, the NavigationEntry must be
1831 // reused and should already be marked as the initial NavigationEntry.
1832 DCHECK(entry->IsInitialEntry());
1833 } else {
1834 // If this is for a cross-document navigation, it can be caused by a
1835 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1836 // "for synchronous about:blank" in the latter case, and also when it is
1837 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1838 // is not for a synchronous about:blank commit.
1839 NavigationEntryImpl::InitialNavigationEntryState new_state =
1840 NavigationEntryImpl::InitialNavigationEntryState::
1841 kInitialNotForSynchronousAboutBlank;
1842 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1843 request->is_synchronous_renderer_commit()) {
1844 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1845 kInitialForSynchronousAboutBlank;
1846 }
1847 entry->set_initial_navigation_entry_state(new_state);
1848 }
1849 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1850 // Remove the "initial NavigationEntry" status.
1851 entry->set_initial_navigation_entry_state(
1852 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001853 }
Rakina Zata Amniddf10502022-01-15 02:56:551854
Rakina Zata Amni3460d382021-10-29 00:43:371855 if (is_new_entry) {
1856 // Some properties of the NavigationEntry are only set when the entry is
1857 // new (we aren't reusing it).
1858 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171859 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1860 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371861 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1862 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1863 } else {
1864 // We are reusing the NavigationEntry. The site instance will normally be
1865 // the same except for a few cases:
1866 // 1) session restore, when no site instance will be assigned or
1867 // 2) redirect, when the site instance is reset.
1868 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1869 entry->site_instance() == rfh->GetSiteInstance());
1870 }
1871}
1872
Rakina Zata Amniafd3c6582021-11-30 06:19:171873void NavigationControllerImpl::CreateInitialEntry() {
1874 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031875 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171876 auto params = mojom::DidCommitProvisionalLoadParams::New();
1877 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1878 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1879 // before we have initial NavigationEntries.
1880 params->url = GURL::EmptyGURL();
1881 params->http_status_code = 0;
1882 params->url_is_unreachable = false;
1883 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171884 params->post_id = -1;
1885 params->embedding_token = base::UnguessableToken::Create();
1886 params->navigation_token = base::UnguessableToken::Create();
1887 params->did_create_new_entry = true;
1888 params->origin = rfh->GetLastCommittedOrigin();
1889 params->should_update_history = true;
1890 params->item_sequence_number = 0;
1891 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151892 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171893 params->transition = is_in_fenced_frame_tree
1894 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1895 : ui::PAGE_TRANSITION_LINK;
1896 params->referrer = blink::mojom::Referrer::New();
1897
Rakina Zata Amniafd3c6582021-11-30 06:19:171898 auto new_entry = std::make_unique<NavigationEntryImpl>(
1899 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381900 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211901 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1902 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1903 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171904 UpdateNavigationEntryDetails(
1905 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001906 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1907 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171908
1909 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1910 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001911 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171912}
1913
Charlie Reisc0f17d2d2021-01-12 18:52:491914void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321915 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071916 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361917 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441918 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471919 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001920 NavigationRequest* request,
1921 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571922 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071923 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451924 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:521925 absl::optional<GURL> initiator_base_url;
1926 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
1927 initiator_base_url = request->common_params().initiator_base_url;
1928 }
Lukasz Anforowicz435bcb582019-07-12 20:50:061929
creisf49dfc92016-07-26 17:05:181930 // First check if this is an in-page navigation. If so, clone the current
1931 // entry instead of looking at the pending entry, because the pending entry
1932 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451933 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301934 FrameNavigationEntry* previous_frame_entry =
1935 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451936 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481937 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571938 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:081939 rfh->GetSiteInstance(), nullptr, params.url,
1940 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:211941 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:091942 request->GetRedirectChain(), params.page_state, params.method,
1943 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:391944 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301945 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:571946 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:301947 // FrameNavigationEntry.
1948 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:571949 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:031950
creisf49dfc92016-07-26 17:05:181951 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:031952 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:521953 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1954 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571955 // TODO(jam): we had one report of this with a URL that was redirecting to
1956 // only tildes. Until we understand that better, don't copy the cert in
1957 // this case.
1958 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571959 }
creisf49dfc92016-07-26 17:05:181960
Patrick Monette50e8bd82019-06-13 22:40:451961 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1962 // that |frame_entry| should now have a reference count of exactly 2: one
1963 // due to the local variable |frame_entry|, and another due to |new_entry|
1964 // also retaining one. This should never fail, because it's the main frame.
1965 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181966 }
1967
Harkiran Bolaria59290d62021-03-17 01:53:011968 // If this is an activation navigation from a prerendered page, transfer the
1969 // new entry from an entry already created and stored in the
1970 // NavigationRequest. |new_entry| will not have been set prior to this as
1971 // |is_same_document| is mutually exclusive with
1972 // |IsPrerenderedPageActivation|.
1973 if (request->IsPrerenderedPageActivation()) {
1974 DCHECK(!is_same_document);
1975 DCHECK(!new_entry);
1976 new_entry = request->TakePrerenderNavigationEntry();
1977 DCHECK(new_entry);
1978 }
1979
Charlie Reisc0f17d2d2021-01-12 18:52:491980 // Only make a copy of the pending entry if it is appropriate for the new
1981 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451982 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041983 // 1. The SiteInstance hasn't been assigned to something else.
1984 // 2. The pending entry was intended as a new entry, rather than being a
1985 // history navigation that was interrupted by an unrelated,
1986 // renderer-initiated navigation.
1987 // TODO(csharrison): Investigate whether we can remove some of the coarser
1988 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451989 if (!new_entry && PendingEntryMatchesRequest(request) &&
1990 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:341991 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:431992 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:351993 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:431994
Camille Lamy62b826012019-02-26 09:15:471995 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451996 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:181997 }
1998
Charlie Reisc0f17d2d2021-01-12 18:52:491999 // For cross-document commits with no matching pending entry, create a new
2000 // entry.
creisf49dfc92016-07-26 17:05:182001 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062002 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072003 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212004 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582005 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452006 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172007 nullptr, // blob_url_loader_factory
2008 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242009
2010 // Find out whether the new entry needs to update its virtual URL on URL
2011 // change and set up the entry accordingly. This is needed to correctly
2012 // update the virtual URL when replaceState is called after a pushState.
2013 GURL url = params.url;
2014 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492015 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412016 // update the virtual URL based on the new URL. For example, this is needed
2017 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2018 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372019 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2020 &url, browser_context_, &needs_update);
2021 new_entry->set_update_virtual_url_with_url(needs_update);
2022
Camille Lamy62b826012019-02-26 09:15:472023 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452024 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432025 }
2026
Harkiran Bolaria59290d62021-03-17 01:53:012027 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
2028 // for prerendered contents, if any. This is because prerendering/activation
2029 // technically won't be creating a new document. Unlike BFCache, prerendering
2030 // creates a new NavigationEntry rather than using an existing one.
2031 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372032 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2033 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002034 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082035
Harkiran Bolaria59290d62021-03-17 01:53:012036 // history.pushState() is classified as a navigation to a new page, but sets
2037 // is_same_document to true. In this case, we already have the title and
2038 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452039 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012040 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2041 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2042 }
[email protected]3a868f212014-08-09 10:41:192043 }
[email protected]ff64b3e2014-05-31 04:07:332044
[email protected]60d6cca2013-04-30 08:47:132045 DCHECK(!params.history_list_was_cleared || !replace_entry);
2046 // The browser requested to clear the session history when it initiated the
2047 // navigation. Now we know that the renderer has updated its state accordingly
2048 // and it is safe to also clear the browser side history.
2049 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552050 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132051 entries_.clear();
2052 last_committed_entry_index_ = -1;
2053 }
2054
Nasko Oskovaee2f862018-06-15 00:05:522055 // If this is a new navigation with replacement and there is a
2056 // pending_entry_ which matches the navigation reported by the renderer
2057 // process, then it should be the one replaced, so update the
2058 // last_committed_entry_index_ to use it.
2059 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092060 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522061 last_committed_entry_index_ = pending_entry_index_;
2062 }
2063
Alexander Timine3ec4192020-04-20 16:39:402064 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412065 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402066 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052067
Yuzu Saijoa725585f2022-11-28 04:14:032068 // If this is a history navigation and the old entry has an existing
2069 // back/forward cache metrics object, keep using the old one so that the
2070 // reasons logged from the last time the page navigated gets preserved.
2071 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2072 request)) {
2073 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2074 // because some tests do not have a pending entry.
2075 NavigationEntryImpl* entry =
2076 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2077 if (entry && entry->back_forward_cache_metrics()) {
2078 scoped_refptr<BackForwardCacheMetrics> metrics =
2079 entry->TakeBackForwardCacheMetrics();
2080 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2081 }
2082 }
2083
Carlos IL42b416592019-10-07 23:10:362084 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312085 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152086 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432087}
2088
Charlie Reisc0f17d2d2021-01-12 18:52:492089void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322090 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072091 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362092 bool is_same_document,
jam48cea9082017-02-15 06:13:292093 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452094 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002095 bool keep_pending_entry,
2096 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562097 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2098 << "that a last committed entry exists.";
2099
[email protected]e9ba4472008-09-14 15:42:432100 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002101 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432102
Charlie Reis7e2cb6d2021-01-26 01:27:162103 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002104 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162105 // We're guaranteed to have a last committed entry if intended_as_new_entry
2106 // is true.
avicbdc4c12015-07-01 16:07:112107 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162108
2109 // If the NavigationRequest matches a new pending entry and is classified as
2110 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2111 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092112 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162113 // Note: The pending entry will usually have a real ReloadType here, but
2114 // it can still be ReloadType::NONE in cases that
2115 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2116
2117 // If we classified this correctly, the SiteInstance should not have
2118 // changed.
2119 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2120
2121 // For converted reloads, we assign the entry's unique ID to be that of
2122 // the new one. Since this is always the result of a user action, we want
2123 // to dismiss infobars, etc. like a regular user-initiated navigation.
2124 entry->set_unique_id(pending_entry_->GetUniqueID());
2125
2126 // The extra headers may have changed due to reloading with different
2127 // headers.
2128 entry->set_extra_headers(pending_entry_->extra_headers());
2129 }
2130 // Otherwise, this was intended as a new entry but the pending entry was
2131 // lost in the meantime and no new entry was created. We are stuck at the
2132 // last committed entry.
2133
2134 // Even if this is a converted reload from pressing enter in the omnibox,
2135 // the server could redirect, requiring an update to the SSL status. If this
2136 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452137 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162138 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472139 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452140 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162141 }
Rakina Zata Amnif6950d552020-11-24 03:26:102142 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112143 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102144 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162145
eugenebut604866f2017-05-10 21:35:362146 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452147 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362148 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2149 // this was a restored same document navigation entry, then it won't have
2150 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2151 // navigated it.
jam48cea9082017-02-15 06:13:292152 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522153 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2154 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292155 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2156 was_restored) {
2157 entry->GetSSL() = last_entry->GetSSL();
2158 }
2159 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452160 // In rapid back/forward navigations |request| sometimes won't have a cert
2161 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192162 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452163 if (request->GetSSLInfo().has_value() &&
2164 request->GetSSLInfo()->is_valid()) {
2165 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522166 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2167 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192168 entry->GetSSL() = SSLStatus();
2169 }
jam48cea9082017-02-15 06:13:292170 }
avicbdc4c12015-07-01 16:07:112171 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272172 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572173 // navigations that are EXISTING_ENTRY are same-document navigations that
2174 // result in replacement (e.g. history.replaceState(), location.replace(),
2175 // forced replacements for trivial session history contexts). For these
2176 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112177 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102178
Mikel Astizba9cf2fd2017-12-17 10:38:102179 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2180 // to avoid misleading interpretations (e.g. URLs paired with
2181 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2182 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2183 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2184
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572185 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102186
eugenebut604866f2017-05-10 21:35:362187 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452188 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362189 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472190 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452191 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112192 }
2193 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432194
Rakina Zata Amni3460d382021-10-29 00:43:372195 UpdateNavigationEntryDetails(entry, rfh, params, request,
2196 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002197 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302198
[email protected]5ccd4dc2012-10-24 02:28:142199 // The redirected to page should not inherit the favicon from the previous
2200 // page.
eugenebut604866f2017-05-10 21:35:362201 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482202 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142203
Charlie Reis951f43372023-05-05 00:30:072204 // Update the last committed index to reflect the committed entry. Do this
2205 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2206 // delegate sees the correct committed index when notified of navigation
2207 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2208 // https://crbug.com/1439948.)
2209 if (base::FeatureList::IsEnabled(
2210 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2211 last_committed_entry_index_ = GetIndexOfEntry(entry);
2212 }
2213
Peter Boströmd7592132019-01-30 04:50:312214 // We should also usually discard the pending entry if it corresponds to a
2215 // different navigation, since that one is now likely canceled. In rare
2216 // cases, we leave the pending entry for another navigation in place when we
2217 // know it is still ongoing, to avoid a flicker in the omnibox (see
2218 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432219 //
2220 // Note that we need to use the "internal" version since we don't want to
2221 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312222 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002223 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392224
Charlie Reis951f43372023-05-05 00:30:072225 if (!base::FeatureList::IsEnabled(
2226 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2227 // Update the last committed index to reflect the committed entry.
2228 // (This is legacy behavior, in case the kill-switch needs to be used.)
2229 last_committed_entry_index_ = GetIndexOfEntry(entry);
2230 }
[email protected]e9ba4472008-09-14 15:42:432231}
2232
[email protected]d202a7c2012-01-04 07:53:472233void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322234 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072235 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362236 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472237 bool replace_entry,
2238 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002239 NavigationRequest* request,
2240 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262241 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2242 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552243 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2244 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112245
[email protected]e9ba4472008-09-14 15:42:432246 // Manual subframe navigations just get the current entry cloned so the user
2247 // can go back or forward to it. The actual subframe information will be
2248 // stored in the page state for each of those entries. This happens out of
2249 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092250 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2251 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382252
Mikel Astizba9cf2fd2017-12-17 10:38:102253 // The DCHECK below documents the fact that we don't know of any situation
2254 // where |replace_entry| is true for subframe navigations. This simplifies
2255 // reasoning about the replacement struct for subframes (see
2256 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2257 DCHECK(!replace_entry);
2258
Patrick Monette50e8bd82019-06-13 22:40:452259 // This FrameNavigationEntry might not end up being used in the
2260 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072261 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452262 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:522263 absl::optional<GURL> initiator_base_url;
2264 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2265 initiator_base_url = request->common_params().initiator_base_url;
2266 }
Nate Chapin63db0d12022-01-20 22:03:302267 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2268 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2269 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572270 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302271 if (is_same_document) {
2272 FrameNavigationEntry* previous_frame_entry =
2273 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572274 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302275 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572276 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302277 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572278 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302279 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572280 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302281 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572282 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302283 policy_container_policies->referrer_policy);
2284 }
2285
Patrick Monette50e8bd82019-06-13 22:40:452286 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482287 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572288 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082289 rfh->GetSiteInstance(), nullptr, params.url,
2290 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212291 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2292 request->GetRedirectChain(), params.page_state, params.method,
2293 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572294 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032295
creisce0ef3572017-01-26 17:53:082296 std::unique_ptr<NavigationEntryImpl> new_entry =
2297 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452298 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032299 frame_tree_->root());
creise062d542015-08-25 02:01:552300
Alexander Timine3ec4192020-04-20 16:39:402301 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412302 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402303 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472304
creisce0ef3572017-01-26 17:53:082305 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452306 // to replace, which can happen due to a unique name change. See
2307 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2308 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382309
Dave Tapuska87696ae2021-11-18 18:48:312310 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152311 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432312}
2313
[email protected]d202a7c2012-01-04 07:53:472314bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322315 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072316 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392317 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252318 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002319 NavigationRequest* request,
2320 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292321 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2322 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2323
[email protected]e9ba4472008-09-14 15:42:432324 // We're guaranteed to have a previously committed entry, and we now need to
2325 // handle navigation inside of a subframe in it without creating a new entry.
2326 DCHECK(GetLastCommittedEntry());
2327
creis913c63ce2016-07-16 19:52:522328 // For newly created subframes, we don't need to send a commit notification.
2329 // This is only necessary for history navigations in subframes.
2330 bool send_commit_notification = false;
2331
Rakina Zata Amnif6950d552020-11-24 03:26:102332 // If |nav_entry_id| is non-zero and matches an existing entry, this
2333 // is a history navigation. Update the last committed index accordingly. If
2334 // we don't recognize the |nav_entry_id|, it might be a recently
2335 // pruned entry. We'll handle it below.
2336 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2337 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472338 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062339 // Make sure that a subframe commit isn't changing the main frame's
2340 // origin. Otherwise the renderer process may be confused, leading to a
2341 // URL spoof. We can't check the path since that may change
2342 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572343 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2344 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242345 // We should use checks similar to RenderFrameHostImpl's
2346 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2347 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572348 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2349 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2350 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2351 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522352 current_top_url.DeprecatedGetOriginAsURL() !=
2353 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442354 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512355 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062356 }
creis3cdc3b02015-05-29 23:00:472357
creis913c63ce2016-07-16 19:52:522358 // We only need to discard the pending entry in this history navigation
2359 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062360 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002361 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522362
2363 // History navigations should send a commit notification.
2364 send_commit_notification = true;
avi98405c22015-05-21 20:47:062365 }
[email protected]e9ba4472008-09-14 15:42:432366 }
[email protected]f233e4232013-02-23 00:55:142367
creisce0ef3572017-01-26 17:53:082368 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2369 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372370 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2371 // exists), or we may want to clobber it and create a new one. We update in
2372 // cases where the corresponding FrameNavigationEntry is conceptually similar
2373 // to the document described by the commit params: same-document
2374 // navigations, history traversal to an existing entry, and reloads (including
2375 // a "soft reload" where we navigate to the same url without flagging it as a
2376 // reload). But in the case of a different document that is not logically
2377 // related to the committed FrameNavigationEntry's document (cross-document,
2378 // not same url, not a reload, not a history traversal), we replace rather
2379 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252380 //
Nate Chapin9f169072021-06-09 19:32:372381 // In the case where we update, the FrameNavigationEntry will potentially be
2382 // shared across multiple NavigationEntries, and any updates will be reflected
2383 // in all of those NavigationEntries. In the replace case, any existing
2384 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252385 //
2386 // When navigating away from the initial empty document, we also update rather
2387 // than replace. Either update or replace will overwrite the initial empty
2388 // document state for |last_committed|, but if the FrameNavigationEntry for
2389 // the initial empty document is shared across multiple NavigationEntries (due
2390 // to a navigation in another frame), we want to make sure we overwrite the
2391 // initial empty document state everywhere this FrameNavigationEntry is used,
2392 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452393 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372394 FrameNavigationEntry* last_committed_frame_entry =
2395 last_committed->GetFrameEntry(rfh->frame_tree_node());
2396 NavigationEntryImpl::UpdatePolicy update_policy =
2397 NavigationEntryImpl::UpdatePolicy::kUpdate;
2398 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312399 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372400 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252401 last_committed_frame_entry->url() != params.url &&
2402 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372403 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2404 }
2405
Rakina Zata Amni3460d382021-10-29 00:43:372406 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002407 update_policy, false /* is_new_entry */,
2408 commit_details);
creis625a0c7d2015-03-24 23:17:122409
creis913c63ce2016-07-16 19:52:522410 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432411}
2412
[email protected]d202a7c2012-01-04 07:53:472413int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232414 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032415 for (size_t i = 0; i < entries_.size(); ++i) {
2416 if (entries_[i].get() == entry)
2417 return i;
2418 }
2419 return -1;
[email protected]765b35502008-08-21 00:51:202420}
2421
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572422void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242423 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572424 NavigationControllerImpl* source =
2425 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572426 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382427 DCHECK_EQ(1, GetEntryCount());
2428 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472429 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172430 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572431
Francois Dorayeaace782017-06-21 16:37:242432 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442433 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572434 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572435
Fergal Dalya1d569972021-03-16 03:24:532436 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302437 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532438 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2439 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302440 }
[email protected]4e6419c2010-01-15 04:50:342441
Lukasz Anforowicz0de0f452020-12-02 19:57:152442 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572443}
2444
Aran Gilman37d11632019-10-08 23:07:152445void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2446 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162447 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012448 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162449
[email protected]d202a7c2012-01-04 07:53:472450 NavigationControllerImpl* source =
2451 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252452
avi2b177592014-12-10 02:08:022453 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012454 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252455
[email protected]474f8512013-05-31 22:31:162456 // We now have one entry, possibly with a new pending entry. Ensure that
2457 // adding the entries from source won't put us over the limit.
2458 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572459 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572460 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252461
Carlos IL4dea8902020-05-26 15:14:292462 // Insert the entries from source. Ignore any pending entry, since it has not
2463 // committed in source.
[email protected]474f8512013-05-31 22:31:162464 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172465 DCHECK_NE(max_source_index, -1);
2466 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572467
2468 // Ignore the source's current entry if merging with replacement.
2469 // TODO(davidben): This should preserve entries forward of the current
2470 // too. http://crbug.com/317872
2471 if (replace_entry && max_source_index > 0)
2472 max_source_index--;
2473
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572474 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252475
2476 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552477 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142478
Hayato Ito2c8c08d02021-06-23 03:38:432479 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252480}
2481
[email protected]79368982013-11-13 01:11:012482bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162483 // If there is no last committed entry, we cannot prune. Even if there is a
2484 // pending entry, it may not commit, leaving this WebContents blank, despite
2485 // possibly giving it new entries via CopyStateFromAndPrune.
2486 if (last_committed_entry_index_ == -1)
2487 return false;
[email protected]9350602e2013-02-26 23:27:442488
[email protected]474f8512013-05-31 22:31:162489 // We cannot prune if there is a pending entry at an existing entry index.
2490 // It may not commit, so we have to keep the last committed entry, and thus
2491 // there is no sensible place to keep the pending entry. It is ok to have
2492 // a new pending entry, which can optionally commit as a new navigation.
2493 if (pending_entry_index_ != -1)
2494 return false;
2495
[email protected]474f8512013-05-31 22:31:162496 return true;
2497}
2498
[email protected]79368982013-11-13 01:11:012499void NavigationControllerImpl::PruneAllButLastCommitted() {
2500 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162501
avi2b177592014-12-10 02:08:022502 DCHECK_EQ(0, last_committed_entry_index_);
2503 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442504
Hayato Ito2c8c08d02021-06-23 03:38:432505 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442506}
2507
[email protected]79368982013-11-13 01:11:012508void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162509 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012510 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262511
Nate Chapin9eb16be72022-09-23 22:54:312512 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2513
[email protected]474f8512013-05-31 22:31:162514 // Erase all entries but the last committed entry. There may still be a
2515 // new pending entry after this.
2516 entries_.erase(entries_.begin(),
2517 entries_.begin() + last_committed_entry_index_);
2518 entries_.erase(entries_.begin() + 1, entries_.end());
2519 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262520}
2521
Christian Dullweber1af31e62018-02-22 11:49:482522void NavigationControllerImpl::DeleteNavigationEntries(
2523 const DeletionPredicate& deletionPredicate) {
2524 // It is up to callers to check the invariants before calling this.
2525 CHECK(CanPruneAllButLastCommitted());
2526 std::vector<int> delete_indices;
2527 for (size_t i = 0; i < entries_.size(); i++) {
2528 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572529 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482530 delete_indices.push_back(i);
2531 }
2532 }
2533 if (delete_indices.empty())
2534 return;
2535
2536 if (delete_indices.size() == GetEntryCount() - 1U) {
2537 PruneAllButLastCommitted();
2538 } else {
2539 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382540 for (const auto& index : base::Reversed(delete_indices)) {
2541 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482542 }
Hayato Ito2c8c08d02021-06-23 03:38:432543 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482544 }
2545 delegate()->NotifyNavigationEntriesDeleted();
2546}
2547
Shivani Sharma883f5f32019-02-12 18:20:012548bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2549 auto* entry = GetEntryAtIndex(index);
2550 return entry && entry->should_skip_on_back_forward_ui();
2551}
2552
Carlos Caballero35ce710c2019-09-19 10:59:452553BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2554 return back_forward_cache_;
2555}
2556
William Liu055a3542023-04-02 17:21:192557NavigationEntryScreenshotCache*
2558NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
2559 CHECK_EQ(frame_tree_->type(), FrameTree::Type::kPrimary);
2560 if (!nav_entry_screenshot_cache_ && AreBackForwardTransitionsEnabled()) {
2561 nav_entry_screenshot_cache_ =
2562 std::make_unique<NavigationEntryScreenshotCache>(
2563 BrowserContextImpl::From(browser_context_)
2564 ->GetNavigationEntryScreenshotManager()
2565 ->GetSafeRef(),
2566 this);
2567 }
2568 return nav_entry_screenshot_cache_.get();
2569}
2570
clamy987a3752018-05-03 17:36:262571void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2572 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2573 // progress, since this will cause a use-after-free. (We only allow this
2574 // when the tab is being destroyed for shutdown, since it won't return to
2575 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032576 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262577
2578 if (was_failure && pending_entry_) {
2579 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2580 } else {
2581 failed_pending_entry_id_ = 0;
2582 }
2583
2584 if (pending_entry_) {
2585 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332586 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262587 pending_entry_index_ = -1;
2588 pending_entry_ = nullptr;
2589 }
arthursonzogni66f711c2019-10-08 14:40:362590
2591 // Ensure any refs to the current pending entry are ignored if they get
2592 // deleted, by clearing the set of known refs. All future pending entries will
2593 // only be affected by new refs.
2594 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262595}
2596
2597void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2598 if (pending_entry_)
2599 pending_entry_->set_ssl_error(error);
2600}
2601
Xiaohan Wang7f8052e02022-01-14 18:44:282602#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422603// static
2604bool NavigationControllerImpl::ValidateDataURLAsString(
2605 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2606 if (!data_url_as_string)
2607 return false;
2608
2609 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2610 return false;
2611
2612 // The number of characters that is enough for validating a data: URI.
2613 // From the GURL's POV, the only important part here is scheme, it doesn't
2614 // check the actual content. Thus we can take only the prefix of the url, to
2615 // avoid unneeded copying of a potentially long string.
2616 const size_t kDataUriPrefixMaxLen = 64;
2617 GURL data_url(
2618 std::string(data_url_as_string->front_as<char>(),
2619 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2620 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2621 return false;
2622
2623 return true;
2624}
2625#endif
2626
Shivani Sharma194877032019-03-07 17:52:472627void NavigationControllerImpl::NotifyUserActivation() {
2628 // When a user activation occurs, ensure that all adjacent entries for the
2629 // same document clear their skippable bit, so that the history manipulation
2630 // intervention does not apply to them.
shivanigithub99368382021-06-16 18:33:372631 if (base::FeatureList::IsEnabled(
2632 features::kDebugHistoryInterventionNoUserActivation)) {
2633 return;
2634 }
2635
Shivani Sharmac4cc8922019-04-18 03:11:172636 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472637}
2638
clamy987a3752018-05-03 17:36:262639bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2640 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332641 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2642 blink::LocalFrameToken initiator_frame_token,
2643 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262644 NavigationEntryImpl* entry =
2645 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2646 if (!entry)
2647 return false;
2648
2649 FrameNavigationEntry* frame_entry =
2650 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2651 if (!frame_entry)
2652 return false;
2653
Camille Lamy5193caa2018-10-12 11:59:422654 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572655 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232656 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332657 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2658 initiator_process_id);
clamyea99ea12018-05-28 13:54:232659
2660 if (!request)
2661 return false;
2662
arthursonzognif046d4a2019-12-12 19:08:102663 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412664
Rakina Zata Amni1c83b082023-02-08 01:09:002665 SCOPED_CRASH_KEY_STRING256(
2666 "Bug1400009", "req_url",
2667 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2668 SCOPED_CRASH_KEY_NUMBER(
2669 "Bug1400009", "nav_entry_si",
2670 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2671 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2672 frame_entry->site_instance()
2673 ? ((int)frame_entry->site_instance()->GetId())
2674 : -1);
2675 bool has_sig =
2676 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2677 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2678 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2679 has_sig ? (!!frame_tree_->GetRenderViewHost(
2680 frame_entry->site_instance()->group()))
2681 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052682 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2683 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232684
2685 return true;
clamy987a3752018-05-03 17:36:262686}
2687
Tsuyoshi Horo52fd08e2020-07-07 07:03:452688bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2689 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2690 if (!entry)
2691 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432692
2693 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2694 // We should never navigate to an existing initial NavigationEntry that is
2695 // the initial NavigationEntry for the initial empty document that hasn't
2696 // been overridden by the synchronous about:blank commit, to preserve
2697 // legacy behavior where trying to reload when the main frame is on the
2698 // initial empty document won't result in a navigation. See also
2699 // https://crbug.com/1277414.
2700 return false;
2701 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452702 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2703 if (!frame_entry)
2704 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142705 ReloadType reload_type = ReloadType::NORMAL;
2706 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452707 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142708 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452709 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432710 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332711 absl::nullopt /* initiator_frame_token */,
2712 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452713 if (!request)
2714 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052715 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452716 return true;
2717}
2718
clamy987a3752018-05-03 17:36:262719void NavigationControllerImpl::NavigateFromFrameProxy(
2720 RenderFrameHostImpl* render_frame_host,
2721 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022722 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452723 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072724 const absl::optional<url::Origin>& initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212725 const absl::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262726 bool is_renderer_initiated,
2727 SiteInstance* source_site_instance,
2728 const Referrer& referrer,
2729 ui::PageTransition page_transition,
2730 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252731 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262732 const std::string& method,
2733 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092734 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142735 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212736 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502737 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392738 const absl::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292739 blink::mojom::NavigationInitiatorActivationAndAdStatus
2740 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222741 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492742 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462743 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452744 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582745 bool is_container_initiated,
2746 absl::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582747 if (is_renderer_initiated)
2748 DCHECK(initiator_origin.has_value());
2749
clamy987a3752018-05-03 17:36:262750 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582751
Rakina Zata Amni2322f4f82022-01-24 13:24:242752 // Don't allow an entry replacement if there is no entry to replace.
2753 // http://crbug.com/457149
2754 if (GetEntryCount() == 0)
2755 should_replace_current_entry = false;
2756
clamy987a3752018-05-03 17:36:262757 // Create a NavigationEntry for the transfer, without making it the pending
2758 // entry. Subframe transfers should have a clone of the last committed entry
2759 // with a FrameNavigationEntry for the target frame. Main frame transfers
2760 // should have a new NavigationEntry.
2761 // TODO(creis): Make this unnecessary by creating (and validating) the params
2762 // directly, passing them to the destination RenderFrameHost. See
2763 // https://crbug.com/536906.
2764 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262765 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262766 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452767 DCHECK(GetLastCommittedEntry());
2768 entry = GetLastCommittedEntry()->Clone();
2769 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172770 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2771 // Renderer-initiated navigation that target a remote frame are currently
2772 // classified as browser-initiated when this one has already navigated.
2773 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372774 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2775 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2776 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2777 // same-document navigation), they will still be present in the
2778 // committed NavigationEntry that will be referenced to construct the new
2779 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262780 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082781 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582782 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072783 absl::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212784 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152785 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262786 } else {
2787 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172788 // If `node` is the outermost main frame, it rewrites a virtual url in order
2789 // to adjust the original input url if needed. For inner frames such as
2790 // fenced frames or subframes, they don't rewrite urls as the urls are not
2791 // input urls by users.
2792 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:322793 absl::optional<GURL> source_process_site_url = absl::nullopt;
2794 if (source_site_instance && source_site_instance->HasProcess()) {
2795 source_process_site_url =
2796 source_site_instance->GetProcess()->GetProcessLock().site_url();
2797 }
clamy987a3752018-05-03 17:36:262798 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212799 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322800 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212801 extra_headers, browser_context_, blob_url_loader_factory,
2802 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262803 entry->root_node()->frame_entry->set_source_site_instance(
2804 static_cast<SiteInstanceImpl*>(source_site_instance));
2805 entry->root_node()->frame_entry->set_method(method);
2806 }
clamy987a3752018-05-03 17:36:262807
Camille Lamy5193caa2018-10-12 11:59:422808 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452809 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262810 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422811 override_user_agent = true;
clamy987a3752018-05-03 17:36:262812 }
2813 // TODO(creis): Set user gesture and intent received timestamp on Android.
2814
2815 // We may not have successfully added the FrameNavigationEntry to |entry|
2816 // above (per https://crbug.com/608402), in which case we create it from
2817 // scratch. This works because we do not depend on |frame_entry| being inside
2818 // |entry| during NavigateToEntry. This will go away when we shortcut this
2819 // further in https://crbug.com/536906.
2820 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2821 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452822 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082823 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582824 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072825 absl::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212826 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152827 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572828 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262829 }
2830
Camille Lamy5193caa2018-10-12 11:59:422831 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022832 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452833 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292834 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212835 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422836 params.source_site_instance = source_site_instance;
2837 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2838 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032839 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422840 params.referrer = referrer;
2841 /* params.redirect_chain: skip */
2842 params.extra_headers = extra_headers;
2843 params.is_renderer_initiated = is_renderer_initiated;
2844 params.override_user_agent = UA_OVERRIDE_INHERIT;
2845 /* params.base_url_for_data_url: skip */
2846 /* params.virtual_url_for_data_url: skip */
2847 /* params.data_url_as_string: skip */
2848 params.post_data = post_body;
2849 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582850 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422851 /* params.frame_name: skip */
2852 // TODO(clamy): See if user gesture should be propagated to this function.
2853 params.has_user_gesture = false;
2854 params.should_clear_history_list = false;
2855 params.started_from_context_menu = false;
2856 /* params.navigation_ui_data: skip */
2857 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222858 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542859 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212860 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412861 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502862 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292863 params.initiator_activation_and_ad_status =
2864 initiator_activation_and_ad_status;
Camille Lamy5193caa2018-10-12 11:59:422865
2866 std::unique_ptr<NavigationRequest> request =
2867 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032868 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142869 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392870 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492871 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582872 is_unfenced_top_navigation, is_container_initiated,
2873 embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232874
2875 if (!request)
2876 return;
2877
Garrett Tanzerbb8db412022-09-27 21:59:462878 // Force the navigation to take place in a new browsing instance.
2879 // This is used by _unfencedTop in fenced frames to ensure that navigations
2880 // leaving the fenced context create a new browsing instance.
2881 if (force_new_browsing_instance) {
2882 request->coop_status().ForceBrowsingInstanceSwap();
2883 }
2884
Arthur Hemery948742762019-09-18 10:06:242885 // At this stage we are proceeding with this navigation. If this was renderer
2886 // initiated with user gesture, we need to make sure we clear up potential
2887 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2888 DiscardNonCommittedEntries();
2889
Lukasz Anforowicz9ee83c272020-12-01 20:14:052890 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262891}
2892
[email protected]d1198fd2012-08-13 22:50:192893void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252894 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212895 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192896 if (!session_storage_namespace)
2897 return;
2898
2899 // We can't overwrite an existing SessionStorage without violating spec.
2900 // Attempts to do so may give a tab access to another tab's session storage
2901 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152902 bool successful_insert =
2903 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252904 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052905 static_cast<SessionStorageNamespaceImpl*>(
2906 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302907 .second;
2908 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192909}
2910
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572911bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452912 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032913 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462914}
2915
Aran Gilman37d11632019-10-08 23:07:152916SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252917 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302918 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252919 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032920 DOMStorageContextWrapper* context_wrapper =
2921 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2922
2923 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252924 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032925 if (it != session_storage_namespace_map_.end()) {
2926 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152927 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2928 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472929
michaelnbacbcbd2016-02-09 00:32:032930 return it->second.get();
2931 }
2932
2933 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102934 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2935 SessionStorageNamespaceImpl::Create(context_wrapper);
2936 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2937 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252938 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102939 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302940
Daniel Murphy31bbb8b12018-02-07 21:44:102941 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302942}
2943
2944SessionStorageNamespace*
2945NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252946 return GetSessionStorageNamespace(
2947 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302948}
2949
2950const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572951NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302952 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552953}
[email protected]d202a7c2012-01-04 07:53:472954
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572955bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562956 return needs_reload_;
2957}
[email protected]a26023822011-12-29 00:23:552958
[email protected]46bb5e9c2013-10-03 22:16:472959void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412960 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2961}
2962
2963void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472964 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412965 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542966
2967 if (last_committed_entry_index_ != -1) {
2968 entries_[last_committed_entry_index_]->SetTransitionType(
2969 ui::PAGE_TRANSITION_RELOAD);
2970 }
[email protected]46bb5e9c2013-10-03 22:16:472971}
2972
[email protected]d202a7c2012-01-04 07:53:472973void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572974 DCHECK_LT(index, GetEntryCount());
2975 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312976 DiscardNonCommittedEntries();
2977
Nate Chapin9eb16be72022-09-23 22:54:312978 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:312979 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122980 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312981 last_committed_entry_index_--;
2982}
2983
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572984NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272985 // If there is no pending_entry_, there should be no pending_entry_index_.
2986 DCHECK(pending_entry_ || pending_entry_index_ == -1);
2987
2988 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:362989 // at that index. An exception is while a reload of a post commit error page
2990 // is ongoing; in that case pending entry will point to the entry replaced
2991 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:272992 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:362993 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
2994 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:272995
[email protected]022af742011-12-28 18:37:252996 return pending_entry_;
2997}
2998
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572999int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273000 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273001 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553002 return pending_entry_index_;
3003}
3004
avi25764702015-06-23 15:43:373005void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573006 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363007 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313008 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003009 bool in_fenced_frame_tree,
3010 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313011 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3012 // set because:
3013 // 1) They don't influence the history of the outer page.
3014 // 2) They are always replace only navigation (there is always only one entry
3015 // in their history stack).
3016 // 3) Are not top level navigations and appear similar to iframes.
3017 // Navigations of the fenced frame might create a new NavigationEntry, which
3018 // will call this function. Non fenced frame navigations will never have
3019 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3020 // InsertOrReplaceEntry.
3021 DCHECK_EQ(in_fenced_frame_tree,
3022 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3023 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203024
avi5cad4912015-06-19 05:25:443025 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3026 // need to keep continuity with the pending entry, so copy the pending entry's
3027 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3028 // then the renderer navigated on its own, independent of the pending entry,
3029 // so don't copy anything.
3030 if (pending_entry_ && pending_entry_index_ == -1)
3031 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203032
Rakina Zata Amnia4e27222021-12-22 01:05:003033 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203034
creisee17e932015-07-17 17:56:223035 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453036 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103037 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573038 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363039 // If the new entry is a post-commit error page, we store the current last
3040 // committed entry to the side so that we can put it back when navigating
3041 // away from the error.
3042 if (was_post_commit_error) {
3043 DCHECK(!entry_replaced_by_post_commit_error_);
3044 entry_replaced_by_post_commit_error_ =
3045 std::move(entries_[last_committed_entry_index_]);
3046 }
dcheng36b6aec92015-12-26 06:16:363047 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223048 return;
3049 }
[email protected]765b35502008-08-21 00:51:203050
creis37979a62015-08-04 19:48:183051 // We shouldn't see replace == true when there's no committed entries.
3052 DCHECK(!replace);
3053
Michael Thiessen9b14d512019-09-23 21:19:473054 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203055
Shivani Sharmad8c8d652019-02-13 17:27:573056 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203057
dcheng36b6aec92015-12-26 06:16:363058 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203059 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293060}
3061
Shivani Sharmad8c8d652019-02-13 17:27:573062void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163063 if (entries_.size() < max_entry_count())
3064 return;
3065
3066 DCHECK_EQ(max_entry_count(), entries_.size());
3067 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573068 CHECK_EQ(pending_entry_index_, -1);
3069
3070 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423071 // Retrieve the oldest skippable entry.
3072 for (; index < GetEntryCount(); index++) {
3073 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3074 break;
Shivani Sharmad8c8d652019-02-13 17:27:573075 }
3076
3077 // If there is no skippable entry or if it is the last committed entry then
3078 // fall back to pruning the oldest entry. It is not safe to prune the last
3079 // committed entry.
3080 if (index == GetEntryCount() || index == last_committed_entry_index_)
3081 index = 0;
3082
3083 bool should_succeed = RemoveEntryAtIndex(index);
3084 DCHECK_EQ(true, should_succeed);
3085
3086 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253087}
3088
clamy3cb9bea92018-07-10 12:42:023089void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163090 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203091 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:133092 absl::optional<blink::scheduler::TaskAttributionId>
3093 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203094 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503095 TRACE_EVENT0("navigation",
3096 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273097 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023098 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363099 if (pending_entry_index_ != -1) {
3100 // The pending entry may not be in entries_ if a post-commit error page is
3101 // showing.
3102 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3103 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3104 }
Gyuyoung Kim107c2a02021-04-13 01:49:303105 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573106 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013107 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033108 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573109 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133110 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3111 // the same as the top level frame being navigated.
3112 if (root->current_frame_host() != initiator_rfh) {
3113 soft_navigation_heuristics_task_id = absl::nullopt;
3114 }
Arthur Sonzogni620cec62018-12-13 13:08:573115
[email protected]83c2e232011-10-07 21:36:463116 // If we were navigating to a slow-to-commit page, and the user performs
3117 // a session history navigation to the last committed page, RenderViewHost
3118 // will force the throbber to start, but WebKit will essentially ignore the
3119 // navigation, and won't send a message to stop the throbber. To prevent this
3120 // from happening, we drop the navigation here and stop the slow-to-commit
3121 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023122 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083123 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273124 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033125 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123126
[email protected]83c2e232011-10-07 21:36:463127 DiscardNonCommittedEntries();
3128 return;
3129 }
3130
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333131 absl::optional<blink::LocalFrameToken> initiator_frame_token;
3132 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3133 if (initiator_rfh) {
3134 initiator_frame_token = initiator_rfh->GetFrameToken();
3135 initiator_process_id = initiator_rfh->GetProcess()->GetID();
3136 DCHECK(initiator_frame_token);
3137 }
3138
creisce0ef3572017-01-26 17:53:083139 // Compare FrameNavigationEntries to see which frames in the tree need to be
3140 // navigated.
clamy3cb9bea92018-07-10 12:42:023141 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3142 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333143 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3144 initiator_process_id, soft_navigation_heuristics_task_id,
3145 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303146
3147 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573148 // We were unable to match any frames to navigate. This can happen if a
3149 // history navigation targets a subframe that no longer exists
3150 // (https://crbug.com/705550). In this case, we need to update the current
3151 // history entry to the pending one but keep the main document loaded. We
3152 // also need to ensure that observers are informed about the updated
3153 // current history entry (e.g., for greying out back/forward buttons), and
3154 // that renderer processes update their history offsets. The easiest way
3155 // to do all that is to schedule a "redundant" same-document navigation in
3156 // the main frame.
3157 //
3158 // Note that we don't want to remove this history entry, as it might still
3159 // be valid later, since a frame that it's targeting may be recreated.
3160 //
3161 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3162 // need to repeat history navigations until finding the one that works.
3163 // Consider changing this behavior to keep looking for the first valid
3164 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023165 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423166 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573167 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573168 ReloadType::NONE /* reload_type */,
3169 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433170 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333171 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023172 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573173 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023174 DiscardPendingEntry(false);
3175 return;
3176 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573177 same_document_loads.push_back(std::move(navigation_request));
3178
3179 // Sanity check that we never take this branch for any kinds of reloads,
3180 // as those should've queued a different-document load in the main frame.
3181 DCHECK(!is_forced_reload);
3182 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303183 }
3184
Nate Chapinbf682fa32022-09-26 22:41:203185 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163186 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203187 if (initiator_rfh && initiator_rfh->IsSandboxed(
3188 network::mojom::WebSandboxFlags::kTopNavigation)) {
3189 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3190 initiator_rfh, same_document_loads) &&
3191 DoesSandboxNavigationStayWithinSubtree(
3192 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503193 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163194 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203195 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3196 initiator_rfh,
3197 navigates_inside_tree
3198 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3199 : blink::mojom::WebFeature::
3200 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523201
3202 // If the navigation occurred outside the tree discard it because
3203 // the sandboxed frame didn't have permission to navigate outside
3204 // its tree. If it is possible that the navigation is both inside and
3205 // outside the frame tree and we discard it entirely because we don't
3206 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143207 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203208 // If a |navigation_api_key| was provided, this navigation originated from
3209 // the navigation API. Notify the renderer that the navigation was
3210 // cancelled so the navigation API can fire an error event and reject the
3211 // relevant promise.
3212 if (navigation_api_key) {
3213 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3214 *navigation_api_key,
3215 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3216 }
Dave Tapuska855c1e12019-08-23 20:45:523217 DiscardPendingEntry(false);
3218 return;
3219 }
Dave Tapuska8bfd84c2019-03-26 20:47:163220 }
3221
Nate Chapin6c43c022023-02-13 23:32:423222 // If it is possible that this traverse may involve a same-document navigation
3223 // in the initiator and there is a Navigation API key involved, then we may
3224 // need to notify the initiator if it fails. (The early returns above either
3225 // do not involve these cases or already notify the initiator.)
3226 // The event only needs to fire for the initiator, and only if the initiator
3227 // itself is performing a same-document navigation (because the event will not
3228 // fire if it navigates cross-document).
3229 if (navigation_api_key) {
3230 for (auto& item : same_document_loads) {
3231 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3232 item->set_pending_navigation_api_key(*navigation_api_key);
3233 break;
3234 }
3235 }
3236 }
3237
Carlos Caballero539a421c2020-07-06 10:25:573238 // BackForwardCache:
3239 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563240 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573241 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3242 DCHECK_EQ(reload_type, ReloadType::NONE);
3243 auto navigation_request = CreateNavigationRequestFromEntry(
3244 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3245 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333246 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3247 initiator_process_id);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053248 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573249
3250 return;
3251 }
3252
3253 // History navigation might try to reuse a specific BrowsingInstance, already
3254 // used by a page in the cache. To avoid having two different main frames that
3255 // live in the same BrowsingInstance, evict the all pages with this
3256 // BrowsingInstance from the cache.
3257 //
3258 // For example, take the following scenario:
3259 //
3260 // A1 = Some page on a.com
3261 // A2 = Some other page on a.com
3262 // B3 = An uncacheable page on b.com
3263 //
3264 // Then the following navigations occur:
3265 // A1->A2->B3->A1
3266 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3267 // take its place) and A1 will be created in the same BrowsingInstance (and
3268 // SiteInstance), as A2.
3269 //
3270 // If we didn't do anything, both A1 and A2 would remain alive in the same
3271 // BrowsingInstance/SiteInstance, which is unsupported by
3272 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3273 // A2 from the cache.
3274 if (pending_entry_->site_instance()) {
3275 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3276 pending_entry_->site_instance());
3277 }
3278
Rakina Zata Amnid605d462022-06-01 10:17:033279 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3280 pending_entry_ && pending_entry_->IsRestored());
3281 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3282 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3283 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3284 pending_entry_index_);
3285 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3286 last_committed_entry_index_);
3287 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3288 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3289 pending_entry_ && pending_entry_->IsInitialEntry());
3290 SCOPED_CRASH_KEY_BOOL(
3291 "nav_reentrancy", "pending_entry_initial2",
3292 pending_entry_ &&
3293 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3294 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3295 IsInitialNavigation());
3296 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3297 IsInitialBlankNavigation());
3298 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3299 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3300 (int)pending_reload_);
3301
clamy3cb9bea92018-07-10 12:42:023302 // This call does not support re-entrancy. See http://crbug.com/347742.
3303 CHECK(!in_navigate_to_pending_entry_);
3304 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303305
Rakina Zata Amnid605d462022-06-01 10:17:033306 // If the navigation-reentrancy is caused by calling
3307 // NavigateToExistingPendingEntry twice, this will note the previous call's
3308 // pending entry's ID.
3309 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3310 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3311
arthursonzogni66f711c2019-10-08 14:40:363312 // It is not possible to delete the pending NavigationEntry while navigating
3313 // to it. Grab a reference to delay potential deletion until the end of this
3314 // function.
3315 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3316
Nate Chapin154b14b2023-02-17 18:28:163317 // If there is a main-frame same-document history navigation, we may defer
3318 // the subframe history navigations in order to give JS in the main frame the
3319 // opportunity to cancel the entire traverse via the navigate event. In that
3320 // case, we need to stash the main frame request's navigation token on the
3321 // subframes, so they can look up the main frame request and defer themselves
3322 // until it completes.
3323 if (!same_document_loads.empty() &&
3324 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3325 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3326 // The token will only be returned in cases where deferring the navigation
3327 // is necessary.
3328 if (auto main_frame_same_document_token =
3329 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3330 for (auto& item : same_document_loads) {
3331 if (item.get() != main_frame_request) {
3332 item->set_main_frame_same_document_history_token(
3333 main_frame_same_document_token);
3334 }
3335 }
3336 for (auto& item : different_document_loads) {
3337 item->set_main_frame_same_document_history_token(
3338 main_frame_same_document_token);
3339 }
3340 }
3341 }
3342
creis4e2ecb72015-06-20 00:46:303343 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023344 for (auto& item : same_document_loads) {
3345 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053346 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303347 }
clamy3cb9bea92018-07-10 12:42:023348 for (auto& item : different_document_loads) {
3349 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053350 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303351 }
clamy3cb9bea92018-07-10 12:42:023352
3353 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303354}
3355
Alex Moshchuk3a4e77a2020-05-29 21:32:573356NavigationControllerImpl::HistoryNavigationAction
3357NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303358 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573359 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423360 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583361 // Only active and prerendered documents are allowed to navigate in their
3362 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423363 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013364 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583365 // - If the document is in pending deletion, the browser already committed
3366 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3367 // - If the document is in back-forward cache, it's not allowed to navigate
3368 // as it should remain frozen. Ignore the request and evict the document
3369 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423370 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583371 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423372 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113373 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3374 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423375 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113376 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423377 }
arthursonzogni03f76152019-02-12 10:35:203378
Alex Moshchuk3a4e77a2020-05-29 21:32:573379 // Reloads should result in a different-document load. Note that reloads may
3380 // also happen via the |needs_reload_| mechanism where the reload_type is
3381 // NONE, so detect this by comparing whether we're going to the same
3382 // entry that we're currently on. Similarly to above, only main frames
3383 // should reach this. Note that subframes support reloads, but that's done
3384 // via a different path that doesn't involve FindFramesToNavigate (see
3385 // RenderFrameHost::Reload()).
3386 if (reload_type != ReloadType::NONE ||
3387 pending_entry_index_ == last_committed_entry_index_) {
3388 DCHECK(frame->IsMainFrame());
3389 return HistoryNavigationAction::kDifferentDocument;
3390 }
3391
Alex Moshchuk47d1a4bd2020-06-01 22:15:343392 // If there is no new FrameNavigationEntry for the frame, ignore the
3393 // load. For example, this may happen when going back to an entry before a
3394 // frame was created. Suppose we commit a same-document navigation that also
3395 // results in adding a new subframe somewhere in the tree. If we go back,
3396 // the new subframe will be missing a FrameNavigationEntry in the previous
3397 // NavigationEntry, but we shouldn't delete or change what's loaded in
3398 // it.
3399 //
Alex Moshchuke65c39272020-06-03 17:55:373400 // Note that in this case, there is no need to keep looking for navigations
3401 // in subframes, which would be missing FrameNavigationEntries as well.
3402 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343403 // It's important to check this before checking |old_item| below, since both
3404 // might be null, and in that case we still shouldn't change what's loaded in
3405 // this frame. Note that scheduling any loads assumes that |new_item| is
3406 // non-null. See https://crbug.com/1088354.
3407 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3408 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373409 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343410
Charlie Reisa474fb62022-03-17 02:31:363411 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3412 // which history item it is currently on, since this may be different than the
3413 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3414 // (e.g., if a history navigation is targeting multiple frames and only some
3415 // have committed so far).
creis4e2ecb72015-06-20 00:46:303416 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363417 frame->current_frame_host()->last_committed_frame_entry();
3418 if (!old_item) {
3419 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3420 // fall back to the last committed NavigationEntry's record for this frame.
3421 // This may happen in cases like the initial state of the RenderFrameHost.
3422 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3423 // accurate FrameNavigationEntry and eliminate this case.
3424 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3425 }
3426 // If neither approach finds a FrameNavigationEntry, schedule a
3427 // different-document load.
3428 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573429 if (!old_item)
3430 return HistoryNavigationAction::kDifferentDocument;
3431
Alex Moshchuk3a4e77a2020-05-29 21:32:573432 // If the new item is not in the same SiteInstance, schedule a
3433 // different-document load. Newly restored items may not have a SiteInstance
3434 // yet, in which case it will be assigned on first commit.
3435 if (new_item->site_instance() &&
3436 new_item->site_instance() != old_item->site_instance())
3437 return HistoryNavigationAction::kDifferentDocument;
3438
3439 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313440 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3441 // that we do this even if the history navigation would not be modifying this
3442 // frame were it live.
3443 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573444 return HistoryNavigationAction::kDifferentDocument;
3445
3446 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313447 // Starting a navigation after a crash early-promotes the speculative
3448 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3449 // committed yet, so we can not possibly perform a same-document history
3450 // navigation. The frame would need to be reloaded with a cross-document
3451 // navigation.
3452 if (!frame->current_frame_host()->has_committed_any_navigation())
3453 return HistoryNavigationAction::kDifferentDocument;
3454
creis54131692016-08-12 18:32:253455 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493456 // sequence number but different item sequence number.
3457 if (new_item->document_sequence_number() ==
3458 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573459 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493460 }
avib48cb312016-05-05 21:35:003461
Alex Moshchuk3a4e77a2020-05-29 21:32:573462 // Otherwise, if both item and document sequence numbers differ, this
3463 // should be a different document load.
3464 return HistoryNavigationAction::kDifferentDocument;
3465 }
3466
3467 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373468 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573469 DCHECK_EQ(new_item->document_sequence_number(),
3470 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373471 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573472}
3473
3474void NavigationControllerImpl::FindFramesToNavigate(
3475 FrameTreeNode* frame,
3476 ReloadType reload_type,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333477 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
3478 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133479 absl::optional<blink::scheduler::TaskAttributionId>
3480 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573481 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3482 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3483 DCHECK(pending_entry_);
3484 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3485
3486 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3487
3488 if (action == HistoryNavigationAction::kSameDocument) {
3489 std::unique_ptr<NavigationRequest> navigation_request =
3490 CreateNavigationRequestFromEntry(
3491 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133492 /*is_same_document_history_load=*/true,
3493 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333494 initiator_frame_token, initiator_process_id,
3495 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573496 if (navigation_request) {
3497 // Only add the request if was properly created. It's possible for the
3498 // creation to fail in certain cases, e.g. when the URL is invalid.
3499 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303500 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573501 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473502 std::unique_ptr<NavigationRequest> navigation_request =
3503 CreateNavigationRequestFromEntry(
3504 frame, pending_entry_, new_item, reload_type,
3505 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433506 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333507 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473508 if (navigation_request) {
3509 // Only add the request if was properly created. It's possible for the
3510 // creation to fail in certain cases, e.g. when the URL is invalid.
3511 different_document_loads->push_back(std::move(navigation_request));
3512 }
3513 // For a different document, the subframes will be destroyed, so there's
3514 // no need to consider them.
3515 return;
Alex Moshchuke65c39272020-06-03 17:55:373516 } else if (action == HistoryNavigationAction::kStopLooking) {
3517 return;
creis4e2ecb72015-06-20 00:46:303518 }
3519
Yoav Weiss8c573952022-11-17 17:35:133520 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3521 // we currently only support soft navigation heuristics for the top level
3522 // frame.
creis4e2ecb72015-06-20 00:46:303523 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333524 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3525 initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133526 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
Nate Chapin45f620582021-09-30 17:45:433527 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303528 }
3529}
3530
Harkiran Bolariaba823e42021-05-21 18:30:363531base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243532 const LoadURLParams& params) {
3533 // Find the appropriate FrameTreeNode.
3534 FrameTreeNode* node = nullptr;
3535 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3536 !params.frame_name.empty()) {
3537 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033538 ? frame_tree_->FindByID(params.frame_tree_node_id)
3539 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503540 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243541 }
3542
3543 // If no FrameTreeNode was specified, navigate the main frame.
3544 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033545 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243546
Camille Lamy5193caa2018-10-12 11:59:423547 // Compute overrides to the LoadURLParams for |override_user_agent|,
3548 // |should_replace_current_entry| and |has_user_gesture| that will be used
3549 // both in the creation of the NavigationEntry and the NavigationRequest.
3550 // Ideally, the LoadURLParams themselves would be updated, but since they are
3551 // passed as a const reference, this is not possible.
3552 // TODO(clamy): When we only create a NavigationRequest, move this to
3553 // CreateNavigationRequestFromLoadURLParams.
3554 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3555 GetLastCommittedEntry());
3556
Rakina Zata Amnie2d31312022-11-18 03:38:453557 // An entry replacement must happen if the current browsing context should
3558 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333559 bool should_replace_current_entry =
3560 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453561 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423562
clamy21718cc22018-06-13 13:34:243563 // Javascript URLs should not create NavigationEntries. All other navigations
3564 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243565 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373566 std::unique_ptr<NavigationEntryImpl> entry =
3567 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3568 should_replace_current_entry,
3569 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243570 DiscardPendingEntry(false);
3571 SetPendingEntry(std::move(entry));
3572 }
3573
Tim Judkins59548192023-05-17 17:51:203574 // Renderer-debug URLs are sent to the current renderer process immediately
3575 // for processing and don't need to create a NavigationRequest. Note: this
3576 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243577 // renderer-debug URLs.
3578 // Note: we intentionally leave the pending entry in place for renderer debug
3579 // URLs, unlike the cases below where we clear it if the navigation doesn't
3580 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303581 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483582 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3583 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153584 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203585 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483586 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363587 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483588 }
3589
clamy21718cc22018-06-13 13:34:243590 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363591 return nullptr;
clamy21718cc22018-06-13 13:34:243592 }
3593
Antonio Sartori78a749f2020-11-30 12:03:393594 DCHECK(pending_entry_);
3595
clamy21718cc22018-06-13 13:34:243596 // Convert navigations to the current URL to a reload.
3597 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3598 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3599 // DevTools sometimes issues navigations to main frames that they do not
3600 // expect to see treated as reload, and it only works because they pass a
3601 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3602 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543603 ReloadType reload_type = params.reload_type;
3604 if (reload_type == ReloadType::NONE &&
3605 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043606 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243607 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243608 params.load_type ==
3609 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543610 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243611 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473612 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393613
3614 // If this is a reload of an existing FrameNavigationEntry and we had a
3615 // policy container for it, then we should copy it into the pending entry,
3616 // so that it is copied to the navigation request in
3617 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453618 FrameNavigationEntry* previous_frame_entry =
3619 GetLastCommittedEntry()->GetFrameEntry(node);
3620 if (previous_frame_entry &&
3621 previous_frame_entry->policy_container_policies()) {
3622 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3623 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393624 }
3625 }
3626
3627 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173628 // document, then we should copy the document polices from RenderFrameHost's
3629 // PolicyContainerHost. The NavigationRequest will create a new
3630 // PolicyContainerHost with the document policies from the |pending_entry_|,
3631 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3632 // the navigation. This way, we ensure that we keep enforcing the right
3633 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453634 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393635 if (node->current_frame_host() &&
3636 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193637 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163638 node->current_frame_host()
3639 ->policy_container_host()
3640 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233641 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393642 }
clamy21718cc22018-06-13 13:34:243643 }
3644
3645 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263646 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243647
Tsuyoshi Horo167ca6432022-03-09 05:16:393648 // This will be used to set the Navigation Timing API navigationStart
3649 // parameter for browser navigations in new tabs (intents, tabs opened through
3650 // "Open link in new tab"). If the navigation must wait on the current
3651 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3652 // will be updated when the BeforeUnload ack is received.
3653 const auto navigation_start_time = base::TimeTicks::Now();
3654
Camille Lamy5193caa2018-10-12 11:59:423655 std::unique_ptr<NavigationRequest> request =
3656 CreateNavigationRequestFromLoadParams(
3657 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143658 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393659 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3660 navigation_start_time);
clamy21718cc22018-06-13 13:34:243661
3662 // If the navigation couldn't start, return immediately and discard the
3663 // pending NavigationEntry.
3664 if (!request) {
3665 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363666 return nullptr;
clamy21718cc22018-06-13 13:34:243667 }
3668
Camille Lamy5193caa2018-10-12 11:59:423669#if DCHECK_IS_ON()
3670 // Safety check that NavigationRequest and NavigationEntry match.
3671 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3672#endif
3673
clamy21718cc22018-06-13 13:34:243674 // This call does not support re-entrancy. See http://crbug.com/347742.
3675 CHECK(!in_navigate_to_pending_entry_);
3676 in_navigate_to_pending_entry_ = true;
3677
arthursonzogni66f711c2019-10-08 14:40:363678 // It is not possible to delete the pending NavigationEntry while navigating
3679 // to it. Grab a reference to delay potential deletion until the end of this
3680 // function.
3681 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3682
Harkiran Bolariaba823e42021-05-21 18:30:363683 base::WeakPtr<NavigationHandle> created_navigation_handle(
3684 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053685 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243686
3687 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363688 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243689}
3690
clamyea99ea12018-05-28 13:54:233691void NavigationControllerImpl::HandleRendererDebugURL(
3692 FrameTreeNode* frame_tree_node,
3693 const GURL& url) {
3694 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243695 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3696 // the renderer process is not live, unless it is the initial navigation
3697 // of the tab.
clamyea99ea12018-05-28 13:54:233698 if (!IsInitialNavigation()) {
3699 DiscardNonCommittedEntries();
3700 return;
3701 }
Fergal Dalyecd3b0202020-06-25 01:57:373702 // The current frame is always a main frame. If IsInitialNavigation() is
3703 // true then there have been no navigations and any frames of this tab must
3704 // be in the same renderer process. If that has crashed then the only frame
3705 // that can be revived is the main frame.
3706 frame_tree_node->render_manager()
3707 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233708 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223709
3710 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3711 // notification, so set is loading to true here to properly surface it when
3712 // the renderer process is done handling the URL.
3713 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3714 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223715 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223716 }
clamyea99ea12018-05-28 13:54:233717 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3718}
3719
clamy21718cc22018-06-13 13:34:243720std::unique_ptr<NavigationEntryImpl>
3721NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3722 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423723 const LoadURLParams& params,
3724 bool override_user_agent,
3725 bool should_replace_current_entry,
3726 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393727 // Browser initiated navigations might not have a blob_url_loader_factory set
3728 // in params even if the navigation is to a blob URL. If that happens, lookup
3729 // the correct url loader factory to use here.
3730 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483731 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473732 // Resolve the blob URL in the storage partition associated with the target
3733 // frame. This is the storage partition the URL will be loaded in, and only
3734 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393735 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473736 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393737 }
3738
clamy21718cc22018-06-13 13:34:243739 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443740 // extra_headers in params are \n separated; navigation entries want \r\n.
3741 std::string extra_headers_crlf;
3742 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243743
3744 // For subframes, create a pending entry with a corresponding frame entry.
3745 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453746 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243747 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083748 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243749 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073750 params.url, absl::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213751 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3752 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393753 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163754 // a conversion of a new navigation into a reload, we will set the right
3755 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193756 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243757 } else {
3758 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173759 // If `node` is the outermost main frame, it rewrites a virtual url in order
3760 // to adjust the original input url if needed. For inner frames such as
3761 // fenced frames or subframes, they don't rewrite urls as the urls are not
3762 // input urls by users.
3763 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323764 scoped_refptr<SiteInstance> source_site_instance =
3765 params.source_site_instance;
3766 absl::optional<GURL> source_process_site_url = absl::nullopt;
3767 if (source_site_instance && source_site_instance->HasProcess()) {
3768 source_process_site_url =
3769 source_site_instance->GetProcess()->GetProcessLock().site_url();
3770 }
clamy21718cc22018-06-13 13:34:243771 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063772 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323773 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213774 params.transition_type, params.is_renderer_initiated,
3775 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3776 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243777 entry->set_source_site_instance(
3778 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3779 entry->SetRedirectChain(params.redirect_chain);
3780 }
3781
3782 // Set the FTN ID (only used in non-site-per-process, for tests).
3783 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243784 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423785 entry->SetIsOverridingUserAgent(override_user_agent);
3786 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543787 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243788
clamy21718cc22018-06-13 13:34:243789 switch (params.load_type) {
3790 case LOAD_TYPE_DEFAULT:
3791 break;
3792 case LOAD_TYPE_HTTP_POST:
3793 entry->SetHasPostData(true);
3794 entry->SetPostData(params.post_data);
3795 break;
3796 case LOAD_TYPE_DATA:
3797 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3798 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283799#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243800 entry->SetDataURLAsString(params.data_url_as_string);
3801#endif
3802 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3803 break;
clamy21718cc22018-06-13 13:34:243804 }
3805
3806 // TODO(clamy): NavigationEntry is meant for information that will be kept
3807 // after the navigation ended and therefore is not appropriate for
3808 // started_from_context_menu. Move started_from_context_menu to
3809 // NavigationUIData.
3810 entry->set_started_from_context_menu(params.started_from_context_menu);
3811
3812 return entry;
3813}
3814
clamyea99ea12018-05-28 13:54:233815std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423816NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3817 FrameTreeNode* node,
3818 const LoadURLParams& params,
3819 bool override_user_agent,
3820 bool should_replace_current_entry,
3821 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143822 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423823 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573824 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393825 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223826 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493827 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453828 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583829 bool is_container_initiated,
3830 absl::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573831 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283832 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533833 // All renderer-initiated navigations must have an initiator_origin.
3834 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513835
Camille Lamy5193caa2018-10-12 11:59:423836 GURL url_to_load;
3837 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323838
Camille Lamy2baa8022018-10-19 16:43:173839 // For main frames, rewrite the URL if necessary and compute the virtual URL
3840 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263841 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423842 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173843 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423844 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423845
Camille Lamy2baa8022018-10-19 16:43:173846 // For DATA loads, override the virtual URL.
3847 if (params.load_type == LOAD_TYPE_DATA)
3848 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423849
Camille Lamy2baa8022018-10-19 16:43:173850 if (virtual_url.is_empty())
3851 virtual_url = url_to_load;
3852
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573853 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283854
Aran Gilman249eb122019-12-02 23:32:463855 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3856 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3857 // return different results, leading to a different URL in the
3858 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3859 // pending NavigationEntry, as we'll only make one call to
3860 // RewriteUrlForNavigation.
3861 VLOG_IF(1, (url_to_load != frame_entry->url()))
3862 << "NavigationRequest and FrameEntry have different URLs: "
3863 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283864
Camille Lamy2baa8022018-10-19 16:43:173865 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423866 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173867 // NavigationRequest.
3868 } else {
3869 url_to_load = params.url;
3870 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243871 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173872 }
Camille Lamy5193caa2018-10-12 11:59:423873
Ehsan Karamad44fc72112019-02-26 18:15:473874 if (node->render_manager()->is_attaching_inner_delegate()) {
3875 // Avoid starting any new navigations since this node is now preparing for
3876 // attaching an inner delegate.
3877 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203878 }
Camille Lamy5193caa2018-10-12 11:59:423879
Alex Moshchuk99242832023-05-22 17:21:443880 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:423881 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:443882 }
Camille Lamy5193caa2018-10-12 11:59:423883
danakjd83d706d2020-11-25 22:11:123884 // Look for a pending commit that is to another document in this
3885 // FrameTreeNode. If one exists, then the last committed URL will not be the
3886 // current URL by the time this navigation commits.
3887 bool has_pending_cross_document_commit =
3888 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213889 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123890
Minggang Wangb9f3fa92021-07-01 15:30:313891 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493892 /*old_url=*/node->current_url(),
3893 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3894 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133895 /*is_same_document_history_load=*/false,
3896 is_embedder_initiated_fenced_frame_navigation,
3897 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423898
3899 // Create the NavigationParams based on |params|.
3900
Hiroki Nakagawa4ed61282021-06-18 05:37:233901 bool is_view_source_mode = entry->IsViewSourceMode();
3902 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293903
Antonio Sartori6984c742021-08-26 08:03:413904 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:293905
Hiroki Nakagawa4ed61282021-06-18 05:37:233906 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293907 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253908 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293909
Minggang Wangb9f3fa92021-07-01 15:30:313910 blink::mojom::CommonNavigationParamsPtr common_params =
3911 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:213912 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513913 blink::mojom::Referrer::New(params.referrer.url,
3914 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213915 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513916 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393917 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513918 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143919 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413920 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273921 false /* has_text_fragment_token */,
3922 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3923 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513924 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:053925 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423926
Minggang Wangb9f3fa92021-07-01 15:30:313927 blink::mojom::CommitNavigationParamsPtr commit_params =
3928 blink::mojom::CommitNavigationParams::New(
Rakina Zata Amnic7367852022-11-07 17:10:403929 absl::nullopt,
Ari Chivukula43d2cf82023-01-24 03:16:073930 // The correct storage key and session storage key will be computed
3931 // before committing the navigation.
3932 blink::StorageKey(), blink::StorageKey(), override_user_agent,
3933 params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323934 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503935 std::vector<net::RedirectInfo>(), params.post_content_type,
3936 common_params->url, common_params->method,
3937 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313938 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133939 entry->GetSubframeUniqueNames(node),
3940 /*intended_as_new_entry=*/true,
3941 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143942 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3943 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:133944 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313945 params.should_clear_history_list,
3946 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223947 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:133948 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:513949 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283950#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:133951 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143952#endif
Yoav Weiss8c573952022-11-17 17:35:133953 /*is_browser_initiated=*/!params.is_renderer_initiated,
Yoav Weiss8c573952022-11-17 17:35:133954 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:073955 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133956 /*force_enabled_origin_trials=*/std::vector<std::string>(),
3957 /*origin_agent_cluster=*/false,
3958 /*origin_agent_cluster_left_as_default=*/true,
3959 /*enabled_client_hints=*/
3960 std::vector<network::mojom::WebClientHintsType>(),
3961 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
3962 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:013963 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:133964 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:583965 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:133966 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:133967 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:283968 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:133969 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:443970 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:423971 network::mojom::NavigationDeliveryType::kDefault,
Yoav Weiss8c573952022-11-17 17:35:133972 /*view_transition_state=*/absl::nullopt,
sbinglera07ae732022-12-02 20:49:053973 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
3974 /*modified_runtime_features=*/
Garrett Tanzer29de7112022-12-06 21:26:323975 base::flat_map<::blink::mojom::RuntimeFeatureState, bool>(),
Yuzu Saijo29f96ca92022-12-08 04:54:123976 /*fenced_frame_properties=*/absl::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:053977 /*not_restored_reasons=*/nullptr,
Arthur Hemeryd51484b2023-06-02 15:50:003978 /*load_with_storage_access=*/false,
3979 /*browsing_context_group_info=*/absl::nullopt);
Xiaohan Wang7f8052e02022-01-14 18:44:283980#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423981 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143982 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423983 }
3984#endif
3985
Lucas Furukawa Gadania9c45682019-07-31 22:05:143986 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:073987 commit_params->navigation_timing->system_entropy_at_navigation_start =
3988 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
3989 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:423990
Camille Lamy5193caa2018-10-12 11:59:423991 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3992 std::string extra_headers_crlf;
3993 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:093994
Alex Moshchuk9321e6a2022-12-07 21:58:313995 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143996 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:083997 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:093998 params.initiator_frame_token, params.initiator_process_id,
3999 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214000 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294001 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454002 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584003 is_container_initiated, embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:094004 navigation_request->set_from_download_cross_origin_redirect(
4005 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554006 navigation_request->set_force_new_browsing_instance(
4007 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:094008 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424009}
4010
4011std::unique_ptr<NavigationRequest>
4012NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234013 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574014 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234015 FrameNavigationEntry* frame_entry,
4016 ReloadType reload_type,
4017 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434018 bool is_history_navigation_in_new_child_frame,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334019 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
4020 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:134021 absl::optional<blink::scheduler::TaskAttributionId>
4022 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344023 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234024 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434025 // We should never navigate to an existing initial NavigationEntry that is the
4026 // initial NavigationEntry for the initial empty document that hasn't been
4027 // overridden by the synchronous about:blank commit, to preserve previous
4028 // behavior where trying to reload when the main frame is on the initial empty
4029 // document won't result in a navigation.
4030 // See also https://crbug.com/1277414.
4031 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324032
clamyea99ea12018-05-28 13:54:234033 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:014034 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574035 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:234036 // We may have been redirected when navigating to the current URL.
4037 // Use the URL the user originally intended to visit as signaled by the
4038 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:014039 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574040 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:234041 dest_referrer = Referrer();
clamyea99ea12018-05-28 13:54:234042 }
4043
Ehsan Karamad44fc72112019-02-26 18:15:474044 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4045 // Avoid starting any new navigations since this node is now preparing for
4046 // attaching an inner delegate.
4047 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204048 }
4049
Alex Moshchuk99242832023-05-22 17:21:444050 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4051 dest_url)) {
clamyea99ea12018-05-28 13:54:234052 return nullptr;
4053 }
4054
clamyea99ea12018-05-28 13:54:234055 // This will be used to set the Navigation Timing API navigationStart
4056 // parameter for browser navigations in new tabs (intents, tabs opened through
4057 // "Open link in new tab"). If the navigation must wait on the current
4058 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4059 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074060
clamyea99ea12018-05-28 13:54:234061 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074062 const auto navigation_start_system_entropy =
4063 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4064 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234065
danakjd83d706d2020-11-25 22:11:124066 // Look for a pending commit that is to another document in this
4067 // FrameTreeNode. If one exists, then the last committed URL will not be the
4068 // current URL by the time this navigation commits.
4069 bool has_pending_cross_document_commit =
4070 frame_tree_node->render_manager()
4071 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494072 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214073 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124074
Minggang Wangb9f3fa92021-07-01 15:30:314075 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124076 /*old_url=*/frame_tree_node->current_url(),
4077 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:494078 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494079 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134080 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494081 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424082
4083 // A form submission may happen here if the navigation is a
4084 // back/forward/reload navigation that does a form resubmission.
4085 scoped_refptr<network::ResourceRequestBody> request_body;
4086 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:504087 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
4088 // entry. This way, it could be directly retrieved here. Right now, it is only
4089 // partially recovered when request.method == "POST" and request.body exists.
4090 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424091 if (frame_entry->method() == "POST") {
4092 request_body = frame_entry->GetPostData(&post_content_type);
4093 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304094 post_content_type = std::string(
4095 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504096 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424097 }
4098
4099 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314100 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514101 entry->ConstructCommonNavigationParams(
4102 *frame_entry, request_body, dest_url,
4103 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384104 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534105 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514106 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554107 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424108
4109 // TODO(clamy): |intended_as_new_entry| below should always be false once
4110 // Reload no longer leads to this being called for a pending NavigationEntry
4111 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314112 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144113 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404114 *frame_entry, common_params->url, common_params->method,
4115 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144116 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534117 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484118 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134119 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074120 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144121 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074122 commit_params->navigation_timing->system_entropy_at_navigation_start =
4123 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4124 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Camille Lamy5193caa2018-10-12 11:59:424125
W. James MacLeanb7d6092682022-10-05 15:23:264126 if (common_params->url.IsAboutSrcdoc()) {
4127 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4128 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594129 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264130 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334131 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314132 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144133 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434134 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334135 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4136 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
4137 absl::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294138 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4139 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474140 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234141}
4142
[email protected]d202a7c2012-01-04 07:53:474143void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214144 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274145 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404146
Takashi Toyoshimaea534ef22021-07-21 03:27:594147 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404148 // location bar will have up-to-date information about the security style
4149 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134150 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404151
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374152 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574153 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:464154
[email protected]b0f724c2013-09-05 04:21:134155 // TODO(avi): Remove. http://crbug.com/170921
4156 NotificationDetails notification_details =
4157 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154158 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4159 Source<NavigationController>(this),
4160 notification_details);
initial.commit09911bf2008-07-26 23:55:294161}
4162
initial.commit09911bf2008-07-26 23:55:294163// static
[email protected]d202a7c2012-01-04 07:53:474164size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234165 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154166 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214167 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234168}
4169
[email protected]d202a7c2012-01-04 07:53:474170void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224171 if (is_active && needs_reload_)
4172 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294173}
4174
[email protected]d202a7c2012-01-04 07:53:474175void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034176 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4177 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294178 if (!needs_reload_)
4179 return;
4180
Bo Liucdfa4b12018-11-06 00:21:444181 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4182 needs_reload_type_);
4183
initial.commit09911bf2008-07-26 23:55:294184 // Calling Reload() results in ignoring state, and not loading.
4185 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4186 // cached state.
avicc872d7242015-08-19 21:26:344187 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134188 NavigateToExistingPendingEntry(
4189 ReloadType::NONE,
4190 /*initiator_rfh=*/nullptr,
4191 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4192 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454193 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434194 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274195 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344196 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134197 NavigateToExistingPendingEntry(
4198 ReloadType::NONE,
4199 /*initiator_rfh=*/nullptr,
4200 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4201 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344202 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434203 // We should never navigate to an existing initial NavigationEntry that is
4204 // the initial NavigationEntry for the initial empty document that hasn't
4205 // been overridden by the synchronous about:blank commit, to preserve
4206 // legacy behavior where trying to reload when the main frame is on the
4207 // initial empty document won't result in a navigation. See also
4208 // https://crbug.com/1277414. If there is something to reload, the
4209 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4210 // it here.
avicc872d7242015-08-19 21:26:344211 needs_reload_ = false;
4212 }
initial.commit09911bf2008-07-26 23:55:294213}
4214
Kevin McNeeccca6172021-10-19 17:11:144215base::WeakPtr<NavigationHandle>
4216NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364217 RenderFrameHost* render_frame_host,
4218 const GURL& url,
4219 const std::string& error_page_html,
4220 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134221 RenderFrameHostImpl* rfhi =
4222 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584223
4224 // Only active documents can load post-commit error pages:
4225 // - If the document is in pending deletion, the browser already committed to
4226 // destroying this RenderFrameHost so ignore loading the error page.
4227 // - If the document is in back-forward cache, it's not allowed to navigate as
4228 // it should remain frozen. Ignore the request and evict the document from
4229 // back-forward cache.
4230 // - If the document is prerendering, it can navigate but when loading error
4231 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114232 if (rfhi->IsInactiveAndDisallowActivation(
4233 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144234 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114235 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584236
Rakina Zata Amni919b7922020-12-11 09:03:134237 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414238
Minggang Wangb9f3fa92021-07-01 15:30:314239 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434240 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594241 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4242 // the frame actually committed (e.g. iframe with "src" set to a
4243 // slow-responding URL). We should rewrite the URL to about:blank in this
4244 // case, as the renderer will only think a page is an error page if it has a
4245 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134246 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314247 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434248 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334249 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414250
Mike Jacksone2aa7af2023-05-17 06:45:074251 commit_params->navigation_timing->system_entropy_at_navigation_start =
4252 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4253 node, blink::mojom::SystemEntropy::kNormal);
4254
arthursonzogni70ac7302020-05-28 08:49:054255 // Error pages have a fully permissive FramePolicy.
4256 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4257 // error pages.
4258 commit_params->frame_policy = blink::FramePolicy();
4259
John Delaney131ad362019-08-08 21:57:414260 std::unique_ptr<NavigationRequest> navigation_request =
4261 NavigationRequest::CreateBrowserInitiated(
4262 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094263 false /* was_opener_suppressed */, "" /* extra_headers */,
4264 nullptr /* frame_entry */, nullptr /* entry */,
4265 false /* is_form_submission */, nullptr /* navigation_ui_data */,
4266 absl::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364267 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414268 navigation_request->set_net_error(error);
Charlie Reis09952ee2022-12-08 16:35:074269 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414270 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144271
4272 // Calling BeginNavigation may destroy the NavigationRequest.
4273 base::WeakPtr<NavigationRequest> created_navigation_request(
4274 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414275 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144276 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414277}
4278
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574279void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214280 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094281 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154282 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144283 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294284}
4285
[email protected]d202a7c2012-01-04 07:53:474286void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364287 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474288 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4289 // represent a no-committed-entry state.
4290 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364291 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474292 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4293 // if `entries_` contains pre-existing entries from the NavigationController
4294 // before restore, which would not be removed and will be at the front of the
4295 // entries list, causing the index to be off by the amount of pre-existing
4296 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294297 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294298}
[email protected]765b35502008-08-21 00:51:204299
arthursonzogni69a6a1b2019-09-17 09:23:004300void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004301 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4302}
4303
4304void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4305 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474306 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104307 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4308 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294309 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474310 return;
Michael Thiessenc5676d22019-09-25 22:32:104311 }
avi45a72532015-04-07 21:01:454312 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314313
4314 if (!delegate_)
4315 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374316 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484317}
4318
avi7c6f35e2015-05-08 17:52:384319int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4320 int nav_entry_id) const {
4321 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4322 if (entries_[i]->GetUniqueID() == nav_entry_id)
4323 return i;
4324 }
4325 return -1;
4326}
4327
[email protected]d202a7c2012-01-04 07:53:474328void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574329 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254330 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574331 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574332 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4333 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254334 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374335 // Normally, cloning a NavigationEntryImpl results in sharing
4336 // FrameNavigationEntries between the original and the clone. However, when
4337 // cloning from a different NavigationControllerImpl, we want to fork the
4338 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374339 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574340 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254341 }
Rakina Zata Amnie2d31312022-11-18 03:38:454342 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274343 DCHECK(pending_entry_index_ == -1 ||
4344 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254345}
[email protected]c5b88d82012-10-06 17:03:334346
4347void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184348 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334349 get_timestamp_callback_ = get_timestamp_callback;
4350}
[email protected]8ff00d72012-10-23 19:12:214351
Shivani Sharmaffb32b82019-04-09 16:58:474352// History manipulation intervention:
4353void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474354 bool replace_entry,
4355 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404356 bool is_renderer_initiated,
4357 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454358 // Note that for a subframe, previous_document_was_activated is true if the
4359 // gesture happened in any subframe (propagated to main frame) or in the main
4360 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474361 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274362 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474363 return;
4364 }
4365 if (last_committed_entry_index_ == -1)
4366 return;
4367
Shivani Sharmac4cc8922019-04-18 03:11:174368 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474369
Alexander Timine3ec4192020-04-20 16:39:404370 // Log UKM with the URL we are navigating away from.
4371 ukm::builders::HistoryManipulationIntervention(
4372 previous_page_load_ukm_source_id)
4373 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474374}
4375
Shivani Sharmac4cc8922019-04-18 03:11:174376void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4377 int reference_index,
4378 bool skippable) {
4379 auto* reference_entry = GetEntryAtIndex(reference_index);
4380 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4381
4382 int64_t document_sequence_number =
4383 reference_entry->root_node()->frame_entry->document_sequence_number();
4384 for (int index = 0; index < GetEntryCount(); index++) {
4385 auto* entry = GetEntryAtIndex(index);
4386 if (entry->root_node()->frame_entry->document_sequence_number() ==
4387 document_sequence_number) {
4388 entry->set_should_skip_on_back_forward_ui(skippable);
4389 }
4390 }
4391}
4392
arthursonzogni66f711c2019-10-08 14:40:364393std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4394NavigationControllerImpl::ReferencePendingEntry() {
4395 DCHECK(pending_entry_);
4396 auto pending_entry_ref =
4397 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4398 pending_entry_refs_.insert(pending_entry_ref.get());
4399 return pending_entry_ref;
4400}
4401
4402void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4403 // Ignore refs that don't correspond to the current pending entry.
4404 auto it = pending_entry_refs_.find(ref);
4405 if (it == pending_entry_refs_.end())
4406 return;
4407 pending_entry_refs_.erase(it);
4408
4409 if (!pending_entry_refs_.empty())
4410 return;
4411
4412 // The pending entry may be deleted before the last PendingEntryRef.
4413 if (!pending_entry_)
4414 return;
4415
4416 // We usually clear the pending entry when the matching NavigationRequest
4417 // fails, so that an arbitrary URL isn't left visible above a committed page.
4418 //
4419 // However, we do preserve the pending entry in some cases, such as on the
4420 // initial navigation of an unmodified blank tab. We also allow the delegate
4421 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4422 // user edit the URL and try again. This may be useful in cases that the
4423 // committed page cannot be attacker-controlled. In these cases, we still
4424 // allow the view to clear the pending entry and typed URL if the user
4425 // requests (e.g., hitting Escape with focus in the address bar).
4426 //
4427 // Do not leave the pending entry visible if it has an invalid URL, since this
4428 // might be formatted in an unexpected or unsafe way.
4429 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364430 bool should_preserve_entry =
4431 (pending_entry_ == GetVisibleEntry()) &&
4432 pending_entry_->GetURL().is_valid() &&
4433 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4434 if (should_preserve_entry)
4435 return;
4436
4437 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374438 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364439}
4440
Titouan Rigoudy6ec70402021-02-02 15:42:194441std::unique_ptr<PolicyContainerPolicies>
4442NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394443 RenderFrameHostImpl* rfh,
4444 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174445 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394446 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454447 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394448 FrameNavigationEntry* previous_frame_entry =
4449 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4450
4451 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4452 // ensure we always have a FrameNavigationEntry here.
4453 if (!previous_frame_entry)
4454 return nullptr;
4455
Titouan Rigoudy6ec70402021-02-02 15:42:194456 const PolicyContainerPolicies* previous_policies =
4457 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394458
Titouan Rigoudy6ec70402021-02-02 15:42:194459 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394460 return nullptr;
4461
4462 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234463 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394464 }
4465
Titouan Rigoudy72f892d2022-05-02 18:21:234466 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394467}
4468
Hayato Ito2c8c08d02021-06-23 03:38:434469void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504470 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434471 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4472 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4473 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504474
4475 auto callback = base::BindRepeating(
4476 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4477 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4478 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4479 }
4480 },
Hayato Ito2c8c08d02021-06-23 03:38:434481 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034482 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504483}
4484
4485void NavigationControllerImpl::DidAccessInitialMainDocument() {
4486 // We may have left a failed browser-initiated navigation in the address bar
4487 // to let the user edit it and try again. Clear it now that content might
4488 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034489 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504490 DiscardPendingEntry(false);
4491
4492 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374493 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504494}
4495
4496void NavigationControllerImpl::UpdateStateForFrame(
4497 RenderFrameHostImpl* rfhi,
4498 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564499 OPTIONAL_TRACE_EVENT1("content",
4500 "NavigationControllerImpl::UpdateStateForFrame",
4501 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504502 // The state update affects the last NavigationEntry associated with the given
4503 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4504 // in the case of an UpdateState from a frame being swapped out). We track
4505 // which entry this is in the RenderFrameHost's nav_entry_id.
4506 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4507 if (!entry)
4508 return;
4509
4510 FrameNavigationEntry* frame_entry =
4511 entry->GetFrameEntry(rfhi->frame_tree_node());
4512 if (!frame_entry)
4513 return;
4514
4515 // The SiteInstance might not match if we do a cross-process navigation with
4516 // replacement (e.g., auto-subframe), in which case the swap out of the old
4517 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4518 // has already been replaced and destroyed.
4519 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4520 return;
4521
4522 if (page_state == frame_entry->page_state())
4523 return; // Nothing to update.
4524
4525 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4526
4527 // The document_sequence_number and item_sequence_number recorded in the
4528 // FrameNavigationEntry should not differ from the one coming with the update,
4529 // since it must come from the same document. Do not update it if a difference
4530 // is detected, as this indicates that |frame_entry| is not the correct one.
4531 blink::ExplodedPageState exploded_state;
4532 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4533 return;
4534
4535 if (exploded_state.top.document_sequence_number !=
4536 frame_entry->document_sequence_number() ||
4537 exploded_state.top.item_sequence_number !=
4538 frame_entry->item_sequence_number()) {
4539 return;
4540 }
4541
4542 frame_entry->SetPageState(page_state);
4543 NotifyEntryChanged(entry);
4544}
4545
Domenic Denicolacd30f5f82022-03-16 21:48:014546std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4547NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574548 Direction direction,
4549 int entry_index,
4550 const url::Origin& pending_origin,
4551 FrameTreeNode* node,
4552 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304553 int64_t pending_item_sequence_number,
4554 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014555 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454556 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174557 // Don't process the initial entry.
4558 DCHECK_EQ(GetEntryCount(), 1);
4559 return entries;
4560 }
Nate Chapind1fe3612021-04-16 20:45:574561 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304562 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574563 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4564 i += offset) {
4565 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414566 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574567 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014568 // An entry should only appear in the navigation API entries if it is for
4569 // the same origin as the document being committed. Check the committed
4570 // origin, or if that is not available (during restore), check against the
4571 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414572 url::Origin frame_entry_origin =
4573 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4574 frame_entry->url(),
4575 frame_entry->initiator_origin().value_or(url::Origin())));
4576 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574577 break;
4578 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4579 continue;
4580 blink::ExplodedPageState exploded_page_state;
4581 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4582 &exploded_page_state)) {
4583 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304584
4585 // If the document represented by this FNE hid its full url from appearing
4586 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014587 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304588 // document).
4589 std::u16string url;
4590 if (pending_document_sequence_number ==
4591 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574592 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304593 url = frame_state.url_string.value_or(std::u16string());
4594 }
4595
Domenic Denicolacd30f5f82022-03-16 21:48:014596 blink::mojom::NavigationApiHistoryEntryPtr entry =
4597 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574598 frame_state.navigation_api_key.value_or(std::u16string()),
4599 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094600 frame_state.item_sequence_number,
4601 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304602 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174603
Nate Chapin63db0d12022-01-20 22:03:304604 DCHECK(entry->url.empty() ||
4605 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574606 entries.push_back(std::move(entry));
4607 previous_item_sequence_number = frame_entry->item_sequence_number();
4608 }
4609 }
4610 // If |entries| was constructed by iterating backwards from
4611 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4612 // earliest-at-the-front. Reverse it.
4613 if (direction == Direction::kBack)
4614 std::reverse(entries.begin(), entries.end());
4615 return entries;
4616}
4617
Domenic Denicolacd30f5f82022-03-16 21:48:014618blink::mojom::NavigationApiHistoryEntryArraysPtr
4619NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554620 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574621 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404622 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444623 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404624 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574625
Nate Chapind1fe3612021-04-16 20:45:574626 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554627 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574628
Nate Chapine82339d02022-05-03 23:48:254629 // NOTE: |entry_index| is the index where this entry will commit if no
4630 // modifications are made between now and DidCommitNavigation. This is used to
4631 // walk |entries_| and determine which entries should be exposed by the
4632 // navigation API. It is important to calculate this correctly, because blink
4633 // will cancel a same-document history commit if it's not present in the
4634 // entries blink knows about.
4635 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574636 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304637 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254638 bool will_create_new_entry = false;
4639 if (GetPendingEntryIndex() != -1) {
4640 entry_index = GetPendingEntryIndex();
4641 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4642 pending_item_sequence_number = frame_entry->item_sequence_number();
4643 pending_document_sequence_number =
4644 frame_entry->document_sequence_number();
4645 }
4646 } else if (request &&
4647 !NavigationTypeUtils::IsReload(
4648 request->common_params().navigation_type) &&
4649 !NavigationTypeUtils::IsHistory(
4650 request->common_params().navigation_type) &&
4651 !request->common_params().should_replace_current_entry &&
4652 !request->common_params()
4653 .is_history_navigation_in_new_child_frame) {
4654 will_create_new_entry = true;
4655 entry_index = GetLastCommittedEntryIndex() + 1;
4656 // Don't set pending_item_sequence_number or
4657 // pending_document_sequence_number in this case - a new unique isn/dsn will
4658 // be calculated in the renderer later.
4659 } else if (GetLastCommittedEntryIndex() != -1) {
4660 entry_index = GetLastCommittedEntryIndex();
4661 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574662 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304663 pending_document_sequence_number =
4664 frame_entry->document_sequence_number();
4665 }
Nate Chapind1fe3612021-04-16 20:45:574666 }
4667
Domenic Denicolacd30f5f82022-03-16 21:48:014668 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254669 if (entry_index == -1) {
4670 // TODO(rakina): Exit early when there is no last committed entry.
4671 // Remove when InitialNavigationEntry ships.
4672 return entry_arrays;
4673 }
4674
Domenic Denicolacd30f5f82022-03-16 21:48:014675 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574676 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374677 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574678
4679 // Don't populate forward entries if they will be truncated by a new entry.
4680 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014681 entry_arrays->forward_entries =
4682 PopulateSingleNavigationApiHistoryEntryVector(
4683 Direction::kForward, entry_index, pending_origin, node,
4684 site_instance.get(), pending_item_sequence_number,
4685 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574686 }
Nate Chapin4e657a472022-02-06 03:38:374687 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574688}
4689
Nate Chapinfbfe5af2021-06-10 17:22:084690NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574691NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084692 FrameNavigationEntry* current_entry,
4693 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574694 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084695 if (!target_entry || !target_entry->committed_origin())
4696 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084697 if (!current_entry->committed_origin()->IsSameOriginWith(
4698 *target_entry->committed_origin())) {
4699 return HistoryNavigationAction::kStopLooking;
4700 }
4701
4702 // NOTE: We don't actually care between kSameDocument and
4703 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574704 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084705 return HistoryNavigationAction::kDifferentDocument;
4706 return HistoryNavigationAction::kKeepLooking;
4707}
4708
Domenic Denicolacc094fb2022-03-16 23:40:574709void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204710 RenderFrameHostImpl* initiator_rfh,
Yoav Weissa7449c3b2022-11-22 15:15:144711 absl::optional<blink::scheduler::TaskAttributionId>
4712 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574713 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204714 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084715 FrameNavigationEntry* current_entry =
4716 GetLastCommittedEntry()->GetFrameEntry(node);
4717 if (!current_entry)
4718 return;
4719
Yoav Weiss8c573952022-11-17 17:35:134720 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4721 // when `navigation.traverseTo()` is called.
4722
Nate Chapinfbfe5af2021-06-10 17:22:084723 // We want to find the nearest matching entry that is contiguously
4724 // same-instance and same-origin. Check back first, then forward.
4725 // TODO(japhet): Link spec here once it exists.
4726 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574727 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084728 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4729 if (result == HistoryNavigationAction::kStopLooking)
4730 break;
4731 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144732 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084733 return;
4734 }
4735 }
4736 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574737 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084738 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4739 if (result == HistoryNavigationAction::kStopLooking)
4740 break;
4741 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144742 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084743 return;
4744 }
4745 }
Nate Chapinbf682fa32022-09-26 22:41:204746
4747 // If we fall through to here, a matching NavigationEntry couldn't be found.
4748 // Notify the renderer that the navigation was cancelled.
4749 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4750 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084751}
4752
Domenic Denicolacc094fb2022-03-16 23:40:574753bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304754 network::mojom::ReferrerPolicy referrer_policy) {
4755 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4756 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4757}
4758
shivanigithubf405bf0d2021-11-05 17:58:334759bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4760 const FrameTreeNode* frame_tree_node) const {
4761 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4762 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544763 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Ali Hijazid87307d2022-11-07 20:15:034764 return frame_tree_->is_prerendering() ||
shivanigithubf405bf0d2021-11-05 17:58:334765 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544766}
4767
Julie Jeongeun Kim0e242242022-11-30 10:45:094768void NavigationControllerImpl::DidChangeReferrerPolicy(
4769 FrameTreeNode* node,
4770 network::mojom::ReferrerPolicy referrer_policy) {
4771 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4772 if (!entry)
4773 return;
4774
4775 // The FrameNavigationEntry may want to change whether to protect its url
4776 // in the navigation API when the referrer policy changes.
4777 entry->set_protect_url_in_navigation_api(
4778 ShouldProtectUrlInNavigationApi(referrer_policy));
4779}
4780
[email protected]8ff00d72012-10-23 19:12:214781} // namespace content