blob: e86ff0abc499f56944e5af1a8f12d5e586719292 [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) {
Rakina Zata Amnid605d462022-06-01 10:17:031153 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
sunjian30574a62017-03-21 21:39:441154 TRACE_EVENT0("browser,navigation,benchmark",
1155 "NavigationControllerImpl::GoToIndex");
[email protected]765b35502008-08-21 00:51:201156 if (index < 0 || index >= static_cast<int>(entries_.size())) {
Rakina Zata Amni4595c36a2023-02-01 03:51:181157 // We've seen reports of this NOTREACHED being hit on Android WebView, where
1158 // we won't get the log message below. The following code ensures that
1159 // `index` and `entries_size` will show up on the minidump for that case.
1160 base::debug::Alias(&index);
1161 const size_t entries_size = entries_.size();
1162 base::debug::Alias(&entries_size);
1163 NOTREACHED() << "Index " << index
1164 << " is out of bounds, entries_.size() is " << entries_size;
[email protected]765b35502008-08-21 00:51:201165 return;
1166 }
1167
Rakina Zata Amnif297a802022-01-18 03:53:431168 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1169 // We should never navigate to an existing initial NavigationEntry that is
1170 // the initial NavigationEntry for the initial empty document that hasn't
1171 // been overridden by the synchronous about:blank commit, to preserve
1172 // legacy behavior where trying to reload when the main frame is on the
1173 // initial empty document won't result in a navigation. See also
1174 // https://crbug.com/1277414.
1175 return;
1176 }
1177
[email protected]cbab76d2008-10-13 22:42:471178 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201179
arthursonzogni5c4c202d2017-04-25 23:41:271180 DCHECK_EQ(nullptr, pending_entry_);
1181 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431182
arthursonzogni5c4c202d2017-04-25 23:41:271183 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201184 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271185 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1186 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201187 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131188 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201189 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201190}
1191
[email protected]d202a7c2012-01-04 07:53:471192void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121193 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031194 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201195 return;
1196
[email protected]9ba14052012-06-22 23:50:031197 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201198}
1199
Nate Chapinbf682fa32022-09-26 22:41:201200void NavigationControllerImpl::GoToOffsetFromRenderer(
1201 int offset,
Yoav Weiss8c573952022-11-17 17:35:131202 RenderFrameHostImpl* initiator_rfh,
1203 absl::optional<blink::scheduler::TaskAttributionId>
1204 soft_navigation_heuristics_task_id) {
Nate Chapin758e5e482023-05-02 00:22:551205 // If the renderer sent an out-of-bounds offset, cancel and notify the
1206 // renderer.
1207 if (!CanGoToOffset(offset)) {
1208 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
1209 /*navigation_api_key=*/std::string(),
1210 blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapin45f620582021-09-30 17:45:431211 return;
Nate Chapin758e5e482023-05-02 00:22:551212 }
Nate Chapin45f620582021-09-30 17:45:431213
Nate Chapinbf682fa32022-09-26 22:41:201214 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131215 soft_navigation_heuristics_task_id,
1216 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431217}
1218
Xiaohan Wang7f8052e02022-01-14 18:44:281219#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151220void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1221 // Note: This is actually reached in unit tests.
1222 if (!CanGoToOffsetWithSkipping(offset))
1223 return;
1224
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421225 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151226 GoToIndex(GetIndexForOffset(offset));
1227 return;
1228 }
1229 int increment = offset > 0 ? 1 : -1;
1230 // Find the offset without counting skippable entries.
1231 int target_index = GetIndexForOffset(increment);
1232 int non_skippable_entries = 0;
1233 for (int index = target_index; index >= 0 && index < GetEntryCount();
1234 index += increment) {
1235 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1236 non_skippable_entries++;
1237
1238 if (non_skippable_entries == std::abs(offset)) {
1239 target_index = index;
1240 break;
1241 }
1242 }
1243
1244 GoToIndex(target_index);
1245}
1246#endif
1247
[email protected]41374f12013-07-24 02:49:281248bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151249 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281250 return false;
[email protected]6a13a6c2011-12-20 21:47:121251
[email protected]43032342011-03-21 14:10:311252 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281253 return true;
[email protected]cbab76d2008-10-13 22:42:471254}
1255
Michael Thiessen9b14d512019-09-23 21:19:471256void NavigationControllerImpl::PruneForwardEntries() {
1257 DiscardNonCommittedEntries();
1258 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471259 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471260 if (num_removed <= 0)
1261 return;
Nate Chapin9eb16be72022-09-23 22:54:311262 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471263 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1264 NotifyPrunedEntries(this, remove_start_index /* start index */,
1265 num_removed /* count */);
1266}
1267
Aran Gilman37d11632019-10-08 23:07:151268void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1269 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321270 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311271 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511272 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1273 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321274 }
1275}
1276
Harkiran Bolariaba823e42021-05-21 18:30:361277base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1278 const GURL& url,
1279 const Referrer& referrer,
1280 ui::PageTransition transition,
1281 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471282 LoadURLParams params(url);
1283 params.referrer = referrer;
1284 params.transition_type = transition;
1285 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361286 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471287}
1288
Harkiran Bolariaba823e42021-05-21 18:30:361289base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1290 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061291 if (params.is_renderer_initiated)
1292 DCHECK(params.initiator_origin.has_value());
1293
naskob8744d22014-08-28 17:07:431294 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151295 "NavigationControllerImpl::LoadURLWithParams", "url",
1296 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291297 bool is_explicit_navigation =
1298 GetContentClient()->browser()->IsExplicitNavigation(
1299 params.transition_type);
1300 if (HandleDebugURL(params.url, params.transition_type,
1301 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431302 // If Telemetry is running, allow the URL load to proceed as if it's
1303 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491304 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431305 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361306 return nullptr;
[email protected]47752982014-07-29 08:01:431307 }
[email protected]8bf1048012012-02-08 01:22:181308
[email protected]cf002332012-08-14 19:17:471309 // Checks based on params.load_type.
1310 switch (params.load_type) {
1311 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431312 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471313 break;
1314 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261315 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471316 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361317 return nullptr;
[email protected]cf002332012-08-14 19:17:471318 }
1319 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461320 }
[email protected]e47ae9472011-10-13 19:48:341321
[email protected]e47ae9472011-10-13 19:48:341322 // The user initiated a load, we don't need to reload anymore.
1323 needs_reload_ = false;
1324
Harkiran Bolariaba823e42021-05-21 18:30:361325 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441326}
1327
Mohamed Abdelhalim833de902019-09-16 17:41:451328bool NavigationControllerImpl::PendingEntryMatchesRequest(
1329 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191330 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451331 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191332}
1333
[email protected]d202a7c2012-01-04 07:53:471334bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321335 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071336 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331337 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441338 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251339 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471340 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131341 NavigationRequest* navigation_request) {
1342 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331343
1344 // Note: validation checks and renderer kills due to invalid commit messages
1345 // must happen before getting here, in
1346 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1347 // effects of the navigation have already occurred.
1348
[email protected]cd2e15742013-03-08 04:08:311349 is_initial_navigation_ = false;
1350
Wang Hui96ab1012022-10-11 02:05:491351 // Any pending request to repost a form submission is no longer valid, since a
1352 // different NavigationEntry is committing.
1353 pending_reload_ = ReloadType::NONE;
1354
[email protected]0e8db942008-09-24 21:21:481355 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431356 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451357 if (entry_replaced_by_post_commit_error_) {
1358 // Same document navigation events with a post-commit error should already
1359 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1360 // reaching here.
1361 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331362
Rakina Zata Amnie2d31312022-11-18 03:38:451363 // Any commit while a post-commit error page is showing should put the
1364 // original entry back, replacing the error page's entry. This includes
1365 // reloads, where the original entry was used as the pending entry and
1366 // should now be at the correct index at commit time.
1367 entries_[last_committed_entry_index_] =
1368 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481369 }
Rakina Zata Amnie2d31312022-11-18 03:38:451370 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1371 details->previous_entry_index = GetLastCommittedEntryIndex();
1372 if (PendingEntryMatchesRequest(navigation_request) &&
1373 pending_entry_->GetIsOverridingUserAgent() !=
1374 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1375 overriding_user_agent_changed = true;
1376 }
1377#if BUILDFLAG(IS_ANDROID)
1378 // TODO(crbug.com/1266277): Clean up the logic of setting
1379 // |overriding_user_agent_changed| post-launch.
1380 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1381 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
1382 // Must honor user agent overrides in the |navigation_request|, such as
1383 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1384 // result, besides comparing |pending_entry_|'s user agent against
1385 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1386 // agent against LastCommittedEntry's.
1387 if (navigation_request->is_overriding_user_agent() !=
1388 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1389 overriding_user_agent_changed = true;
1390 }
1391 }
1392#endif // BUILDFLAG(IS_ANDROID)
[email protected]ecd9d8702008-08-28 22:10:171393
Dave Tapuskaa2ab4f252021-07-08 21:31:281394 bool is_main_frame_navigation = !rfh->GetParent();
1395
Alexander Timind2f2e4f22019-04-02 20:04:531396 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1397 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281398 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141399 // BackForwardCacheMetrics to be associated with the new navigation's
1400 // NavigationEntry, by either creating a new object or reusing the previous
1401 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281402 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Arthur Sonzognif6785ec2022-12-05 10:11:501403 if (navigation_request->frame_tree_node()->frame_tree().type() ==
Dave Tapuskaa2ab4f252021-07-08 21:31:281404 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141405 back_forward_cache_metrics = BackForwardCacheMetrics::
1406 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281407 GetLastCommittedEntry(), is_main_frame_navigation,
1408 params.document_sequence_number);
1409 }
Yuzu Saijo29f96ca92022-12-08 04:54:121410
Alexander Timind2f2e4f22019-04-02 20:04:531411 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281412 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451413 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1414 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531415 }
1416 }
1417
Rakina Zata Amnifd8370b2022-11-14 13:32:251418 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1419 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091420 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251421 details->did_replace_entry =
1422 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091423
fdegans9caf66a2015-07-30 21:10:421424 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111425 // except for restored entries. This should be true even if the current commit
1426 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291427 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481428 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081429 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111430
1431 // Only make changes based on the pending entry if the NavigationRequest
1432 // matches it. Otherwise, the pending entry may be for a different request
1433 // (e.g., if a slow history navigation is pending while an auto-subframe
1434 // commit occurs).
1435 if (PendingEntryMatchesRequest(navigation_request)) {
1436 // It is no longer necessary to consider the pending entry as restored.
1437 if (pending_entry_->IsRestored()) {
1438 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1439 was_restored = true;
1440 }
[email protected]e9ba4472008-09-14 15:42:431441
Charlie Reisf8cde712022-10-20 16:25:091442 // If the SiteInstance has changed from the matching pending entry, this
1443 // must be treated as a new navigation with replacement. Set the replacement
1444 // bit here and ClassifyNavigation will identify this case and return
1445 // NEW_ENTRY.
1446 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1447 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1448 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251449 // TODO(nasko,creis,rakina): Move this to happen before committing the
1450 // navigation. This is a bit complicated because we don't currently
1451 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091452 details->did_replace_entry = true;
1453 }
Nasko Oskovaee2f862018-06-15 00:05:521454 }
[email protected]bcd904482012-02-01 01:54:221455
[email protected]e9ba4472008-09-14 15:42:431456 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101457 NavigationType navigation_type =
1458 ClassifyNavigation(rfh, params, navigation_request);
1459 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451460
Rakina Zata Amnie2d31312022-11-18 03:38:451461 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451462 // Ensure that this navigation does not add a navigation entry, since
1463 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1464 // beyond the last committed one. Therefore, `should_replace_current_entry`
1465 // should be set, which replaces the current entry, or this should be a
1466 // reload, which does not create a new entry.
1467 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1468 // navigation that is restored will not be creating a new entry anyways, so
1469 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1470 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1471 // pointed out in the issue.
Rakina Zata Amnifd8370b2022-11-14 13:32:251472 DCHECK(navigation_request->common_params().should_replace_current_entry ||
shivanigithub189833f2022-04-27 18:08:451473 navigation_request->GetReloadType() != ReloadType::NONE ||
Miyoung Shin3299cbf2022-11-22 01:41:101474 navigation_type == NAVIGATION_TYPE_AUTO_SUBFRAME);
shivanigithub189833f2022-04-27 18:08:451475 }
1476
Rakina Zata Amnie2d31312022-11-18 03:38:451477 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551478 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241479 // This is a subframe navigation on the initial empty document, which used
1480 // to not have a NavigationEntry to attach to. Now it can attach to the
1481 // initial NavigationEntry, and we must ensure that its NavigationEntry
1482 // will keep the "initial NavigationEntry" status and won't append a new
1483 // NavigationEntry (it should always do replacement instead).
1484 // See also https://crbug.com/1277414.
1485 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551486 // Subframe navigation on initial NavigationEntry must not append a new
1487 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1488 // means every subframe navigation that happens while we're on the initial
1489 // NavigationEntry will always reuse the existing NavigationEntry and
1490 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101491 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1492 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551493 // This is a navigation that modifies the initial NavigationEntry, either
1494 // for a replacement or a reload. The initial NavigationEntry should
1495 // retain its "initial NavigationEntry" status in this case.
1496 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241497 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251498 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1499 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241500 // This is a synchronous about:blank navigation on the main frame, which
1501 // used to not create a NavigationEntry when we have no NavigationEntry on
1502 // FrameTree creation. We now have the initial NavigationEntry and are on
1503 // the initial NavigationEntry. To preserve old behavior, we should still
1504 // keep the "initial" status for the new NavigationEntry that we will
1505 // create for this navigation, so that subframe navigations under the
1506 // synchronously committed about:blank document will never append new
1507 // NavigationEntry, and instead will just reuse the initial
1508 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1509 // See also https://crbug.com/1277414.
1510 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551511 }
1512 }
1513 DCHECK(!details->should_stay_as_initial_entry ||
1514 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201515
eugenebutee08663a2017-04-27 17:43:121516 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441517 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121518
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071519 details->is_prerender_activation =
1520 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241521 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1522 ->GetOutermostMainFrame()
1523 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071524
Peter Boströmd7592132019-01-30 04:50:311525 // Make sure we do not discard the pending entry for a different ongoing
1526 // navigation when a same document commit comes in unexpectedly from the
1527 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1528 // other navigation types. See https://crbug.com/900036.
1529 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061530 bool keep_pending_entry =
1531 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101532 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061533 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311534
Miyoung Shin3299cbf2022-11-22 01:41:101535 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061536 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491537 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051538 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001539 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431540 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061541 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491542 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1543 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001544 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431545 break;
[email protected]8ff00d72012-10-23 19:12:211546 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471547 RendererDidNavigateNewSubframe(
1548 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001549 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431550 break;
[email protected]8ff00d72012-10-23 19:12:211551 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391552 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251553 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001554 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081555 // We don't send a notification about auto-subframe PageState during
1556 // UpdateStateForFrame, since it looks like nothing has changed. Send
1557 // it here at commit time instead.
1558 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431559 return false;
creis59d5a47cb2016-08-24 23:57:191560 }
[email protected]e9ba4472008-09-14 15:42:431561 break;
Aran Gilman37d11632019-10-08 23:07:151562 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431563 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151564 break;
[email protected]765b35502008-08-21 00:51:201565 }
1566
[email protected]688aa65c62012-09-28 04:32:221567 // At this point, we know that the navigation has just completed, so
1568 // record the time.
1569 //
1570 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261571 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331572 base::Time timestamp =
1573 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1574 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131575 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221576
Peter Boströmd7592132019-01-30 04:50:311577 // If we aren't keeping the pending entry, there shouldn't be one at this
1578 // point. Clear it again in case any error cases above forgot to do so.
1579 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1580 // been cleared instead of protecting against it.
1581 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551582 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141583
[email protected]e9ba4472008-09-14 15:42:431584 // All committed entries should have nonempty content state so WebKit doesn't
1585 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471586 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321587 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221588 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441589 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141590
Alexander Timind2f2e4f22019-04-02 20:04:531591 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1592 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281593 if (back_forward_cache_metrics &&
1594 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531595 active_entry->set_back_forward_cache_metrics(
1596 std::move(back_forward_cache_metrics));
1597 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281598
1599 // `back_forward_cache_metrics()` may return null as we do not record
1600 // back-forward cache metrics for navigations in non-primary frame trees.
1601 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141602 // TODO(https://crbug.com/1338089): Remove this.
1603 // These are both only available from details at this point, so we capture
1604 // them here.
1605 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101606 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141607 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1608 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281609 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1610 navigation_request,
1611 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1612 }
naskoc7533512016-05-06 17:01:121613
Charles Reisc0507202017-09-21 00:40:021614 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1615 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1616 // A mismatch can occur if the renderer lies or due to a unique name collision
1617 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121618 FrameNavigationEntry* frame_entry =
1619 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021620 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1621 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031622 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081623 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1624 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031625 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201626
1627 // Remember the bindings the renderer process has at this point, so that
1628 // we do not grant this entry additional bindings if we come back to it.
1629 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301630 }
[email protected]132e281a2012-07-31 18:32:441631
[email protected]97d8f0d2013-10-29 16:49:211632 // Once it is committed, we no longer need to track several pieces of state on
1633 // the entry.
naskoc7533512016-05-06 17:01:121634 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131635
[email protected]49bd30e62011-03-22 20:12:591636 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221637 // TODO(creis): This check won't pass for subframes until we create entries
1638 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001639 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421640 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591641
[email protected]e9ba4472008-09-14 15:42:431642 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001643 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001644 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311645 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531646
arthursonzogni7ddc6542021-04-09 09:16:501647 active_entry->SetIsOverridingUserAgent(
1648 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031649
[email protected]93f230e02011-06-01 14:40:001650 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291651
aelias100c9192017-01-13 00:01:431652 if (overriding_user_agent_changed)
1653 delegate_->UpdateOverridingUserAgent();
1654
creis03b48002015-11-04 00:54:561655 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1656 // one knows the latest NavigationEntry it is showing (whether it has
1657 // committed anything in this navigation or not). This allows things like
1658 // state and title updates from RenderFrames to apply to the latest relevant
1659 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381660 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031661 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381662 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431663
1664 if (navigation_request->IsPrerenderedPageActivation()) {
1665 BroadcastHistoryOffsetAndLength();
1666 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1667 // is activated. As a result, a "prerenderingchange" event listener sees the
1668 // history.length which is not updated yet. We should guarantee that
1669 // history's length and offset should be updated before a
1670 // "prerenderingchange" event listener runs. One possible approach is to use
1671 // the same IPC which "prerenderingchange" uses, and propagate history's
1672 // length and offset together with that.
1673 }
1674
[email protected]e9ba4472008-09-14 15:42:431675 return true;
initial.commit09911bf2008-07-26 23:55:291676}
1677
[email protected]8ff00d72012-10-23 19:12:211678NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321679 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101680 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241681 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591682 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511683 "ClassifyNavigation");
1684
avi7c6f35e2015-05-08 17:52:381685 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241686 // A new entry. We may or may not have a corresponding pending entry, and
1687 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001688 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491689 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061690 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381691 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241692 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511693 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381694 return NAVIGATION_TYPE_NEW_SUBFRAME;
1695 }
1696
Charlie Reisc0f17d2d2021-01-12 18:52:491697 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381698 DCHECK(!params.history_list_was_cleared);
1699
avi39c1edd32015-06-04 20:06:001700 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381701 // All manual subframes would be did_create_new_entry and handled above, so
1702 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081703 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1704 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381705 }
1706
Rakina Zata Amnif6950d552020-11-24 03:26:101707 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1708 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381709 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1710 // create a new page.
1711
Hayato Ito2ae49442021-07-02 02:59:251712 // This main frame navigation is not a history navigation (since
1713 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1714 // reload or a replacement navigation, which will modify the existing entry.
1715 //
Nasko Oskov332593c2018-08-16 17:21:341716 // TODO(nasko): With error page isolation, reloading an existing session
1717 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491718 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341719 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511720 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491721 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061722 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381723 }
1724
Charlie Reisf8cde712022-10-20 16:25:091725 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521726 // If the SiteInstance of the |pending_entry_| does not match the
1727 // SiteInstance that got committed, treat this as a new navigation with
1728 // replacement. This can happen if back/forward/reload encounters a server
1729 // redirect to a different site or an isolated error page gets successfully
1730 // reloaded into a different SiteInstance.
1731 if (pending_entry_->site_instance() &&
1732 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491733 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061734 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521735 }
creis77c9aa32015-09-25 19:59:421736
Nasko Oskovaee2f862018-06-15 00:05:521737 if (pending_entry_index_ == -1) {
1738 // In this case, we have a pending entry for a load of a new URL but Blink
1739 // didn't do a new navigation (params.did_create_new_entry). First check
1740 // to make sure Blink didn't treat a new cross-process navigation as
1741 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161742 // we must treat it as NEW rather than the converted reload case below,
1743 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451744 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161745 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061746 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521747 }
1748
1749 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161750 // We will create a pending entry, but NavigateWithoutEntry will convert
1751 // it to a reload since it's the same page and not create a new entry for
1752 // it. (The user doesn't want to have a new back/forward entry when they
1753 // do this.) Therefore we want to just ignore the pending entry and go
1754 // back to where we were (the "existing entry").
1755 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061756 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521757 }
avi7c6f35e2015-05-08 17:52:381758 }
1759
Rakina Zata Amni153d5702021-09-13 22:48:001760 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381761 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491762 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1763 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161764 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061765 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381766 }
1767
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121768 if (navigation_request->DidEncounterError() &&
1769 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101770 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381771 // If the renderer was going to a new pending entry that got cleared because
1772 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491773 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381774 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511775 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491776 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061777 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381778 }
1779
Charlie Reisc0f17d2d2021-01-12 18:52:491780 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101781 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511782 trace_return.traced_value()->SetInteger("existing_entry_index",
1783 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381784 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441785 // The renderer has committed a navigation to an entry that no longer
1786 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491787 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061788 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381789 }
1790
avi7c6f35e2015-05-08 17:52:381791 // Since we weeded out "new" navigations above, we know this is an existing
1792 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491793 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061794 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381795}
1796
Rakina Zata Amni3460d382021-10-29 00:43:371797void NavigationControllerImpl::UpdateNavigationEntryDetails(
1798 NavigationEntryImpl* entry,
1799 RenderFrameHostImpl* rfh,
1800 const mojom::DidCommitProvisionalLoadParams& params,
1801 NavigationRequest* request,
1802 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001803 bool is_new_entry,
1804 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371805 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171806 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371807 entry->AddOrUpdateFrameEntry(
1808 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571809 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371810 rfh->GetSiteInstance(), nullptr, params.url,
1811 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171812 Referrer(*params.referrer),
1813 request ? request->common_params().initiator_origin : params.origin,
W. James MacLean23e90a12022-12-21 04:38:211814 request ? request->common_params().initiator_base_url : absl::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171815 request ? request->GetRedirectChain() : redirects, params.page_state,
1816 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371817 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171818 rfh, request && request->IsSameDocument(),
1819 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371820
1821 if (rfh->GetParent()) {
1822 // Only modify the NavigationEntry for main frame navigations.
1823 return;
1824 }
1825 if (entry->update_virtual_url_with_url())
1826 UpdateVirtualURLToURL(entry, params.url);
1827 // Don't use the page type from the pending entry. Some interstitial page
1828 // may have set the type to interstitial. Once we commit, however, the page
1829 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171830 entry->set_page_type((request && request->DidEncounterError())
1831 ? PAGE_TYPE_ERROR
1832 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431833 if (commit_details && commit_details->should_stay_as_initial_entry) {
1834 // Retain the "initial NavigationEntry" status.
1835 if (request->IsSameDocument()) {
1836 // If this is for a same-document navigation, the NavigationEntry must be
1837 // reused and should already be marked as the initial NavigationEntry.
1838 DCHECK(entry->IsInitialEntry());
1839 } else {
1840 // If this is for a cross-document navigation, it can be caused by a
1841 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1842 // "for synchronous about:blank" in the latter case, and also when it is
1843 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1844 // is not for a synchronous about:blank commit.
1845 NavigationEntryImpl::InitialNavigationEntryState new_state =
1846 NavigationEntryImpl::InitialNavigationEntryState::
1847 kInitialNotForSynchronousAboutBlank;
1848 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1849 request->is_synchronous_renderer_commit()) {
1850 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1851 kInitialForSynchronousAboutBlank;
1852 }
1853 entry->set_initial_navigation_entry_state(new_state);
1854 }
1855 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1856 // Remove the "initial NavigationEntry" status.
1857 entry->set_initial_navigation_entry_state(
1858 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001859 }
Rakina Zata Amniddf10502022-01-15 02:56:551860
Rakina Zata Amni3460d382021-10-29 00:43:371861 if (is_new_entry) {
1862 // Some properties of the NavigationEntry are only set when the entry is
1863 // new (we aren't reusing it).
1864 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171865 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1866 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371867 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1868 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1869 } else {
1870 // We are reusing the NavigationEntry. The site instance will normally be
1871 // the same except for a few cases:
1872 // 1) session restore, when no site instance will be assigned or
1873 // 2) redirect, when the site instance is reset.
1874 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1875 entry->site_instance() == rfh->GetSiteInstance());
1876 }
1877}
1878
Rakina Zata Amniafd3c6582021-11-30 06:19:171879void NavigationControllerImpl::CreateInitialEntry() {
1880 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031881 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171882 auto params = mojom::DidCommitProvisionalLoadParams::New();
1883 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1884 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1885 // before we have initial NavigationEntries.
1886 params->url = GURL::EmptyGURL();
1887 params->http_status_code = 0;
1888 params->url_is_unreachable = false;
1889 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171890 params->post_id = -1;
1891 params->embedding_token = base::UnguessableToken::Create();
1892 params->navigation_token = base::UnguessableToken::Create();
1893 params->did_create_new_entry = true;
1894 params->origin = rfh->GetLastCommittedOrigin();
1895 params->should_update_history = true;
1896 params->item_sequence_number = 0;
1897 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151898 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171899 params->transition = is_in_fenced_frame_tree
1900 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1901 : ui::PAGE_TRANSITION_LINK;
1902 params->referrer = blink::mojom::Referrer::New();
1903
Rakina Zata Amniafd3c6582021-11-30 06:19:171904 auto new_entry = std::make_unique<NavigationEntryImpl>(
1905 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381906 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211907 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1908 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1909 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171910 UpdateNavigationEntryDetails(
1911 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001912 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1913 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171914
1915 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1916 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001917 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171918}
1919
Charlie Reisc0f17d2d2021-01-12 18:52:491920void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321921 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071922 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361923 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441924 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471925 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001926 NavigationRequest* request,
1927 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571928 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071929 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451930 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:521931 absl::optional<GURL> initiator_base_url;
1932 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
1933 initiator_base_url = request->common_params().initiator_base_url;
1934 }
Lukasz Anforowicz435bcb582019-07-12 20:50:061935
creisf49dfc92016-07-26 17:05:181936 // First check if this is an in-page navigation. If so, clone the current
1937 // entry instead of looking at the pending entry, because the pending entry
1938 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451939 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301940 FrameNavigationEntry* previous_frame_entry =
1941 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451942 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481943 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571944 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:081945 rfh->GetSiteInstance(), nullptr, params.url,
1946 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:211947 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:091948 request->GetRedirectChain(), params.page_state, params.method,
1949 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:391950 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301951 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:571952 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:301953 // FrameNavigationEntry.
1954 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:571955 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:031956
creisf49dfc92016-07-26 17:05:181957 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:031958 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:521959 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1960 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571961 // TODO(jam): we had one report of this with a URL that was redirecting to
1962 // only tildes. Until we understand that better, don't copy the cert in
1963 // this case.
1964 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571965 }
creisf49dfc92016-07-26 17:05:181966
Patrick Monette50e8bd82019-06-13 22:40:451967 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1968 // that |frame_entry| should now have a reference count of exactly 2: one
1969 // due to the local variable |frame_entry|, and another due to |new_entry|
1970 // also retaining one. This should never fail, because it's the main frame.
1971 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181972 }
1973
Harkiran Bolaria59290d62021-03-17 01:53:011974 // If this is an activation navigation from a prerendered page, transfer the
1975 // new entry from an entry already created and stored in the
1976 // NavigationRequest. |new_entry| will not have been set prior to this as
1977 // |is_same_document| is mutually exclusive with
1978 // |IsPrerenderedPageActivation|.
1979 if (request->IsPrerenderedPageActivation()) {
1980 DCHECK(!is_same_document);
1981 DCHECK(!new_entry);
1982 new_entry = request->TakePrerenderNavigationEntry();
1983 DCHECK(new_entry);
1984 }
1985
Charlie Reisc0f17d2d2021-01-12 18:52:491986 // Only make a copy of the pending entry if it is appropriate for the new
1987 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451988 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041989 // 1. The SiteInstance hasn't been assigned to something else.
1990 // 2. The pending entry was intended as a new entry, rather than being a
1991 // history navigation that was interrupted by an unrelated,
1992 // renderer-initiated navigation.
1993 // TODO(csharrison): Investigate whether we can remove some of the coarser
1994 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451995 if (!new_entry && PendingEntryMatchesRequest(request) &&
1996 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:341997 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:431998 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:351999 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432000
Camille Lamy62b826012019-02-26 09:15:472001 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452002 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182003 }
2004
Charlie Reisc0f17d2d2021-01-12 18:52:492005 // For cross-document commits with no matching pending entry, create a new
2006 // entry.
creisf49dfc92016-07-26 17:05:182007 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062008 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072009 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212010 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582011 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452012 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172013 nullptr, // blob_url_loader_factory
2014 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242015
2016 // Find out whether the new entry needs to update its virtual URL on URL
2017 // change and set up the entry accordingly. This is needed to correctly
2018 // update the virtual URL when replaceState is called after a pushState.
2019 GURL url = params.url;
2020 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492021 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412022 // update the virtual URL based on the new URL. For example, this is needed
2023 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2024 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372025 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2026 &url, browser_context_, &needs_update);
2027 new_entry->set_update_virtual_url_with_url(needs_update);
2028
Camille Lamy62b826012019-02-26 09:15:472029 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452030 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432031 }
2032
Harkiran Bolaria59290d62021-03-17 01:53:012033 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
2034 // for prerendered contents, if any. This is because prerendering/activation
2035 // technically won't be creating a new document. Unlike BFCache, prerendering
2036 // creates a new NavigationEntry rather than using an existing one.
2037 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372038 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2039 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002040 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082041
Harkiran Bolaria59290d62021-03-17 01:53:012042 // history.pushState() is classified as a navigation to a new page, but sets
2043 // is_same_document to true. In this case, we already have the title and
2044 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452045 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012046 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2047 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2048 }
[email protected]3a868f212014-08-09 10:41:192049 }
[email protected]ff64b3e2014-05-31 04:07:332050
[email protected]60d6cca2013-04-30 08:47:132051 DCHECK(!params.history_list_was_cleared || !replace_entry);
2052 // The browser requested to clear the session history when it initiated the
2053 // navigation. Now we know that the renderer has updated its state accordingly
2054 // and it is safe to also clear the browser side history.
2055 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552056 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132057 entries_.clear();
2058 last_committed_entry_index_ = -1;
2059 }
2060
Nasko Oskovaee2f862018-06-15 00:05:522061 // If this is a new navigation with replacement and there is a
2062 // pending_entry_ which matches the navigation reported by the renderer
2063 // process, then it should be the one replaced, so update the
2064 // last_committed_entry_index_ to use it.
2065 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092066 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522067 last_committed_entry_index_ = pending_entry_index_;
2068 }
2069
Alexander Timine3ec4192020-04-20 16:39:402070 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412071 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402072 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052073
Yuzu Saijoa725585f2022-11-28 04:14:032074 // If this is a history navigation and the old entry has an existing
2075 // back/forward cache metrics object, keep using the old one so that the
2076 // reasons logged from the last time the page navigated gets preserved.
2077 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2078 request)) {
2079 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2080 // because some tests do not have a pending entry.
2081 NavigationEntryImpl* entry =
2082 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2083 if (entry && entry->back_forward_cache_metrics()) {
2084 scoped_refptr<BackForwardCacheMetrics> metrics =
2085 entry->TakeBackForwardCacheMetrics();
2086 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2087 }
2088 }
2089
Carlos IL42b416592019-10-07 23:10:362090 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312091 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152092 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432093}
2094
Charlie Reisc0f17d2d2021-01-12 18:52:492095void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322096 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072097 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362098 bool is_same_document,
jam48cea9082017-02-15 06:13:292099 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452100 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002101 bool keep_pending_entry,
2102 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562103 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2104 << "that a last committed entry exists.";
2105
[email protected]e9ba4472008-09-14 15:42:432106 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002107 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432108
Charlie Reis7e2cb6d2021-01-26 01:27:162109 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002110 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162111 // We're guaranteed to have a last committed entry if intended_as_new_entry
2112 // is true.
avicbdc4c12015-07-01 16:07:112113 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162114
2115 // If the NavigationRequest matches a new pending entry and is classified as
2116 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2117 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092118 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162119 // Note: The pending entry will usually have a real ReloadType here, but
2120 // it can still be ReloadType::NONE in cases that
2121 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2122
2123 // If we classified this correctly, the SiteInstance should not have
2124 // changed.
2125 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2126
2127 // For converted reloads, we assign the entry's unique ID to be that of
2128 // the new one. Since this is always the result of a user action, we want
2129 // to dismiss infobars, etc. like a regular user-initiated navigation.
2130 entry->set_unique_id(pending_entry_->GetUniqueID());
2131
2132 // The extra headers may have changed due to reloading with different
2133 // headers.
2134 entry->set_extra_headers(pending_entry_->extra_headers());
2135 }
2136 // Otherwise, this was intended as a new entry but the pending entry was
2137 // lost in the meantime and no new entry was created. We are stuck at the
2138 // last committed entry.
2139
2140 // Even if this is a converted reload from pressing enter in the omnibox,
2141 // the server could redirect, requiring an update to the SSL status. If this
2142 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452143 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162144 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472145 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452146 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162147 }
Rakina Zata Amnif6950d552020-11-24 03:26:102148 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112149 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102150 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162151
eugenebut604866f2017-05-10 21:35:362152 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452153 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362154 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2155 // this was a restored same document navigation entry, then it won't have
2156 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2157 // navigated it.
jam48cea9082017-02-15 06:13:292158 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522159 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2160 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292161 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2162 was_restored) {
2163 entry->GetSSL() = last_entry->GetSSL();
2164 }
2165 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452166 // In rapid back/forward navigations |request| sometimes won't have a cert
2167 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192168 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452169 if (request->GetSSLInfo().has_value() &&
2170 request->GetSSLInfo()->is_valid()) {
2171 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522172 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2173 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192174 entry->GetSSL() = SSLStatus();
2175 }
jam48cea9082017-02-15 06:13:292176 }
avicbdc4c12015-07-01 16:07:112177 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272178 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572179 // navigations that are EXISTING_ENTRY are same-document navigations that
2180 // result in replacement (e.g. history.replaceState(), location.replace(),
2181 // forced replacements for trivial session history contexts). For these
2182 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112183 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102184
Mikel Astizba9cf2fd2017-12-17 10:38:102185 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2186 // to avoid misleading interpretations (e.g. URLs paired with
2187 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2188 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2189 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2190
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572191 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102192
eugenebut604866f2017-05-10 21:35:362193 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452194 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362195 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472196 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452197 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112198 }
2199 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432200
Rakina Zata Amni3460d382021-10-29 00:43:372201 UpdateNavigationEntryDetails(entry, rfh, params, request,
2202 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002203 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302204
[email protected]5ccd4dc2012-10-24 02:28:142205 // The redirected to page should not inherit the favicon from the previous
2206 // page.
eugenebut604866f2017-05-10 21:35:362207 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482208 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142209
Charlie Reis951f43372023-05-05 00:30:072210 // Update the last committed index to reflect the committed entry. Do this
2211 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2212 // delegate sees the correct committed index when notified of navigation
2213 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2214 // https://crbug.com/1439948.)
2215 if (base::FeatureList::IsEnabled(
2216 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2217 last_committed_entry_index_ = GetIndexOfEntry(entry);
2218 }
2219
Peter Boströmd7592132019-01-30 04:50:312220 // We should also usually discard the pending entry if it corresponds to a
2221 // different navigation, since that one is now likely canceled. In rare
2222 // cases, we leave the pending entry for another navigation in place when we
2223 // know it is still ongoing, to avoid a flicker in the omnibox (see
2224 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432225 //
2226 // Note that we need to use the "internal" version since we don't want to
2227 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312228 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002229 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392230
Charlie Reis951f43372023-05-05 00:30:072231 if (!base::FeatureList::IsEnabled(
2232 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2233 // Update the last committed index to reflect the committed entry.
2234 // (This is legacy behavior, in case the kill-switch needs to be used.)
2235 last_committed_entry_index_ = GetIndexOfEntry(entry);
2236 }
[email protected]e9ba4472008-09-14 15:42:432237}
2238
[email protected]d202a7c2012-01-04 07:53:472239void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322240 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072241 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362242 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472243 bool replace_entry,
2244 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002245 NavigationRequest* request,
2246 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262247 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2248 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552249 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2250 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112251
[email protected]e9ba4472008-09-14 15:42:432252 // Manual subframe navigations just get the current entry cloned so the user
2253 // can go back or forward to it. The actual subframe information will be
2254 // stored in the page state for each of those entries. This happens out of
2255 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092256 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2257 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382258
Mikel Astizba9cf2fd2017-12-17 10:38:102259 // The DCHECK below documents the fact that we don't know of any situation
2260 // where |replace_entry| is true for subframe navigations. This simplifies
2261 // reasoning about the replacement struct for subframes (see
2262 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2263 DCHECK(!replace_entry);
2264
Patrick Monette50e8bd82019-06-13 22:40:452265 // This FrameNavigationEntry might not end up being used in the
2266 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072267 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452268 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:522269 absl::optional<GURL> initiator_base_url;
2270 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2271 initiator_base_url = request->common_params().initiator_base_url;
2272 }
Nate Chapin63db0d12022-01-20 22:03:302273 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2274 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2275 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572276 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302277 if (is_same_document) {
2278 FrameNavigationEntry* previous_frame_entry =
2279 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572280 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302281 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572282 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302283 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572284 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302285 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572286 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302287 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572288 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302289 policy_container_policies->referrer_policy);
2290 }
2291
Patrick Monette50e8bd82019-06-13 22:40:452292 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482293 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572294 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082295 rfh->GetSiteInstance(), nullptr, params.url,
2296 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212297 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2298 request->GetRedirectChain(), params.page_state, params.method,
2299 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572300 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032301
creisce0ef3572017-01-26 17:53:082302 std::unique_ptr<NavigationEntryImpl> new_entry =
2303 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452304 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032305 frame_tree_->root());
creise062d542015-08-25 02:01:552306
Alexander Timine3ec4192020-04-20 16:39:402307 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412308 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402309 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472310
creisce0ef3572017-01-26 17:53:082311 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452312 // to replace, which can happen due to a unique name change. See
2313 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2314 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382315
Dave Tapuska87696ae2021-11-18 18:48:312316 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152317 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432318}
2319
[email protected]d202a7c2012-01-04 07:53:472320bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322321 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072322 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392323 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252324 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002325 NavigationRequest* request,
2326 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292327 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2328 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2329
[email protected]e9ba4472008-09-14 15:42:432330 // We're guaranteed to have a previously committed entry, and we now need to
2331 // handle navigation inside of a subframe in it without creating a new entry.
2332 DCHECK(GetLastCommittedEntry());
2333
creis913c63ce2016-07-16 19:52:522334 // For newly created subframes, we don't need to send a commit notification.
2335 // This is only necessary for history navigations in subframes.
2336 bool send_commit_notification = false;
2337
Rakina Zata Amnif6950d552020-11-24 03:26:102338 // If |nav_entry_id| is non-zero and matches an existing entry, this
2339 // is a history navigation. Update the last committed index accordingly. If
2340 // we don't recognize the |nav_entry_id|, it might be a recently
2341 // pruned entry. We'll handle it below.
2342 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2343 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472344 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062345 // Make sure that a subframe commit isn't changing the main frame's
2346 // origin. Otherwise the renderer process may be confused, leading to a
2347 // URL spoof. We can't check the path since that may change
2348 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572349 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2350 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242351 // We should use checks similar to RenderFrameHostImpl's
2352 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2353 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572354 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2355 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2356 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2357 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522358 current_top_url.DeprecatedGetOriginAsURL() !=
2359 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442360 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512361 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062362 }
creis3cdc3b02015-05-29 23:00:472363
creis913c63ce2016-07-16 19:52:522364 // We only need to discard the pending entry in this history navigation
2365 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062366 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002367 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522368
2369 // History navigations should send a commit notification.
2370 send_commit_notification = true;
avi98405c22015-05-21 20:47:062371 }
[email protected]e9ba4472008-09-14 15:42:432372 }
[email protected]f233e4232013-02-23 00:55:142373
creisce0ef3572017-01-26 17:53:082374 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2375 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372376 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2377 // exists), or we may want to clobber it and create a new one. We update in
2378 // cases where the corresponding FrameNavigationEntry is conceptually similar
2379 // to the document described by the commit params: same-document
2380 // navigations, history traversal to an existing entry, and reloads (including
2381 // a "soft reload" where we navigate to the same url without flagging it as a
2382 // reload). But in the case of a different document that is not logically
2383 // related to the committed FrameNavigationEntry's document (cross-document,
2384 // not same url, not a reload, not a history traversal), we replace rather
2385 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252386 //
Nate Chapin9f169072021-06-09 19:32:372387 // In the case where we update, the FrameNavigationEntry will potentially be
2388 // shared across multiple NavigationEntries, and any updates will be reflected
2389 // in all of those NavigationEntries. In the replace case, any existing
2390 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252391 //
2392 // When navigating away from the initial empty document, we also update rather
2393 // than replace. Either update or replace will overwrite the initial empty
2394 // document state for |last_committed|, but if the FrameNavigationEntry for
2395 // the initial empty document is shared across multiple NavigationEntries (due
2396 // to a navigation in another frame), we want to make sure we overwrite the
2397 // initial empty document state everywhere this FrameNavigationEntry is used,
2398 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452399 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372400 FrameNavigationEntry* last_committed_frame_entry =
2401 last_committed->GetFrameEntry(rfh->frame_tree_node());
2402 NavigationEntryImpl::UpdatePolicy update_policy =
2403 NavigationEntryImpl::UpdatePolicy::kUpdate;
2404 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312405 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372406 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252407 last_committed_frame_entry->url() != params.url &&
2408 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372409 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2410 }
2411
Rakina Zata Amni3460d382021-10-29 00:43:372412 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002413 update_policy, false /* is_new_entry */,
2414 commit_details);
creis625a0c7d2015-03-24 23:17:122415
creis913c63ce2016-07-16 19:52:522416 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432417}
2418
[email protected]d202a7c2012-01-04 07:53:472419int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232420 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032421 for (size_t i = 0; i < entries_.size(); ++i) {
2422 if (entries_[i].get() == entry)
2423 return i;
2424 }
2425 return -1;
[email protected]765b35502008-08-21 00:51:202426}
2427
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572428void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242429 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572430 NavigationControllerImpl* source =
2431 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572432 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382433 DCHECK_EQ(1, GetEntryCount());
2434 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472435 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172436 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572437
Francois Dorayeaace782017-06-21 16:37:242438 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442439 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572440 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572441
Fergal Dalya1d569972021-03-16 03:24:532442 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302443 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532444 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2445 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302446 }
[email protected]4e6419c2010-01-15 04:50:342447
Lukasz Anforowicz0de0f452020-12-02 19:57:152448 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572449}
2450
Aran Gilman37d11632019-10-08 23:07:152451void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2452 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162453 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012454 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162455
[email protected]d202a7c2012-01-04 07:53:472456 NavigationControllerImpl* source =
2457 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252458
avi2b177592014-12-10 02:08:022459 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012460 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252461
[email protected]474f8512013-05-31 22:31:162462 // We now have one entry, possibly with a new pending entry. Ensure that
2463 // adding the entries from source won't put us over the limit.
2464 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572465 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572466 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252467
Carlos IL4dea8902020-05-26 15:14:292468 // Insert the entries from source. Ignore any pending entry, since it has not
2469 // committed in source.
[email protected]474f8512013-05-31 22:31:162470 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172471 DCHECK_NE(max_source_index, -1);
2472 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572473
2474 // Ignore the source's current entry if merging with replacement.
2475 // TODO(davidben): This should preserve entries forward of the current
2476 // too. http://crbug.com/317872
2477 if (replace_entry && max_source_index > 0)
2478 max_source_index--;
2479
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572480 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252481
2482 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552483 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142484
Hayato Ito2c8c08d02021-06-23 03:38:432485 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252486}
2487
[email protected]79368982013-11-13 01:11:012488bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162489 // If there is no last committed entry, we cannot prune. Even if there is a
2490 // pending entry, it may not commit, leaving this WebContents blank, despite
2491 // possibly giving it new entries via CopyStateFromAndPrune.
2492 if (last_committed_entry_index_ == -1)
2493 return false;
[email protected]9350602e2013-02-26 23:27:442494
[email protected]474f8512013-05-31 22:31:162495 // We cannot prune if there is a pending entry at an existing entry index.
2496 // It may not commit, so we have to keep the last committed entry, and thus
2497 // there is no sensible place to keep the pending entry. It is ok to have
2498 // a new pending entry, which can optionally commit as a new navigation.
2499 if (pending_entry_index_ != -1)
2500 return false;
2501
[email protected]474f8512013-05-31 22:31:162502 return true;
2503}
2504
[email protected]79368982013-11-13 01:11:012505void NavigationControllerImpl::PruneAllButLastCommitted() {
2506 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162507
avi2b177592014-12-10 02:08:022508 DCHECK_EQ(0, last_committed_entry_index_);
2509 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442510
Hayato Ito2c8c08d02021-06-23 03:38:432511 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442512}
2513
[email protected]79368982013-11-13 01:11:012514void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162515 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012516 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262517
Nate Chapin9eb16be72022-09-23 22:54:312518 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2519
[email protected]474f8512013-05-31 22:31:162520 // Erase all entries but the last committed entry. There may still be a
2521 // new pending entry after this.
2522 entries_.erase(entries_.begin(),
2523 entries_.begin() + last_committed_entry_index_);
2524 entries_.erase(entries_.begin() + 1, entries_.end());
2525 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262526}
2527
Christian Dullweber1af31e62018-02-22 11:49:482528void NavigationControllerImpl::DeleteNavigationEntries(
2529 const DeletionPredicate& deletionPredicate) {
2530 // It is up to callers to check the invariants before calling this.
2531 CHECK(CanPruneAllButLastCommitted());
2532 std::vector<int> delete_indices;
2533 for (size_t i = 0; i < entries_.size(); i++) {
2534 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572535 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482536 delete_indices.push_back(i);
2537 }
2538 }
2539 if (delete_indices.empty())
2540 return;
2541
2542 if (delete_indices.size() == GetEntryCount() - 1U) {
2543 PruneAllButLastCommitted();
2544 } else {
2545 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382546 for (const auto& index : base::Reversed(delete_indices)) {
2547 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482548 }
Hayato Ito2c8c08d02021-06-23 03:38:432549 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482550 }
2551 delegate()->NotifyNavigationEntriesDeleted();
2552}
2553
Shivani Sharma883f5f32019-02-12 18:20:012554bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2555 auto* entry = GetEntryAtIndex(index);
2556 return entry && entry->should_skip_on_back_forward_ui();
2557}
2558
Carlos Caballero35ce710c2019-09-19 10:59:452559BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2560 return back_forward_cache_;
2561}
2562
William Liu055a3542023-04-02 17:21:192563NavigationEntryScreenshotCache*
2564NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
2565 CHECK_EQ(frame_tree_->type(), FrameTree::Type::kPrimary);
2566 if (!nav_entry_screenshot_cache_ && AreBackForwardTransitionsEnabled()) {
2567 nav_entry_screenshot_cache_ =
2568 std::make_unique<NavigationEntryScreenshotCache>(
2569 BrowserContextImpl::From(browser_context_)
2570 ->GetNavigationEntryScreenshotManager()
2571 ->GetSafeRef(),
2572 this);
2573 }
2574 return nav_entry_screenshot_cache_.get();
2575}
2576
clamy987a3752018-05-03 17:36:262577void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2578 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2579 // progress, since this will cause a use-after-free. (We only allow this
2580 // when the tab is being destroyed for shutdown, since it won't return to
2581 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032582 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262583
2584 if (was_failure && pending_entry_) {
2585 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2586 } else {
2587 failed_pending_entry_id_ = 0;
2588 }
2589
2590 if (pending_entry_) {
2591 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332592 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262593 pending_entry_index_ = -1;
2594 pending_entry_ = nullptr;
2595 }
arthursonzogni66f711c2019-10-08 14:40:362596
2597 // Ensure any refs to the current pending entry are ignored if they get
2598 // deleted, by clearing the set of known refs. All future pending entries will
2599 // only be affected by new refs.
2600 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262601}
2602
2603void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2604 if (pending_entry_)
2605 pending_entry_->set_ssl_error(error);
2606}
2607
Xiaohan Wang7f8052e02022-01-14 18:44:282608#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422609// static
2610bool NavigationControllerImpl::ValidateDataURLAsString(
2611 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2612 if (!data_url_as_string)
2613 return false;
2614
2615 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2616 return false;
2617
2618 // The number of characters that is enough for validating a data: URI.
2619 // From the GURL's POV, the only important part here is scheme, it doesn't
2620 // check the actual content. Thus we can take only the prefix of the url, to
2621 // avoid unneeded copying of a potentially long string.
2622 const size_t kDataUriPrefixMaxLen = 64;
2623 GURL data_url(
2624 std::string(data_url_as_string->front_as<char>(),
2625 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2626 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2627 return false;
2628
2629 return true;
2630}
2631#endif
2632
Shivani Sharma194877032019-03-07 17:52:472633void NavigationControllerImpl::NotifyUserActivation() {
2634 // When a user activation occurs, ensure that all adjacent entries for the
2635 // same document clear their skippable bit, so that the history manipulation
2636 // intervention does not apply to them.
shivanigithub99368382021-06-16 18:33:372637 if (base::FeatureList::IsEnabled(
2638 features::kDebugHistoryInterventionNoUserActivation)) {
2639 return;
2640 }
2641
Shivani Sharmac4cc8922019-04-18 03:11:172642 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472643}
2644
clamy987a3752018-05-03 17:36:262645bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2646 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332647 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2648 blink::LocalFrameToken initiator_frame_token,
2649 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262650 NavigationEntryImpl* entry =
2651 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2652 if (!entry)
2653 return false;
2654
2655 FrameNavigationEntry* frame_entry =
2656 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2657 if (!frame_entry)
2658 return false;
2659
Camille Lamy5193caa2018-10-12 11:59:422660 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572661 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232662 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332663 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2664 initiator_process_id);
clamyea99ea12018-05-28 13:54:232665
2666 if (!request)
2667 return false;
2668
arthursonzognif046d4a2019-12-12 19:08:102669 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412670
Rakina Zata Amni1c83b082023-02-08 01:09:002671 SCOPED_CRASH_KEY_STRING256(
2672 "Bug1400009", "req_url",
2673 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2674 SCOPED_CRASH_KEY_NUMBER(
2675 "Bug1400009", "nav_entry_si",
2676 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2677 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2678 frame_entry->site_instance()
2679 ? ((int)frame_entry->site_instance()->GetId())
2680 : -1);
2681 bool has_sig =
2682 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2683 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2684 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2685 has_sig ? (!!frame_tree_->GetRenderViewHost(
2686 frame_entry->site_instance()->group()))
2687 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052688 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2689 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232690
2691 return true;
clamy987a3752018-05-03 17:36:262692}
2693
Tsuyoshi Horo52fd08e2020-07-07 07:03:452694bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2695 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2696 if (!entry)
2697 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432698
2699 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2700 // We should never navigate to an existing initial NavigationEntry that is
2701 // the initial NavigationEntry for the initial empty document that hasn't
2702 // been overridden by the synchronous about:blank commit, to preserve
2703 // legacy behavior where trying to reload when the main frame is on the
2704 // initial empty document won't result in a navigation. See also
2705 // https://crbug.com/1277414.
2706 return false;
2707 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452708 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2709 if (!frame_entry)
2710 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142711 ReloadType reload_type = ReloadType::NORMAL;
2712 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452713 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142714 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452715 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432716 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332717 absl::nullopt /* initiator_frame_token */,
2718 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452719 if (!request)
2720 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052721 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452722 return true;
2723}
2724
clamy987a3752018-05-03 17:36:262725void NavigationControllerImpl::NavigateFromFrameProxy(
2726 RenderFrameHostImpl* render_frame_host,
2727 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022728 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452729 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072730 const absl::optional<url::Origin>& initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212731 const absl::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262732 bool is_renderer_initiated,
2733 SiteInstance* source_site_instance,
2734 const Referrer& referrer,
2735 ui::PageTransition page_transition,
2736 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252737 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262738 const std::string& method,
2739 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092740 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142741 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212742 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502743 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392744 const absl::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292745 blink::mojom::NavigationInitiatorActivationAndAdStatus
2746 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222747 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492748 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462749 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452750 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582751 bool is_container_initiated,
2752 absl::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582753 if (is_renderer_initiated)
2754 DCHECK(initiator_origin.has_value());
2755
clamy987a3752018-05-03 17:36:262756 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582757
Rakina Zata Amni2322f4f82022-01-24 13:24:242758 // Don't allow an entry replacement if there is no entry to replace.
2759 // http://crbug.com/457149
2760 if (GetEntryCount() == 0)
2761 should_replace_current_entry = false;
2762
clamy987a3752018-05-03 17:36:262763 // Create a NavigationEntry for the transfer, without making it the pending
2764 // entry. Subframe transfers should have a clone of the last committed entry
2765 // with a FrameNavigationEntry for the target frame. Main frame transfers
2766 // should have a new NavigationEntry.
2767 // TODO(creis): Make this unnecessary by creating (and validating) the params
2768 // directly, passing them to the destination RenderFrameHost. See
2769 // https://crbug.com/536906.
2770 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262771 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262772 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452773 DCHECK(GetLastCommittedEntry());
2774 entry = GetLastCommittedEntry()->Clone();
2775 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172776 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2777 // Renderer-initiated navigation that target a remote frame are currently
2778 // classified as browser-initiated when this one has already navigated.
2779 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372780 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2781 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2782 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2783 // same-document navigation), they will still be present in the
2784 // committed NavigationEntry that will be referenced to construct the new
2785 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262786 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082787 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582788 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072789 absl::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212790 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152791 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262792 } else {
2793 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172794 // If `node` is the outermost main frame, it rewrites a virtual url in order
2795 // to adjust the original input url if needed. For inner frames such as
2796 // fenced frames or subframes, they don't rewrite urls as the urls are not
2797 // input urls by users.
2798 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:322799 absl::optional<GURL> source_process_site_url = absl::nullopt;
2800 if (source_site_instance && source_site_instance->HasProcess()) {
2801 source_process_site_url =
2802 source_site_instance->GetProcess()->GetProcessLock().site_url();
2803 }
clamy987a3752018-05-03 17:36:262804 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212805 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322806 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212807 extra_headers, browser_context_, blob_url_loader_factory,
2808 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262809 entry->root_node()->frame_entry->set_source_site_instance(
2810 static_cast<SiteInstanceImpl*>(source_site_instance));
2811 entry->root_node()->frame_entry->set_method(method);
2812 }
clamy987a3752018-05-03 17:36:262813
Camille Lamy5193caa2018-10-12 11:59:422814 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452815 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262816 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422817 override_user_agent = true;
clamy987a3752018-05-03 17:36:262818 }
2819 // TODO(creis): Set user gesture and intent received timestamp on Android.
2820
2821 // We may not have successfully added the FrameNavigationEntry to |entry|
2822 // above (per https://crbug.com/608402), in which case we create it from
2823 // scratch. This works because we do not depend on |frame_entry| being inside
2824 // |entry| during NavigateToEntry. This will go away when we shortcut this
2825 // further in https://crbug.com/536906.
2826 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2827 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452828 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082829 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582830 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072831 absl::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212832 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152833 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572834 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262835 }
2836
Camille Lamy5193caa2018-10-12 11:59:422837 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022838 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452839 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292840 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212841 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422842 params.source_site_instance = source_site_instance;
2843 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2844 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032845 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422846 params.referrer = referrer;
2847 /* params.redirect_chain: skip */
2848 params.extra_headers = extra_headers;
2849 params.is_renderer_initiated = is_renderer_initiated;
2850 params.override_user_agent = UA_OVERRIDE_INHERIT;
2851 /* params.base_url_for_data_url: skip */
2852 /* params.virtual_url_for_data_url: skip */
2853 /* params.data_url_as_string: skip */
2854 params.post_data = post_body;
2855 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582856 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422857 /* params.frame_name: skip */
2858 // TODO(clamy): See if user gesture should be propagated to this function.
2859 params.has_user_gesture = false;
2860 params.should_clear_history_list = false;
2861 params.started_from_context_menu = false;
2862 /* params.navigation_ui_data: skip */
2863 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222864 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542865 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212866 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412867 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502868 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292869 params.initiator_activation_and_ad_status =
2870 initiator_activation_and_ad_status;
Camille Lamy5193caa2018-10-12 11:59:422871
2872 std::unique_ptr<NavigationRequest> request =
2873 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032874 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142875 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392876 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492877 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582878 is_unfenced_top_navigation, is_container_initiated,
2879 embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232880
2881 if (!request)
2882 return;
2883
Garrett Tanzerbb8db412022-09-27 21:59:462884 // Force the navigation to take place in a new browsing instance.
2885 // This is used by _unfencedTop in fenced frames to ensure that navigations
2886 // leaving the fenced context create a new browsing instance.
2887 if (force_new_browsing_instance) {
2888 request->coop_status().ForceBrowsingInstanceSwap();
2889 }
2890
Arthur Hemery948742762019-09-18 10:06:242891 // At this stage we are proceeding with this navigation. If this was renderer
2892 // initiated with user gesture, we need to make sure we clear up potential
2893 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2894 DiscardNonCommittedEntries();
2895
Lukasz Anforowicz9ee83c272020-12-01 20:14:052896 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262897}
2898
[email protected]d1198fd2012-08-13 22:50:192899void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252900 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212901 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192902 if (!session_storage_namespace)
2903 return;
2904
2905 // We can't overwrite an existing SessionStorage without violating spec.
2906 // Attempts to do so may give a tab access to another tab's session storage
2907 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152908 bool successful_insert =
2909 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252910 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052911 static_cast<SessionStorageNamespaceImpl*>(
2912 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302913 .second;
2914 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192915}
2916
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572917bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452918 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032919 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462920}
2921
Aran Gilman37d11632019-10-08 23:07:152922SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252923 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302924 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252925 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032926 DOMStorageContextWrapper* context_wrapper =
2927 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2928
2929 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252930 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032931 if (it != session_storage_namespace_map_.end()) {
2932 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152933 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2934 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472935
michaelnbacbcbd2016-02-09 00:32:032936 return it->second.get();
2937 }
2938
2939 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102940 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2941 SessionStorageNamespaceImpl::Create(context_wrapper);
2942 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2943 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252944 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102945 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302946
Daniel Murphy31bbb8b12018-02-07 21:44:102947 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302948}
2949
2950SessionStorageNamespace*
2951NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252952 return GetSessionStorageNamespace(
2953 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302954}
2955
2956const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572957NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302958 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552959}
[email protected]d202a7c2012-01-04 07:53:472960
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572961bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562962 return needs_reload_;
2963}
[email protected]a26023822011-12-29 00:23:552964
[email protected]46bb5e9c2013-10-03 22:16:472965void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412966 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2967}
2968
2969void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472970 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412971 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542972
2973 if (last_committed_entry_index_ != -1) {
2974 entries_[last_committed_entry_index_]->SetTransitionType(
2975 ui::PAGE_TRANSITION_RELOAD);
2976 }
[email protected]46bb5e9c2013-10-03 22:16:472977}
2978
[email protected]d202a7c2012-01-04 07:53:472979void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572980 DCHECK_LT(index, GetEntryCount());
2981 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312982 DiscardNonCommittedEntries();
2983
Nate Chapin9eb16be72022-09-23 22:54:312984 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:312985 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122986 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312987 last_committed_entry_index_--;
2988}
2989
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572990NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272991 // If there is no pending_entry_, there should be no pending_entry_index_.
2992 DCHECK(pending_entry_ || pending_entry_index_ == -1);
2993
2994 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:362995 // at that index. An exception is while a reload of a post commit error page
2996 // is ongoing; in that case pending entry will point to the entry replaced
2997 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:272998 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:362999 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3000 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273001
[email protected]022af742011-12-28 18:37:253002 return pending_entry_;
3003}
3004
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573005int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273006 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273007 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553008 return pending_entry_index_;
3009}
3010
avi25764702015-06-23 15:43:373011void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573012 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363013 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313014 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003015 bool in_fenced_frame_tree,
3016 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313017 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3018 // set because:
3019 // 1) They don't influence the history of the outer page.
3020 // 2) They are always replace only navigation (there is always only one entry
3021 // in their history stack).
3022 // 3) Are not top level navigations and appear similar to iframes.
3023 // Navigations of the fenced frame might create a new NavigationEntry, which
3024 // will call this function. Non fenced frame navigations will never have
3025 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3026 // InsertOrReplaceEntry.
3027 DCHECK_EQ(in_fenced_frame_tree,
3028 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3029 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203030
avi5cad4912015-06-19 05:25:443031 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3032 // need to keep continuity with the pending entry, so copy the pending entry's
3033 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3034 // then the renderer navigated on its own, independent of the pending entry,
3035 // so don't copy anything.
3036 if (pending_entry_ && pending_entry_index_ == -1)
3037 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203038
Rakina Zata Amnia4e27222021-12-22 01:05:003039 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203040
creisee17e932015-07-17 17:56:223041 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453042 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103043 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573044 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363045 // If the new entry is a post-commit error page, we store the current last
3046 // committed entry to the side so that we can put it back when navigating
3047 // away from the error.
3048 if (was_post_commit_error) {
3049 DCHECK(!entry_replaced_by_post_commit_error_);
3050 entry_replaced_by_post_commit_error_ =
3051 std::move(entries_[last_committed_entry_index_]);
3052 }
dcheng36b6aec92015-12-26 06:16:363053 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223054 return;
3055 }
[email protected]765b35502008-08-21 00:51:203056
creis37979a62015-08-04 19:48:183057 // We shouldn't see replace == true when there's no committed entries.
3058 DCHECK(!replace);
3059
Michael Thiessen9b14d512019-09-23 21:19:473060 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203061
Shivani Sharmad8c8d652019-02-13 17:27:573062 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203063
dcheng36b6aec92015-12-26 06:16:363064 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203065 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293066}
3067
Shivani Sharmad8c8d652019-02-13 17:27:573068void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163069 if (entries_.size() < max_entry_count())
3070 return;
3071
3072 DCHECK_EQ(max_entry_count(), entries_.size());
3073 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573074 CHECK_EQ(pending_entry_index_, -1);
3075
3076 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423077 // Retrieve the oldest skippable entry.
3078 for (; index < GetEntryCount(); index++) {
3079 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3080 break;
Shivani Sharmad8c8d652019-02-13 17:27:573081 }
3082
3083 // If there is no skippable entry or if it is the last committed entry then
3084 // fall back to pruning the oldest entry. It is not safe to prune the last
3085 // committed entry.
3086 if (index == GetEntryCount() || index == last_committed_entry_index_)
3087 index = 0;
3088
3089 bool should_succeed = RemoveEntryAtIndex(index);
3090 DCHECK_EQ(true, should_succeed);
3091
3092 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253093}
3094
clamy3cb9bea92018-07-10 12:42:023095void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163096 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203097 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:133098 absl::optional<blink::scheduler::TaskAttributionId>
3099 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203100 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503101 TRACE_EVENT0("navigation",
3102 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273103 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023104 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363105 if (pending_entry_index_ != -1) {
3106 // The pending entry may not be in entries_ if a post-commit error page is
3107 // showing.
3108 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3109 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3110 }
Gyuyoung Kim107c2a02021-04-13 01:49:303111 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573112 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013113 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033114 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573115 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133116 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3117 // the same as the top level frame being navigated.
3118 if (root->current_frame_host() != initiator_rfh) {
3119 soft_navigation_heuristics_task_id = absl::nullopt;
3120 }
Arthur Sonzogni620cec62018-12-13 13:08:573121
[email protected]83c2e232011-10-07 21:36:463122 // If we were navigating to a slow-to-commit page, and the user performs
3123 // a session history navigation to the last committed page, RenderViewHost
3124 // will force the throbber to start, but WebKit will essentially ignore the
3125 // navigation, and won't send a message to stop the throbber. To prevent this
3126 // from happening, we drop the navigation here and stop the slow-to-commit
3127 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023128 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083129 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273130 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033131 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123132
[email protected]83c2e232011-10-07 21:36:463133 DiscardNonCommittedEntries();
3134 return;
3135 }
3136
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333137 absl::optional<blink::LocalFrameToken> initiator_frame_token;
3138 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3139 if (initiator_rfh) {
3140 initiator_frame_token = initiator_rfh->GetFrameToken();
3141 initiator_process_id = initiator_rfh->GetProcess()->GetID();
3142 DCHECK(initiator_frame_token);
3143 }
3144
creisce0ef3572017-01-26 17:53:083145 // Compare FrameNavigationEntries to see which frames in the tree need to be
3146 // navigated.
clamy3cb9bea92018-07-10 12:42:023147 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3148 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333149 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3150 initiator_process_id, soft_navigation_heuristics_task_id,
3151 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303152
3153 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573154 // We were unable to match any frames to navigate. This can happen if a
3155 // history navigation targets a subframe that no longer exists
3156 // (https://crbug.com/705550). In this case, we need to update the current
3157 // history entry to the pending one but keep the main document loaded. We
3158 // also need to ensure that observers are informed about the updated
3159 // current history entry (e.g., for greying out back/forward buttons), and
3160 // that renderer processes update their history offsets. The easiest way
3161 // to do all that is to schedule a "redundant" same-document navigation in
3162 // the main frame.
3163 //
3164 // Note that we don't want to remove this history entry, as it might still
3165 // be valid later, since a frame that it's targeting may be recreated.
3166 //
3167 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3168 // need to repeat history navigations until finding the one that works.
3169 // Consider changing this behavior to keep looking for the first valid
3170 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023171 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423172 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573173 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573174 ReloadType::NONE /* reload_type */,
3175 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433176 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333177 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023178 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573179 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023180 DiscardPendingEntry(false);
3181 return;
3182 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573183 same_document_loads.push_back(std::move(navigation_request));
3184
3185 // Sanity check that we never take this branch for any kinds of reloads,
3186 // as those should've queued a different-document load in the main frame.
3187 DCHECK(!is_forced_reload);
3188 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303189 }
3190
Nate Chapinbf682fa32022-09-26 22:41:203191 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163192 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203193 if (initiator_rfh && initiator_rfh->IsSandboxed(
3194 network::mojom::WebSandboxFlags::kTopNavigation)) {
3195 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3196 initiator_rfh, same_document_loads) &&
3197 DoesSandboxNavigationStayWithinSubtree(
3198 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503199 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163200 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203201 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3202 initiator_rfh,
3203 navigates_inside_tree
3204 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3205 : blink::mojom::WebFeature::
3206 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523207
3208 // If the navigation occurred outside the tree discard it because
3209 // the sandboxed frame didn't have permission to navigate outside
3210 // its tree. If it is possible that the navigation is both inside and
3211 // outside the frame tree and we discard it entirely because we don't
3212 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143213 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203214 // If a |navigation_api_key| was provided, this navigation originated from
3215 // the navigation API. Notify the renderer that the navigation was
3216 // cancelled so the navigation API can fire an error event and reject the
3217 // relevant promise.
3218 if (navigation_api_key) {
3219 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3220 *navigation_api_key,
3221 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3222 }
Dave Tapuska855c1e12019-08-23 20:45:523223 DiscardPendingEntry(false);
3224 return;
3225 }
Dave Tapuska8bfd84c2019-03-26 20:47:163226 }
3227
Nate Chapin6c43c022023-02-13 23:32:423228 // If it is possible that this traverse may involve a same-document navigation
3229 // in the initiator and there is a Navigation API key involved, then we may
3230 // need to notify the initiator if it fails. (The early returns above either
3231 // do not involve these cases or already notify the initiator.)
3232 // The event only needs to fire for the initiator, and only if the initiator
3233 // itself is performing a same-document navigation (because the event will not
3234 // fire if it navigates cross-document).
3235 if (navigation_api_key) {
3236 for (auto& item : same_document_loads) {
3237 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3238 item->set_pending_navigation_api_key(*navigation_api_key);
3239 break;
3240 }
3241 }
3242 }
3243
Carlos Caballero539a421c2020-07-06 10:25:573244 // BackForwardCache:
3245 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563246 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573247 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3248 DCHECK_EQ(reload_type, ReloadType::NONE);
3249 auto navigation_request = CreateNavigationRequestFromEntry(
3250 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3251 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333252 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3253 initiator_process_id);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053254 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573255
3256 return;
3257 }
3258
3259 // History navigation might try to reuse a specific BrowsingInstance, already
3260 // used by a page in the cache. To avoid having two different main frames that
3261 // live in the same BrowsingInstance, evict the all pages with this
3262 // BrowsingInstance from the cache.
3263 //
3264 // For example, take the following scenario:
3265 //
3266 // A1 = Some page on a.com
3267 // A2 = Some other page on a.com
3268 // B3 = An uncacheable page on b.com
3269 //
3270 // Then the following navigations occur:
3271 // A1->A2->B3->A1
3272 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3273 // take its place) and A1 will be created in the same BrowsingInstance (and
3274 // SiteInstance), as A2.
3275 //
3276 // If we didn't do anything, both A1 and A2 would remain alive in the same
3277 // BrowsingInstance/SiteInstance, which is unsupported by
3278 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3279 // A2 from the cache.
3280 if (pending_entry_->site_instance()) {
3281 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3282 pending_entry_->site_instance());
3283 }
3284
Rakina Zata Amnid605d462022-06-01 10:17:033285 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3286 pending_entry_ && pending_entry_->IsRestored());
3287 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3288 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3289 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3290 pending_entry_index_);
3291 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3292 last_committed_entry_index_);
3293 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3294 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3295 pending_entry_ && pending_entry_->IsInitialEntry());
3296 SCOPED_CRASH_KEY_BOOL(
3297 "nav_reentrancy", "pending_entry_initial2",
3298 pending_entry_ &&
3299 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3300 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3301 IsInitialNavigation());
3302 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3303 IsInitialBlankNavigation());
3304 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3305 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3306 (int)pending_reload_);
3307
clamy3cb9bea92018-07-10 12:42:023308 // This call does not support re-entrancy. See http://crbug.com/347742.
3309 CHECK(!in_navigate_to_pending_entry_);
3310 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303311
Rakina Zata Amnid605d462022-06-01 10:17:033312 // If the navigation-reentrancy is caused by calling
3313 // NavigateToExistingPendingEntry twice, this will note the previous call's
3314 // pending entry's ID.
3315 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3316 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3317
arthursonzogni66f711c2019-10-08 14:40:363318 // It is not possible to delete the pending NavigationEntry while navigating
3319 // to it. Grab a reference to delay potential deletion until the end of this
3320 // function.
3321 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3322
Nate Chapin154b14b2023-02-17 18:28:163323 // If there is a main-frame same-document history navigation, we may defer
3324 // the subframe history navigations in order to give JS in the main frame the
3325 // opportunity to cancel the entire traverse via the navigate event. In that
3326 // case, we need to stash the main frame request's navigation token on the
3327 // subframes, so they can look up the main frame request and defer themselves
3328 // until it completes.
3329 if (!same_document_loads.empty() &&
3330 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3331 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3332 // The token will only be returned in cases where deferring the navigation
3333 // is necessary.
3334 if (auto main_frame_same_document_token =
3335 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3336 for (auto& item : same_document_loads) {
3337 if (item.get() != main_frame_request) {
3338 item->set_main_frame_same_document_history_token(
3339 main_frame_same_document_token);
3340 }
3341 }
3342 for (auto& item : different_document_loads) {
3343 item->set_main_frame_same_document_history_token(
3344 main_frame_same_document_token);
3345 }
3346 }
3347 }
3348
creis4e2ecb72015-06-20 00:46:303349 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023350 for (auto& item : same_document_loads) {
3351 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053352 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303353 }
clamy3cb9bea92018-07-10 12:42:023354 for (auto& item : different_document_loads) {
3355 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053356 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303357 }
clamy3cb9bea92018-07-10 12:42:023358
3359 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303360}
3361
Alex Moshchuk3a4e77a2020-05-29 21:32:573362NavigationControllerImpl::HistoryNavigationAction
3363NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303364 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573365 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423366 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583367 // Only active and prerendered documents are allowed to navigate in their
3368 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423369 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013370 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583371 // - If the document is in pending deletion, the browser already committed
3372 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3373 // - If the document is in back-forward cache, it's not allowed to navigate
3374 // as it should remain frozen. Ignore the request and evict the document
3375 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423376 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583377 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423378 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113379 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3380 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423381 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113382 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423383 }
arthursonzogni03f76152019-02-12 10:35:203384
Alex Moshchuk3a4e77a2020-05-29 21:32:573385 // Reloads should result in a different-document load. Note that reloads may
3386 // also happen via the |needs_reload_| mechanism where the reload_type is
3387 // NONE, so detect this by comparing whether we're going to the same
3388 // entry that we're currently on. Similarly to above, only main frames
3389 // should reach this. Note that subframes support reloads, but that's done
3390 // via a different path that doesn't involve FindFramesToNavigate (see
3391 // RenderFrameHost::Reload()).
3392 if (reload_type != ReloadType::NONE ||
3393 pending_entry_index_ == last_committed_entry_index_) {
3394 DCHECK(frame->IsMainFrame());
3395 return HistoryNavigationAction::kDifferentDocument;
3396 }
3397
Alex Moshchuk47d1a4bd2020-06-01 22:15:343398 // If there is no new FrameNavigationEntry for the frame, ignore the
3399 // load. For example, this may happen when going back to an entry before a
3400 // frame was created. Suppose we commit a same-document navigation that also
3401 // results in adding a new subframe somewhere in the tree. If we go back,
3402 // the new subframe will be missing a FrameNavigationEntry in the previous
3403 // NavigationEntry, but we shouldn't delete or change what's loaded in
3404 // it.
3405 //
Alex Moshchuke65c39272020-06-03 17:55:373406 // Note that in this case, there is no need to keep looking for navigations
3407 // in subframes, which would be missing FrameNavigationEntries as well.
3408 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343409 // It's important to check this before checking |old_item| below, since both
3410 // might be null, and in that case we still shouldn't change what's loaded in
3411 // this frame. Note that scheduling any loads assumes that |new_item| is
3412 // non-null. See https://crbug.com/1088354.
3413 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3414 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373415 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343416
Charlie Reisa474fb62022-03-17 02:31:363417 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3418 // which history item it is currently on, since this may be different than the
3419 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3420 // (e.g., if a history navigation is targeting multiple frames and only some
3421 // have committed so far).
creis4e2ecb72015-06-20 00:46:303422 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363423 frame->current_frame_host()->last_committed_frame_entry();
3424 if (!old_item) {
3425 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3426 // fall back to the last committed NavigationEntry's record for this frame.
3427 // This may happen in cases like the initial state of the RenderFrameHost.
3428 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3429 // accurate FrameNavigationEntry and eliminate this case.
3430 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3431 }
3432 // If neither approach finds a FrameNavigationEntry, schedule a
3433 // different-document load.
3434 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573435 if (!old_item)
3436 return HistoryNavigationAction::kDifferentDocument;
3437
Alex Moshchuk3a4e77a2020-05-29 21:32:573438 // If the new item is not in the same SiteInstance, schedule a
3439 // different-document load. Newly restored items may not have a SiteInstance
3440 // yet, in which case it will be assigned on first commit.
3441 if (new_item->site_instance() &&
3442 new_item->site_instance() != old_item->site_instance())
3443 return HistoryNavigationAction::kDifferentDocument;
3444
3445 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313446 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3447 // that we do this even if the history navigation would not be modifying this
3448 // frame were it live.
3449 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573450 return HistoryNavigationAction::kDifferentDocument;
3451
3452 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313453 // Starting a navigation after a crash early-promotes the speculative
3454 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3455 // committed yet, so we can not possibly perform a same-document history
3456 // navigation. The frame would need to be reloaded with a cross-document
3457 // navigation.
3458 if (!frame->current_frame_host()->has_committed_any_navigation())
3459 return HistoryNavigationAction::kDifferentDocument;
3460
creis54131692016-08-12 18:32:253461 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493462 // sequence number but different item sequence number.
3463 if (new_item->document_sequence_number() ==
3464 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573465 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493466 }
avib48cb312016-05-05 21:35:003467
Alex Moshchuk3a4e77a2020-05-29 21:32:573468 // Otherwise, if both item and document sequence numbers differ, this
3469 // should be a different document load.
3470 return HistoryNavigationAction::kDifferentDocument;
3471 }
3472
3473 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373474 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573475 DCHECK_EQ(new_item->document_sequence_number(),
3476 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373477 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573478}
3479
3480void NavigationControllerImpl::FindFramesToNavigate(
3481 FrameTreeNode* frame,
3482 ReloadType reload_type,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333483 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
3484 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133485 absl::optional<blink::scheduler::TaskAttributionId>
3486 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573487 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3488 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3489 DCHECK(pending_entry_);
3490 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3491
3492 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3493
3494 if (action == HistoryNavigationAction::kSameDocument) {
3495 std::unique_ptr<NavigationRequest> navigation_request =
3496 CreateNavigationRequestFromEntry(
3497 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133498 /*is_same_document_history_load=*/true,
3499 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333500 initiator_frame_token, initiator_process_id,
3501 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573502 if (navigation_request) {
3503 // Only add the request if was properly created. It's possible for the
3504 // creation to fail in certain cases, e.g. when the URL is invalid.
3505 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303506 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573507 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473508 std::unique_ptr<NavigationRequest> navigation_request =
3509 CreateNavigationRequestFromEntry(
3510 frame, pending_entry_, new_item, reload_type,
3511 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433512 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333513 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473514 if (navigation_request) {
3515 // Only add the request if was properly created. It's possible for the
3516 // creation to fail in certain cases, e.g. when the URL is invalid.
3517 different_document_loads->push_back(std::move(navigation_request));
3518 }
3519 // For a different document, the subframes will be destroyed, so there's
3520 // no need to consider them.
3521 return;
Alex Moshchuke65c39272020-06-03 17:55:373522 } else if (action == HistoryNavigationAction::kStopLooking) {
3523 return;
creis4e2ecb72015-06-20 00:46:303524 }
3525
Yoav Weiss8c573952022-11-17 17:35:133526 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3527 // we currently only support soft navigation heuristics for the top level
3528 // frame.
creis4e2ecb72015-06-20 00:46:303529 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333530 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3531 initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133532 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
Nate Chapin45f620582021-09-30 17:45:433533 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303534 }
3535}
3536
Harkiran Bolariaba823e42021-05-21 18:30:363537base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243538 const LoadURLParams& params) {
3539 // Find the appropriate FrameTreeNode.
3540 FrameTreeNode* node = nullptr;
3541 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3542 !params.frame_name.empty()) {
3543 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033544 ? frame_tree_->FindByID(params.frame_tree_node_id)
3545 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503546 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243547 }
3548
3549 // If no FrameTreeNode was specified, navigate the main frame.
3550 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033551 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243552
Camille Lamy5193caa2018-10-12 11:59:423553 // Compute overrides to the LoadURLParams for |override_user_agent|,
3554 // |should_replace_current_entry| and |has_user_gesture| that will be used
3555 // both in the creation of the NavigationEntry and the NavigationRequest.
3556 // Ideally, the LoadURLParams themselves would be updated, but since they are
3557 // passed as a const reference, this is not possible.
3558 // TODO(clamy): When we only create a NavigationRequest, move this to
3559 // CreateNavigationRequestFromLoadURLParams.
3560 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3561 GetLastCommittedEntry());
3562
Rakina Zata Amnie2d31312022-11-18 03:38:453563 // An entry replacement must happen if the current browsing context should
3564 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333565 bool should_replace_current_entry =
3566 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453567 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423568
clamy21718cc22018-06-13 13:34:243569 // Javascript URLs should not create NavigationEntries. All other navigations
3570 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243571 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373572 std::unique_ptr<NavigationEntryImpl> entry =
3573 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3574 should_replace_current_entry,
3575 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243576 DiscardPendingEntry(false);
3577 SetPendingEntry(std::move(entry));
3578 }
3579
Tim Judkins59548192023-05-17 17:51:203580 // Renderer-debug URLs are sent to the current renderer process immediately
3581 // for processing and don't need to create a NavigationRequest. Note: this
3582 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243583 // renderer-debug URLs.
3584 // Note: we intentionally leave the pending entry in place for renderer debug
3585 // URLs, unlike the cases below where we clear it if the navigation doesn't
3586 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303587 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483588 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3589 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153590 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203591 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483592 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363593 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483594 }
3595
clamy21718cc22018-06-13 13:34:243596 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363597 return nullptr;
clamy21718cc22018-06-13 13:34:243598 }
3599
Antonio Sartori78a749f2020-11-30 12:03:393600 DCHECK(pending_entry_);
3601
clamy21718cc22018-06-13 13:34:243602 // Convert navigations to the current URL to a reload.
3603 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3604 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3605 // DevTools sometimes issues navigations to main frames that they do not
3606 // expect to see treated as reload, and it only works because they pass a
3607 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3608 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543609 ReloadType reload_type = params.reload_type;
3610 if (reload_type == ReloadType::NONE &&
3611 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043612 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243613 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243614 params.load_type ==
3615 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543616 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243617 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473618 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393619
3620 // If this is a reload of an existing FrameNavigationEntry and we had a
3621 // policy container for it, then we should copy it into the pending entry,
3622 // so that it is copied to the navigation request in
3623 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453624 FrameNavigationEntry* previous_frame_entry =
3625 GetLastCommittedEntry()->GetFrameEntry(node);
3626 if (previous_frame_entry &&
3627 previous_frame_entry->policy_container_policies()) {
3628 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3629 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393630 }
3631 }
3632
3633 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173634 // document, then we should copy the document polices from RenderFrameHost's
3635 // PolicyContainerHost. The NavigationRequest will create a new
3636 // PolicyContainerHost with the document policies from the |pending_entry_|,
3637 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3638 // the navigation. This way, we ensure that we keep enforcing the right
3639 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453640 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393641 if (node->current_frame_host() &&
3642 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193643 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163644 node->current_frame_host()
3645 ->policy_container_host()
3646 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233647 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393648 }
clamy21718cc22018-06-13 13:34:243649 }
3650
3651 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263652 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243653
Tsuyoshi Horo167ca6432022-03-09 05:16:393654 // This will be used to set the Navigation Timing API navigationStart
3655 // parameter for browser navigations in new tabs (intents, tabs opened through
3656 // "Open link in new tab"). If the navigation must wait on the current
3657 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3658 // will be updated when the BeforeUnload ack is received.
3659 const auto navigation_start_time = base::TimeTicks::Now();
3660
Camille Lamy5193caa2018-10-12 11:59:423661 std::unique_ptr<NavigationRequest> request =
3662 CreateNavigationRequestFromLoadParams(
3663 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143664 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393665 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3666 navigation_start_time);
clamy21718cc22018-06-13 13:34:243667
3668 // If the navigation couldn't start, return immediately and discard the
3669 // pending NavigationEntry.
3670 if (!request) {
3671 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363672 return nullptr;
clamy21718cc22018-06-13 13:34:243673 }
3674
Camille Lamy5193caa2018-10-12 11:59:423675#if DCHECK_IS_ON()
3676 // Safety check that NavigationRequest and NavigationEntry match.
3677 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3678#endif
3679
clamy21718cc22018-06-13 13:34:243680 // This call does not support re-entrancy. See http://crbug.com/347742.
3681 CHECK(!in_navigate_to_pending_entry_);
3682 in_navigate_to_pending_entry_ = true;
3683
arthursonzogni66f711c2019-10-08 14:40:363684 // It is not possible to delete the pending NavigationEntry while navigating
3685 // to it. Grab a reference to delay potential deletion until the end of this
3686 // function.
3687 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3688
Harkiran Bolariaba823e42021-05-21 18:30:363689 base::WeakPtr<NavigationHandle> created_navigation_handle(
3690 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053691 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243692
3693 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363694 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243695}
3696
clamyea99ea12018-05-28 13:54:233697void NavigationControllerImpl::HandleRendererDebugURL(
3698 FrameTreeNode* frame_tree_node,
3699 const GURL& url) {
3700 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243701 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3702 // the renderer process is not live, unless it is the initial navigation
3703 // of the tab.
clamyea99ea12018-05-28 13:54:233704 if (!IsInitialNavigation()) {
3705 DiscardNonCommittedEntries();
3706 return;
3707 }
Fergal Dalyecd3b0202020-06-25 01:57:373708 // The current frame is always a main frame. If IsInitialNavigation() is
3709 // true then there have been no navigations and any frames of this tab must
3710 // be in the same renderer process. If that has crashed then the only frame
3711 // that can be revived is the main frame.
3712 frame_tree_node->render_manager()
3713 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233714 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223715
3716 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3717 // notification, so set is loading to true here to properly surface it when
3718 // the renderer process is done handling the URL.
3719 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3720 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223721 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223722 }
clamyea99ea12018-05-28 13:54:233723 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3724}
3725
clamy21718cc22018-06-13 13:34:243726std::unique_ptr<NavigationEntryImpl>
3727NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3728 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423729 const LoadURLParams& params,
3730 bool override_user_agent,
3731 bool should_replace_current_entry,
3732 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393733 // Browser initiated navigations might not have a blob_url_loader_factory set
3734 // in params even if the navigation is to a blob URL. If that happens, lookup
3735 // the correct url loader factory to use here.
3736 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483737 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473738 // Resolve the blob URL in the storage partition associated with the target
3739 // frame. This is the storage partition the URL will be loaded in, and only
3740 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393741 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473742 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393743 }
3744
clamy21718cc22018-06-13 13:34:243745 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443746 // extra_headers in params are \n separated; navigation entries want \r\n.
3747 std::string extra_headers_crlf;
3748 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243749
3750 // For subframes, create a pending entry with a corresponding frame entry.
3751 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453752 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243753 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083754 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243755 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073756 params.url, absl::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213757 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3758 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393759 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163760 // a conversion of a new navigation into a reload, we will set the right
3761 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193762 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243763 } else {
3764 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173765 // If `node` is the outermost main frame, it rewrites a virtual url in order
3766 // to adjust the original input url if needed. For inner frames such as
3767 // fenced frames or subframes, they don't rewrite urls as the urls are not
3768 // input urls by users.
3769 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323770 scoped_refptr<SiteInstance> source_site_instance =
3771 params.source_site_instance;
3772 absl::optional<GURL> source_process_site_url = absl::nullopt;
3773 if (source_site_instance && source_site_instance->HasProcess()) {
3774 source_process_site_url =
3775 source_site_instance->GetProcess()->GetProcessLock().site_url();
3776 }
clamy21718cc22018-06-13 13:34:243777 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063778 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323779 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213780 params.transition_type, params.is_renderer_initiated,
3781 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3782 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243783 entry->set_source_site_instance(
3784 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3785 entry->SetRedirectChain(params.redirect_chain);
3786 }
3787
3788 // Set the FTN ID (only used in non-site-per-process, for tests).
3789 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243790 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423791 entry->SetIsOverridingUserAgent(override_user_agent);
3792 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543793 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243794
clamy21718cc22018-06-13 13:34:243795 switch (params.load_type) {
3796 case LOAD_TYPE_DEFAULT:
3797 break;
3798 case LOAD_TYPE_HTTP_POST:
3799 entry->SetHasPostData(true);
3800 entry->SetPostData(params.post_data);
3801 break;
3802 case LOAD_TYPE_DATA:
3803 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3804 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283805#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243806 entry->SetDataURLAsString(params.data_url_as_string);
3807#endif
3808 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3809 break;
clamy21718cc22018-06-13 13:34:243810 }
3811
3812 // TODO(clamy): NavigationEntry is meant for information that will be kept
3813 // after the navigation ended and therefore is not appropriate for
3814 // started_from_context_menu. Move started_from_context_menu to
3815 // NavigationUIData.
3816 entry->set_started_from_context_menu(params.started_from_context_menu);
3817
3818 return entry;
3819}
3820
clamyea99ea12018-05-28 13:54:233821std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423822NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3823 FrameTreeNode* node,
3824 const LoadURLParams& params,
3825 bool override_user_agent,
3826 bool should_replace_current_entry,
3827 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143828 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423829 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573830 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393831 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223832 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493833 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453834 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583835 bool is_container_initiated,
3836 absl::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573837 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283838 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533839 // All renderer-initiated navigations must have an initiator_origin.
3840 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513841
Camille Lamy5193caa2018-10-12 11:59:423842 GURL url_to_load;
3843 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323844
Camille Lamy2baa8022018-10-19 16:43:173845 // For main frames, rewrite the URL if necessary and compute the virtual URL
3846 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263847 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423848 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173849 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423850 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423851
Camille Lamy2baa8022018-10-19 16:43:173852 // For DATA loads, override the virtual URL.
3853 if (params.load_type == LOAD_TYPE_DATA)
3854 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423855
Camille Lamy2baa8022018-10-19 16:43:173856 if (virtual_url.is_empty())
3857 virtual_url = url_to_load;
3858
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573859 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283860
Aran Gilman249eb122019-12-02 23:32:463861 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3862 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3863 // return different results, leading to a different URL in the
3864 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3865 // pending NavigationEntry, as we'll only make one call to
3866 // RewriteUrlForNavigation.
3867 VLOG_IF(1, (url_to_load != frame_entry->url()))
3868 << "NavigationRequest and FrameEntry have different URLs: "
3869 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283870
Camille Lamy2baa8022018-10-19 16:43:173871 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423872 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173873 // NavigationRequest.
3874 } else {
3875 url_to_load = params.url;
3876 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243877 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173878 }
Camille Lamy5193caa2018-10-12 11:59:423879
Ehsan Karamad44fc72112019-02-26 18:15:473880 if (node->render_manager()->is_attaching_inner_delegate()) {
3881 // Avoid starting any new navigations since this node is now preparing for
3882 // attaching an inner delegate.
3883 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203884 }
Camille Lamy5193caa2018-10-12 11:59:423885
Alex Moshchuk99242832023-05-22 17:21:443886 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:423887 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:443888 }
Camille Lamy5193caa2018-10-12 11:59:423889
danakjd83d706d2020-11-25 22:11:123890 // Look for a pending commit that is to another document in this
3891 // FrameTreeNode. If one exists, then the last committed URL will not be the
3892 // current URL by the time this navigation commits.
3893 bool has_pending_cross_document_commit =
3894 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213895 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123896
Minggang Wangb9f3fa92021-07-01 15:30:313897 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493898 /*old_url=*/node->current_url(),
3899 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3900 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133901 /*is_same_document_history_load=*/false,
3902 is_embedder_initiated_fenced_frame_navigation,
3903 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423904
3905 // Create the NavigationParams based on |params|.
3906
Hiroki Nakagawa4ed61282021-06-18 05:37:233907 bool is_view_source_mode = entry->IsViewSourceMode();
3908 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293909
Antonio Sartori6984c742021-08-26 08:03:413910 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:293911
Hiroki Nakagawa4ed61282021-06-18 05:37:233912 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293913 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253914 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293915
Minggang Wangb9f3fa92021-07-01 15:30:313916 blink::mojom::CommonNavigationParamsPtr common_params =
3917 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:213918 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513919 blink::mojom::Referrer::New(params.referrer.url,
3920 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213921 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513922 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393923 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513924 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143925 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413926 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273927 false /* has_text_fragment_token */,
3928 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3929 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513930 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:053931 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423932
Minggang Wangb9f3fa92021-07-01 15:30:313933 blink::mojom::CommitNavigationParamsPtr commit_params =
3934 blink::mojom::CommitNavigationParams::New(
Rakina Zata Amnic7367852022-11-07 17:10:403935 absl::nullopt,
Ari Chivukula43d2cf82023-01-24 03:16:073936 // The correct storage key and session storage key will be computed
3937 // before committing the navigation.
3938 blink::StorageKey(), blink::StorageKey(), override_user_agent,
3939 params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323940 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503941 std::vector<net::RedirectInfo>(), params.post_content_type,
3942 common_params->url, common_params->method,
3943 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313944 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133945 entry->GetSubframeUniqueNames(node),
3946 /*intended_as_new_entry=*/true,
3947 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143948 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3949 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:133950 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313951 params.should_clear_history_list,
3952 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223953 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:133954 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:513955 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283956#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:133957 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143958#endif
Yoav Weiss8c573952022-11-17 17:35:133959 /*is_browser_initiated=*/!params.is_renderer_initiated,
Yoav Weiss8c573952022-11-17 17:35:133960 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:073961 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133962 /*force_enabled_origin_trials=*/std::vector<std::string>(),
3963 /*origin_agent_cluster=*/false,
3964 /*origin_agent_cluster_left_as_default=*/true,
3965 /*enabled_client_hints=*/
3966 std::vector<network::mojom::WebClientHintsType>(),
3967 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
3968 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:013969 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:133970 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:583971 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:133972 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:133973 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:283974 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:133975 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:443976 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:423977 network::mojom::NavigationDeliveryType::kDefault,
Yoav Weiss8c573952022-11-17 17:35:133978 /*view_transition_state=*/absl::nullopt,
sbinglera07ae732022-12-02 20:49:053979 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
3980 /*modified_runtime_features=*/
Garrett Tanzer29de7112022-12-06 21:26:323981 base::flat_map<::blink::mojom::RuntimeFeatureState, bool>(),
Yuzu Saijo29f96ca92022-12-08 04:54:123982 /*fenced_frame_properties=*/absl::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:053983 /*not_restored_reasons=*/nullptr,
Arthur Hemeryd51484b2023-06-02 15:50:003984 /*load_with_storage_access=*/false,
3985 /*browsing_context_group_info=*/absl::nullopt);
Xiaohan Wang7f8052e02022-01-14 18:44:283986#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423987 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143988 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423989 }
3990#endif
3991
Lucas Furukawa Gadania9c45682019-07-31 22:05:143992 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:073993 commit_params->navigation_timing->system_entropy_at_navigation_start =
3994 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
3995 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:423996
Camille Lamy5193caa2018-10-12 11:59:423997 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3998 std::string extra_headers_crlf;
3999 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094000
Alex Moshchuk9321e6a2022-12-07 21:58:314001 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144002 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084003 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094004 params.initiator_frame_token, params.initiator_process_id,
4005 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214006 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294007 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454008 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584009 is_container_initiated, embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:094010 navigation_request->set_from_download_cross_origin_redirect(
4011 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554012 navigation_request->set_force_new_browsing_instance(
4013 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:094014 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424015}
4016
4017std::unique_ptr<NavigationRequest>
4018NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234019 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574020 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234021 FrameNavigationEntry* frame_entry,
4022 ReloadType reload_type,
4023 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434024 bool is_history_navigation_in_new_child_frame,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334025 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
4026 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:134027 absl::optional<blink::scheduler::TaskAttributionId>
4028 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344029 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234030 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434031 // We should never navigate to an existing initial NavigationEntry that is the
4032 // initial NavigationEntry for the initial empty document that hasn't been
4033 // overridden by the synchronous about:blank commit, to preserve previous
4034 // behavior where trying to reload when the main frame is on the initial empty
4035 // document won't result in a navigation.
4036 // See also https://crbug.com/1277414.
4037 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324038
clamyea99ea12018-05-28 13:54:234039 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:014040 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574041 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:234042 // We may have been redirected when navigating to the current URL.
4043 // Use the URL the user originally intended to visit as signaled by the
4044 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:014045 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574046 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:234047 dest_referrer = Referrer();
clamyea99ea12018-05-28 13:54:234048 }
4049
Ehsan Karamad44fc72112019-02-26 18:15:474050 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4051 // Avoid starting any new navigations since this node is now preparing for
4052 // attaching an inner delegate.
4053 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204054 }
4055
Alex Moshchuk99242832023-05-22 17:21:444056 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4057 dest_url)) {
clamyea99ea12018-05-28 13:54:234058 return nullptr;
4059 }
4060
clamyea99ea12018-05-28 13:54:234061 // This will be used to set the Navigation Timing API navigationStart
4062 // parameter for browser navigations in new tabs (intents, tabs opened through
4063 // "Open link in new tab"). If the navigation must wait on the current
4064 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4065 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074066
clamyea99ea12018-05-28 13:54:234067 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074068 const auto navigation_start_system_entropy =
4069 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4070 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234071
danakjd83d706d2020-11-25 22:11:124072 // Look for a pending commit that is to another document in this
4073 // FrameTreeNode. If one exists, then the last committed URL will not be the
4074 // current URL by the time this navigation commits.
4075 bool has_pending_cross_document_commit =
4076 frame_tree_node->render_manager()
4077 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494078 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214079 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124080
Minggang Wangb9f3fa92021-07-01 15:30:314081 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124082 /*old_url=*/frame_tree_node->current_url(),
4083 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:494084 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494085 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134086 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494087 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424088
4089 // A form submission may happen here if the navigation is a
4090 // back/forward/reload navigation that does a form resubmission.
4091 scoped_refptr<network::ResourceRequestBody> request_body;
4092 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:504093 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
4094 // entry. This way, it could be directly retrieved here. Right now, it is only
4095 // partially recovered when request.method == "POST" and request.body exists.
4096 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424097 if (frame_entry->method() == "POST") {
4098 request_body = frame_entry->GetPostData(&post_content_type);
4099 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304100 post_content_type = std::string(
4101 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504102 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424103 }
4104
4105 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314106 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514107 entry->ConstructCommonNavigationParams(
4108 *frame_entry, request_body, dest_url,
4109 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384110 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534111 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514112 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554113 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424114
4115 // TODO(clamy): |intended_as_new_entry| below should always be false once
4116 // Reload no longer leads to this being called for a pending NavigationEntry
4117 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314118 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144119 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404120 *frame_entry, common_params->url, common_params->method,
4121 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144122 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534123 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484124 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134125 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074126 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144127 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074128 commit_params->navigation_timing->system_entropy_at_navigation_start =
4129 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4130 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Camille Lamy5193caa2018-10-12 11:59:424131
W. James MacLeanb7d6092682022-10-05 15:23:264132 if (common_params->url.IsAboutSrcdoc()) {
4133 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4134 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594135 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264136 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334137 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314138 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144139 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434140 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334141 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4142 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
4143 absl::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294144 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4145 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474146 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234147}
4148
[email protected]d202a7c2012-01-04 07:53:474149void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214150 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274151 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404152
Takashi Toyoshimaea534ef22021-07-21 03:27:594153 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404154 // location bar will have up-to-date information about the security style
4155 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134156 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404157
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374158 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574159 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:464160
[email protected]b0f724c2013-09-05 04:21:134161 // TODO(avi): Remove. http://crbug.com/170921
4162 NotificationDetails notification_details =
4163 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154164 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4165 Source<NavigationController>(this),
4166 notification_details);
initial.commit09911bf2008-07-26 23:55:294167}
4168
initial.commit09911bf2008-07-26 23:55:294169// static
[email protected]d202a7c2012-01-04 07:53:474170size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234171 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154172 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214173 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234174}
4175
[email protected]d202a7c2012-01-04 07:53:474176void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224177 if (is_active && needs_reload_)
4178 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294179}
4180
[email protected]d202a7c2012-01-04 07:53:474181void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034182 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4183 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294184 if (!needs_reload_)
4185 return;
4186
Bo Liucdfa4b12018-11-06 00:21:444187 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4188 needs_reload_type_);
4189
initial.commit09911bf2008-07-26 23:55:294190 // Calling Reload() results in ignoring state, and not loading.
4191 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4192 // cached state.
avicc872d7242015-08-19 21:26:344193 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134194 NavigateToExistingPendingEntry(
4195 ReloadType::NONE,
4196 /*initiator_rfh=*/nullptr,
4197 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4198 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454199 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434200 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274201 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344202 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134203 NavigateToExistingPendingEntry(
4204 ReloadType::NONE,
4205 /*initiator_rfh=*/nullptr,
4206 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4207 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344208 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434209 // We should never navigate to an existing initial NavigationEntry that is
4210 // the initial NavigationEntry for the initial empty document that hasn't
4211 // been overridden by the synchronous about:blank commit, to preserve
4212 // legacy behavior where trying to reload when the main frame is on the
4213 // initial empty document won't result in a navigation. See also
4214 // https://crbug.com/1277414. If there is something to reload, the
4215 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4216 // it here.
avicc872d7242015-08-19 21:26:344217 needs_reload_ = false;
4218 }
initial.commit09911bf2008-07-26 23:55:294219}
4220
Kevin McNeeccca6172021-10-19 17:11:144221base::WeakPtr<NavigationHandle>
4222NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364223 RenderFrameHost* render_frame_host,
4224 const GURL& url,
4225 const std::string& error_page_html,
4226 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134227 RenderFrameHostImpl* rfhi =
4228 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584229
4230 // Only active documents can load post-commit error pages:
4231 // - If the document is in pending deletion, the browser already committed to
4232 // destroying this RenderFrameHost so ignore loading the error page.
4233 // - If the document is in back-forward cache, it's not allowed to navigate as
4234 // it should remain frozen. Ignore the request and evict the document from
4235 // back-forward cache.
4236 // - If the document is prerendering, it can navigate but when loading error
4237 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114238 if (rfhi->IsInactiveAndDisallowActivation(
4239 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144240 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114241 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584242
Rakina Zata Amni919b7922020-12-11 09:03:134243 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414244
Minggang Wangb9f3fa92021-07-01 15:30:314245 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434246 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594247 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4248 // the frame actually committed (e.g. iframe with "src" set to a
4249 // slow-responding URL). We should rewrite the URL to about:blank in this
4250 // case, as the renderer will only think a page is an error page if it has a
4251 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134252 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314253 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434254 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334255 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414256
Mike Jacksone2aa7af2023-05-17 06:45:074257 commit_params->navigation_timing->system_entropy_at_navigation_start =
4258 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4259 node, blink::mojom::SystemEntropy::kNormal);
4260
arthursonzogni70ac7302020-05-28 08:49:054261 // Error pages have a fully permissive FramePolicy.
4262 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4263 // error pages.
4264 commit_params->frame_policy = blink::FramePolicy();
4265
John Delaney131ad362019-08-08 21:57:414266 std::unique_ptr<NavigationRequest> navigation_request =
4267 NavigationRequest::CreateBrowserInitiated(
4268 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094269 false /* was_opener_suppressed */, "" /* extra_headers */,
4270 nullptr /* frame_entry */, nullptr /* entry */,
4271 false /* is_form_submission */, nullptr /* navigation_ui_data */,
4272 absl::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364273 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414274 navigation_request->set_net_error(error);
Charlie Reis09952ee2022-12-08 16:35:074275 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414276 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144277
4278 // Calling BeginNavigation may destroy the NavigationRequest.
4279 base::WeakPtr<NavigationRequest> created_navigation_request(
4280 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414281 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144282 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414283}
4284
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574285void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214286 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094287 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154288 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144289 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294290}
4291
[email protected]d202a7c2012-01-04 07:53:474292void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364293 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474294 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4295 // represent a no-committed-entry state.
4296 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364297 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474298 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4299 // if `entries_` contains pre-existing entries from the NavigationController
4300 // before restore, which would not be removed and will be at the front of the
4301 // entries list, causing the index to be off by the amount of pre-existing
4302 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294303 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294304}
[email protected]765b35502008-08-21 00:51:204305
arthursonzogni69a6a1b2019-09-17 09:23:004306void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004307 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4308}
4309
4310void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4311 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474312 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104313 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4314 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294315 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474316 return;
Michael Thiessenc5676d22019-09-25 22:32:104317 }
avi45a72532015-04-07 21:01:454318 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314319
4320 if (!delegate_)
4321 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374322 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484323}
4324
avi7c6f35e2015-05-08 17:52:384325int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4326 int nav_entry_id) const {
4327 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4328 if (entries_[i]->GetUniqueID() == nav_entry_id)
4329 return i;
4330 }
4331 return -1;
4332}
4333
[email protected]d202a7c2012-01-04 07:53:474334void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574335 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254336 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574337 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574338 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4339 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254340 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374341 // Normally, cloning a NavigationEntryImpl results in sharing
4342 // FrameNavigationEntries between the original and the clone. However, when
4343 // cloning from a different NavigationControllerImpl, we want to fork the
4344 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374345 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574346 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254347 }
Rakina Zata Amnie2d31312022-11-18 03:38:454348 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274349 DCHECK(pending_entry_index_ == -1 ||
4350 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254351}
[email protected]c5b88d82012-10-06 17:03:334352
4353void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184354 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334355 get_timestamp_callback_ = get_timestamp_callback;
4356}
[email protected]8ff00d72012-10-23 19:12:214357
Shivani Sharmaffb32b82019-04-09 16:58:474358// History manipulation intervention:
4359void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474360 bool replace_entry,
4361 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404362 bool is_renderer_initiated,
4363 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454364 // Note that for a subframe, previous_document_was_activated is true if the
4365 // gesture happened in any subframe (propagated to main frame) or in the main
4366 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474367 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274368 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474369 return;
4370 }
4371 if (last_committed_entry_index_ == -1)
4372 return;
4373
Shivani Sharmac4cc8922019-04-18 03:11:174374 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474375
Alexander Timine3ec4192020-04-20 16:39:404376 // Log UKM with the URL we are navigating away from.
4377 ukm::builders::HistoryManipulationIntervention(
4378 previous_page_load_ukm_source_id)
4379 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474380}
4381
Shivani Sharmac4cc8922019-04-18 03:11:174382void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4383 int reference_index,
4384 bool skippable) {
4385 auto* reference_entry = GetEntryAtIndex(reference_index);
4386 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4387
4388 int64_t document_sequence_number =
4389 reference_entry->root_node()->frame_entry->document_sequence_number();
4390 for (int index = 0; index < GetEntryCount(); index++) {
4391 auto* entry = GetEntryAtIndex(index);
4392 if (entry->root_node()->frame_entry->document_sequence_number() ==
4393 document_sequence_number) {
4394 entry->set_should_skip_on_back_forward_ui(skippable);
4395 }
4396 }
4397}
4398
arthursonzogni66f711c2019-10-08 14:40:364399std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4400NavigationControllerImpl::ReferencePendingEntry() {
4401 DCHECK(pending_entry_);
4402 auto pending_entry_ref =
4403 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4404 pending_entry_refs_.insert(pending_entry_ref.get());
4405 return pending_entry_ref;
4406}
4407
4408void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4409 // Ignore refs that don't correspond to the current pending entry.
4410 auto it = pending_entry_refs_.find(ref);
4411 if (it == pending_entry_refs_.end())
4412 return;
4413 pending_entry_refs_.erase(it);
4414
4415 if (!pending_entry_refs_.empty())
4416 return;
4417
4418 // The pending entry may be deleted before the last PendingEntryRef.
4419 if (!pending_entry_)
4420 return;
4421
4422 // We usually clear the pending entry when the matching NavigationRequest
4423 // fails, so that an arbitrary URL isn't left visible above a committed page.
4424 //
4425 // However, we do preserve the pending entry in some cases, such as on the
4426 // initial navigation of an unmodified blank tab. We also allow the delegate
4427 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4428 // user edit the URL and try again. This may be useful in cases that the
4429 // committed page cannot be attacker-controlled. In these cases, we still
4430 // allow the view to clear the pending entry and typed URL if the user
4431 // requests (e.g., hitting Escape with focus in the address bar).
4432 //
4433 // Do not leave the pending entry visible if it has an invalid URL, since this
4434 // might be formatted in an unexpected or unsafe way.
4435 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364436 bool should_preserve_entry =
4437 (pending_entry_ == GetVisibleEntry()) &&
4438 pending_entry_->GetURL().is_valid() &&
4439 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4440 if (should_preserve_entry)
4441 return;
4442
4443 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374444 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364445}
4446
Titouan Rigoudy6ec70402021-02-02 15:42:194447std::unique_ptr<PolicyContainerPolicies>
4448NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394449 RenderFrameHostImpl* rfh,
4450 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174451 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394452 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454453 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394454 FrameNavigationEntry* previous_frame_entry =
4455 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4456
4457 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4458 // ensure we always have a FrameNavigationEntry here.
4459 if (!previous_frame_entry)
4460 return nullptr;
4461
Titouan Rigoudy6ec70402021-02-02 15:42:194462 const PolicyContainerPolicies* previous_policies =
4463 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394464
Titouan Rigoudy6ec70402021-02-02 15:42:194465 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394466 return nullptr;
4467
4468 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234469 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394470 }
4471
Titouan Rigoudy72f892d2022-05-02 18:21:234472 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394473}
4474
Hayato Ito2c8c08d02021-06-23 03:38:434475void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504476 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434477 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4478 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4479 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504480
4481 auto callback = base::BindRepeating(
4482 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4483 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4484 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4485 }
4486 },
Hayato Ito2c8c08d02021-06-23 03:38:434487 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034488 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504489}
4490
4491void NavigationControllerImpl::DidAccessInitialMainDocument() {
4492 // We may have left a failed browser-initiated navigation in the address bar
4493 // to let the user edit it and try again. Clear it now that content might
4494 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034495 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504496 DiscardPendingEntry(false);
4497
4498 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374499 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504500}
4501
4502void NavigationControllerImpl::UpdateStateForFrame(
4503 RenderFrameHostImpl* rfhi,
4504 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564505 OPTIONAL_TRACE_EVENT1("content",
4506 "NavigationControllerImpl::UpdateStateForFrame",
4507 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504508 // The state update affects the last NavigationEntry associated with the given
4509 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4510 // in the case of an UpdateState from a frame being swapped out). We track
4511 // which entry this is in the RenderFrameHost's nav_entry_id.
4512 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4513 if (!entry)
4514 return;
4515
4516 FrameNavigationEntry* frame_entry =
4517 entry->GetFrameEntry(rfhi->frame_tree_node());
4518 if (!frame_entry)
4519 return;
4520
4521 // The SiteInstance might not match if we do a cross-process navigation with
4522 // replacement (e.g., auto-subframe), in which case the swap out of the old
4523 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4524 // has already been replaced and destroyed.
4525 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4526 return;
4527
4528 if (page_state == frame_entry->page_state())
4529 return; // Nothing to update.
4530
4531 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4532
4533 // The document_sequence_number and item_sequence_number recorded in the
4534 // FrameNavigationEntry should not differ from the one coming with the update,
4535 // since it must come from the same document. Do not update it if a difference
4536 // is detected, as this indicates that |frame_entry| is not the correct one.
4537 blink::ExplodedPageState exploded_state;
4538 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4539 return;
4540
4541 if (exploded_state.top.document_sequence_number !=
4542 frame_entry->document_sequence_number() ||
4543 exploded_state.top.item_sequence_number !=
4544 frame_entry->item_sequence_number()) {
4545 return;
4546 }
4547
4548 frame_entry->SetPageState(page_state);
4549 NotifyEntryChanged(entry);
4550}
4551
Domenic Denicolacd30f5f82022-03-16 21:48:014552std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4553NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574554 Direction direction,
4555 int entry_index,
4556 const url::Origin& pending_origin,
4557 FrameTreeNode* node,
4558 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304559 int64_t pending_item_sequence_number,
4560 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014561 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454562 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174563 // Don't process the initial entry.
4564 DCHECK_EQ(GetEntryCount(), 1);
4565 return entries;
4566 }
Nate Chapind1fe3612021-04-16 20:45:574567 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304568 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574569 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4570 i += offset) {
4571 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414572 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574573 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014574 // An entry should only appear in the navigation API entries if it is for
4575 // the same origin as the document being committed. Check the committed
4576 // origin, or if that is not available (during restore), check against the
4577 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414578 url::Origin frame_entry_origin =
4579 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4580 frame_entry->url(),
4581 frame_entry->initiator_origin().value_or(url::Origin())));
4582 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574583 break;
4584 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4585 continue;
4586 blink::ExplodedPageState exploded_page_state;
4587 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4588 &exploded_page_state)) {
4589 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304590
4591 // If the document represented by this FNE hid its full url from appearing
4592 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014593 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304594 // document).
4595 std::u16string url;
4596 if (pending_document_sequence_number ==
4597 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574598 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304599 url = frame_state.url_string.value_or(std::u16string());
4600 }
4601
Domenic Denicolacd30f5f82022-03-16 21:48:014602 blink::mojom::NavigationApiHistoryEntryPtr entry =
4603 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574604 frame_state.navigation_api_key.value_or(std::u16string()),
4605 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094606 frame_state.item_sequence_number,
4607 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304608 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174609
Nate Chapin63db0d12022-01-20 22:03:304610 DCHECK(entry->url.empty() ||
4611 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574612 entries.push_back(std::move(entry));
4613 previous_item_sequence_number = frame_entry->item_sequence_number();
4614 }
4615 }
4616 // If |entries| was constructed by iterating backwards from
4617 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4618 // earliest-at-the-front. Reverse it.
4619 if (direction == Direction::kBack)
4620 std::reverse(entries.begin(), entries.end());
4621 return entries;
4622}
4623
Domenic Denicolacd30f5f82022-03-16 21:48:014624blink::mojom::NavigationApiHistoryEntryArraysPtr
4625NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554626 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574627 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404628 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444629 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404630 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574631
Nate Chapind1fe3612021-04-16 20:45:574632 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554633 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574634
Nate Chapine82339d02022-05-03 23:48:254635 // NOTE: |entry_index| is the index where this entry will commit if no
4636 // modifications are made between now and DidCommitNavigation. This is used to
4637 // walk |entries_| and determine which entries should be exposed by the
4638 // navigation API. It is important to calculate this correctly, because blink
4639 // will cancel a same-document history commit if it's not present in the
4640 // entries blink knows about.
4641 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574642 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304643 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254644 bool will_create_new_entry = false;
4645 if (GetPendingEntryIndex() != -1) {
4646 entry_index = GetPendingEntryIndex();
4647 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4648 pending_item_sequence_number = frame_entry->item_sequence_number();
4649 pending_document_sequence_number =
4650 frame_entry->document_sequence_number();
4651 }
4652 } else if (request &&
4653 !NavigationTypeUtils::IsReload(
4654 request->common_params().navigation_type) &&
4655 !NavigationTypeUtils::IsHistory(
4656 request->common_params().navigation_type) &&
4657 !request->common_params().should_replace_current_entry &&
4658 !request->common_params()
4659 .is_history_navigation_in_new_child_frame) {
4660 will_create_new_entry = true;
4661 entry_index = GetLastCommittedEntryIndex() + 1;
4662 // Don't set pending_item_sequence_number or
4663 // pending_document_sequence_number in this case - a new unique isn/dsn will
4664 // be calculated in the renderer later.
4665 } else if (GetLastCommittedEntryIndex() != -1) {
4666 entry_index = GetLastCommittedEntryIndex();
4667 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574668 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304669 pending_document_sequence_number =
4670 frame_entry->document_sequence_number();
4671 }
Nate Chapind1fe3612021-04-16 20:45:574672 }
4673
Domenic Denicolacd30f5f82022-03-16 21:48:014674 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254675 if (entry_index == -1) {
4676 // TODO(rakina): Exit early when there is no last committed entry.
4677 // Remove when InitialNavigationEntry ships.
4678 return entry_arrays;
4679 }
4680
Domenic Denicolacd30f5f82022-03-16 21:48:014681 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574682 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374683 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574684
4685 // Don't populate forward entries if they will be truncated by a new entry.
4686 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014687 entry_arrays->forward_entries =
4688 PopulateSingleNavigationApiHistoryEntryVector(
4689 Direction::kForward, entry_index, pending_origin, node,
4690 site_instance.get(), pending_item_sequence_number,
4691 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574692 }
Nate Chapin4e657a472022-02-06 03:38:374693 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574694}
4695
Nate Chapinfbfe5af2021-06-10 17:22:084696NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574697NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084698 FrameNavigationEntry* current_entry,
4699 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574700 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084701 if (!target_entry || !target_entry->committed_origin())
4702 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084703 if (!current_entry->committed_origin()->IsSameOriginWith(
4704 *target_entry->committed_origin())) {
4705 return HistoryNavigationAction::kStopLooking;
4706 }
4707
4708 // NOTE: We don't actually care between kSameDocument and
4709 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574710 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084711 return HistoryNavigationAction::kDifferentDocument;
4712 return HistoryNavigationAction::kKeepLooking;
4713}
4714
Domenic Denicolacc094fb2022-03-16 23:40:574715void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204716 RenderFrameHostImpl* initiator_rfh,
Yoav Weissa7449c3b2022-11-22 15:15:144717 absl::optional<blink::scheduler::TaskAttributionId>
4718 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574719 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204720 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084721 FrameNavigationEntry* current_entry =
4722 GetLastCommittedEntry()->GetFrameEntry(node);
4723 if (!current_entry)
4724 return;
4725
Yoav Weiss8c573952022-11-17 17:35:134726 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4727 // when `navigation.traverseTo()` is called.
4728
Nate Chapinfbfe5af2021-06-10 17:22:084729 // We want to find the nearest matching entry that is contiguously
4730 // same-instance and same-origin. Check back first, then forward.
4731 // TODO(japhet): Link spec here once it exists.
4732 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574733 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084734 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4735 if (result == HistoryNavigationAction::kStopLooking)
4736 break;
4737 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144738 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084739 return;
4740 }
4741 }
4742 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574743 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084744 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4745 if (result == HistoryNavigationAction::kStopLooking)
4746 break;
4747 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144748 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084749 return;
4750 }
4751 }
Nate Chapinbf682fa32022-09-26 22:41:204752
4753 // If we fall through to here, a matching NavigationEntry couldn't be found.
4754 // Notify the renderer that the navigation was cancelled.
4755 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4756 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084757}
4758
Domenic Denicolacc094fb2022-03-16 23:40:574759bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304760 network::mojom::ReferrerPolicy referrer_policy) {
4761 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4762 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4763}
4764
shivanigithubf405bf0d2021-11-05 17:58:334765bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4766 const FrameTreeNode* frame_tree_node) const {
4767 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4768 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544769 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Ali Hijazid87307d2022-11-07 20:15:034770 return frame_tree_->is_prerendering() ||
shivanigithubf405bf0d2021-11-05 17:58:334771 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544772}
4773
Julie Jeongeun Kim0e242242022-11-30 10:45:094774void NavigationControllerImpl::DidChangeReferrerPolicy(
4775 FrameTreeNode* node,
4776 network::mojom::ReferrerPolicy referrer_policy) {
4777 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4778 if (!entry)
4779 return;
4780
4781 // The FrameNavigationEntry may want to change whether to protect its url
4782 // in the navigation API when the referrer policy changes.
4783 entry->set_protect_url_in_navigation_api(
4784 ShouldProtectUrlInNavigationApi(referrer_policy));
4785}
4786
[email protected]8ff00d72012-10-23 19:12:214787} // namespace content