blob: d4a7c6772f45841392d404ede186cae4af617467 [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"
Kunihiko Sakamoto346a74e2021-03-10 08:57:4881#include "content/browser/web_package/subresource_web_bundle_navigation_info.h"
Camille Lamy5193caa2018-10-12 11:59:4282#include "content/common/content_constants_internal.h"
Nate Chapind1fe3612021-04-16 20:45:5783#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5184#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1185#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1986#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1187#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4688#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0089#include "content/public/browser/navigation_details.h"
[email protected]7f6f44c2011-12-14 13:23:3890#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1691#include "content/public/browser/notification_types.h"
Lei Zhang96031532019-10-10 19:05:4792#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5893#include "content/public/browser/render_widget_host.h"
94#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1095#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3496#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1997#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3898#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1099#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:47100#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:43101#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59102#include "media/base/mime_util.h"
Arthur Sonzogni620cec62018-12-13 13:08:57103#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18104#include "services/metrics/public/cpp/ukm_builders.h"
105#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17106#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37107#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44108#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58109#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39110#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30111#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21112#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06113#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43114#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50115#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31116#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51117#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
sbinglera07ae732022-12-02 20:49:05118#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature_state.mojom.h"
[email protected]cca6f392014-05-28 21:32:26119#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29120
[email protected]8ff00d72012-10-23 19:12:21121namespace content {
[email protected]e9ba4472008-09-14 15:42:43122namespace {
123
Charlie Reis951f43372023-05-05 00:30:07124// TODO(https://crbug.com/1439948): Remove this base::Feature kill switch once
125// the feature safely rolls out.
126BASE_FEATURE(kUpdateSessionHistoryIndexBeforeNavigationStateChanged,
127 "UpdateSessionHistoryIndexBeforeNavigationStateChanged",
128 base::FEATURE_ENABLED_BY_DEFAULT);
129
[email protected]e9ba4472008-09-14 15:42:43130// Invoked when entries have been pruned, or removed. For example, if the
131// current entries are [google, digg, yahoo], with the current entry google,
132// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47133void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50134 int index,
[email protected]c12bf1a12008-09-17 16:28:49135 int count) {
[email protected]8ff00d72012-10-23 19:12:21136 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50137 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49138 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14139 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43140}
141
[email protected]e9ba4472008-09-14 15:42:43142// Configure all the NavigationEntries in entries for restore. This resets
143// the transition type to reload and makes sure the content state isn't empty.
144void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57145 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48146 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47147 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43148 // Use a transition type of reload so that we don't incorrectly increase
149 // the typed count.
Lei Zhang96031532019-10-10 19:05:47150 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
151 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43152 }
153}
154
[email protected]bf70edce2012-06-20 22:32:22155// Determines whether or not we should be carrying over a user agent override
156// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57157bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22158 return last_entry && last_entry->GetIsOverridingUserAgent();
159}
160
Camille Lamy5193caa2018-10-12 11:59:42161// Determines whether to override user agent for a navigation.
162bool ShouldOverrideUserAgent(
163 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57164 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42165 switch (override_user_agent) {
166 case NavigationController::UA_OVERRIDE_INHERIT:
167 return ShouldKeepOverride(last_committed_entry);
168 case NavigationController::UA_OVERRIDE_TRUE:
169 return true;
170 case NavigationController::UA_OVERRIDE_FALSE:
171 return false;
Camille Lamy5193caa2018-10-12 11:59:42172 }
173 NOTREACHED();
174 return false;
175}
176
Rakina Zata Amni312822d72021-06-04 16:13:37177// Returns true if this navigation should be treated as a reload. For e.g.
clamy0a656e42018-02-06 18:18:28178// navigating to the last committed url via the address bar or clicking on a
Rakina Zata Amni312822d72021-06-04 16:13:37179// link which results in a navigation to the last committed URL (but wasn't
180// converted to do a replacement navigation in the renderer), etc.
Fergal Daly766177d2020-07-07 07:54:04181// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
182// |base_url_for_data_url|, |transition_type| correspond to the new navigation
183// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
184// navigation that committed.
185bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
186 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57187 const GURL& virtual_url,
188 const GURL& base_url_for_data_url,
189 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57190 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37191 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57192 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37193 // Navigations intended to do a replacement shouldn't be converted to do a
194 // reload.
195 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28196 return false;
clamy0a656e42018-02-06 18:18:28197 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45198 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55199 return false;
200
arthursonzogni7a8243682017-12-14 16:41:42201 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28202 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42203 return false;
204
ananta3bdd8ae2016-12-22 17:11:55205 // We treat (PAGE_TRANSITION_RELOAD | PAGE_TRANSITION_FROM_ADDRESS_BAR),
206 // PAGE_TRANSITION_TYPED or PAGE_TRANSITION_LINK transitions as navigations
207 // which should be treated as reloads.
clamy0a656e42018-02-06 18:18:28208 bool transition_type_can_be_converted = false;
209 if (ui::PageTransitionCoreTypeIs(transition_type,
210 ui::PAGE_TRANSITION_RELOAD) &&
211 (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)) {
212 transition_type_can_be_converted = true;
ananta3bdd8ae2016-12-22 17:11:55213 }
clamy0a656e42018-02-06 18:18:28214 if (ui::PageTransitionCoreTypeIs(transition_type,
ananta3bdd8ae2016-12-22 17:11:55215 ui::PAGE_TRANSITION_TYPED)) {
clamy0a656e42018-02-06 18:18:28216 transition_type_can_be_converted = true;
217 }
218 if (ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_LINK))
219 transition_type_can_be_converted = true;
220 if (!transition_type_can_be_converted)
221 return false;
222
223 // This check is required for cases like view-source:, etc. Here the URL of
224 // the navigation entry would contain the url of the page, while the virtual
225 // URL contains the full URL including the view-source prefix.
226 if (virtual_url != last_committed_entry->GetVirtualURL())
227 return false;
228
Fergal Daly766177d2020-07-07 07:54:04229 // Check that the URLs match.
230 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
231 // If there's no frame entry then by definition the URLs don't match.
232 if (!frame_entry)
233 return false;
234
235 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28236 return false;
237
238 // This check is required for Android WebView loadDataWithBaseURL. Apps
239 // can pass in anything in the base URL and we need to ensure that these
240 // match before classifying it as a reload.
241 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
242 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
243 return false;
ananta3bdd8ae2016-12-22 17:11:55244 }
245
clamy0a656e42018-02-06 18:18:28246 // Skip entries with SSL errors.
247 if (last_committed_entry->ssl_error())
248 return false;
249
250 // Don't convert to a reload when the last navigation was a POST or the new
251 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04252 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28253 return false;
254
255 return true;
ananta3bdd8ae2016-12-22 17:11:55256}
257
Anton Bikineevf62d1bf2021-05-15 17:56:07258absl::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12259 const mojom::DidCommitProvisionalLoadParams& params,
260 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32261 // Error pages commit in an opaque origin, yet have the real URL that resulted
262 // in an error as the |params.url|. Since successful reload of an error page
263 // should commit in the correct origin, setting the opaque origin on the
264 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17265 if (request && request->DidEncounterError())
Anton Bikineevf62d1bf2021-05-15 17:56:07266 return absl::nullopt;
Nasko Oskov03912102019-01-11 00:21:32267
Anton Bikineevf62d1bf2021-05-15 17:56:07268 return absl::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32269}
270
Alex Moshchuk99242832023-05-22 17:21:44271bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42272 const GURL& virtual_url,
273 const GURL& dest_url) {
274 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44275 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
276 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42277 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
278 << virtual_url.possibly_invalid_spec();
279 return false;
280 }
281
282 // Don't attempt to navigate to non-empty invalid URLs.
283 if (!dest_url.is_valid() && !dest_url.is_empty()) {
284 LOG(WARNING) << "Refusing to load invalid URL: "
285 << dest_url.possibly_invalid_spec();
286 return false;
287 }
288
289 // The renderer will reject IPC messages with URLs longer than
290 // this limit, so don't attempt to navigate with a longer URL.
291 if (dest_url.spec().size() > url::kMaxURLChars) {
292 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
293 << " characters.";
294 return false;
295 }
296
Aaron Colwell33109c592020-04-21 21:31:19297 // Reject renderer debug URLs because they should have been handled before
298 // we get to this point. This check handles renderer debug URLs
299 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
300 // provides defense-in-depth if a renderer debug URL manages to get here via
301 // some other path. We want to reject the navigation here so it doesn't
302 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30303 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19304 LOG(WARNING) << "Refusing to load renderer debug URL: "
305 << dest_url.possibly_invalid_spec();
306 return false;
307 }
308
Alex Moshchuk99242832023-05-22 17:21:44309 // Guests only support navigations to known-safe schemes. This check already
310 // exists in the extensions layer, where it also dispatches proper events to
311 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
312 // for defense-in-depth to ensure that no other places in the codebase
313 // accidentally navigate guests to schemes such as WebUI, which is not
314 // supported. See https://crbug.com/1444221.
315 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
316 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
317 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
318 !dest_url.SchemeIs(url::kAboutScheme)) {
319 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
320 << dest_url.possibly_invalid_spec();
321 return false;
322 }
323 }
324
Camille Lamy5193caa2018-10-12 11:59:42325 return true;
326}
327
Mikel Astizba9cf2fd2017-12-17 10:38:10328// See replaced_navigation_entry_data.h for details: this information is meant
329// to ensure |*output_entry| keeps track of its original URL (landing page in
330// case of server redirects) as it gets replaced (e.g. history.replaceState()),
331// without overwriting it later, for main frames.
332void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57333 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10334 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17335 if (output_entry->GetReplacedEntryData().has_value() ||
336 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10337 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17338 }
Mikel Astizba9cf2fd2017-12-17 10:38:10339
340 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57341 data.first_committed_url = replaced_entry->GetURL();
342 data.first_timestamp = replaced_entry->GetTimestamp();
343 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29344 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10345}
346
Minggang Wangb9f3fa92021-07-01 15:30:31347blink::mojom::NavigationType GetNavigationType(
348 const GURL& old_url,
349 const GURL& new_url,
350 ReloadType reload_type,
351 NavigationEntryImpl* entry,
352 const FrameNavigationEntry& frame_entry,
353 bool has_pending_cross_document_commit,
354 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49355 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13356 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49357 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23358 // Reload navigations
359 switch (reload_type) {
360 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31361 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23362 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31363 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23364 case ReloadType::ORIGINAL_REQUEST_URL:
Minggang Wangb9f3fa92021-07-01 15:30:31365 return blink::mojom::NavigationType::RELOAD_ORIGINAL_REQUEST_URL;
clamyea99ea12018-05-28 13:54:23366 case ReloadType::NONE:
367 break; // Fall through to rest of function.
368 }
369
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08370 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31371 return entry->GetHasPostData()
372 ? blink::mojom::NavigationType::RESTORE_WITH_POST
373 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23374 }
375
danakjb952ef12021-01-14 19:58:49376 const bool can_be_same_document =
377 // A pending cross-document commit means this navigation will not occur in
378 // the current document, as that document would end up being replaced in
379 // the meantime.
380 !has_pending_cross_document_commit &&
381 // If the current document is an error page, we should always treat it as
382 // a different-document navigation so that we'll attempt to load the
383 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49384 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13385 // If the navigation is an embedder-initiated navigation of a fenced
386 // frame root (i.e. enters a fenced frame tree from outside),
387 // same-document navigations should be disabled because we don't want to
388 // allow information to be joined across multiple embedder-initiated
389 // fenced frame navigations (which may contain separate cross-site data).
390 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49391 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
392 // same-document navigations should be disabled because we want to force
393 // the creation of a new browsing context group.
394 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12395
clamyea99ea12018-05-28 13:54:23396 // History navigations.
397 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12398 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31399 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
400 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23401 }
402 DCHECK(!is_same_document_history_load);
403
404 // A same-document fragment-navigation happens when the only part of the url
405 // that is modified is after the '#' character.
406 //
407 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12408 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23409 //
410 // Note: this check is only valid for navigations that are not history
411 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
412 // history navigation from 'A#foo' to 'A#bar' is not a same-document
413 // navigation, but a different-document one. This is why history navigation
414 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47415 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
416 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12417
418 // The one case where we do the wrong thing here and incorrectly choose
419 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
420 // the renderer is a frameset. All frameset navigations should be
421 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
422 // navigation would do the right thing, as it would send it to the browser and
423 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
424 // into this method). But since we can't tell that case here for browser-
425 // initiated navigations, we have to get the renderer involved. In that case
426 // the navigation would be restarted due to the renderer spending a reply of
427 // mojom::CommitResult::RestartCrossDocument.
428
429 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31430 ? blink::mojom::NavigationType::SAME_DOCUMENT
431 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23432}
433
Camille Lamy5193caa2018-10-12 11:59:42434// Adjusts the original input URL if needed, to get the URL to actually load and
435// the virtual URL, which may differ.
436void RewriteUrlForNavigation(const GURL& original_url,
437 BrowserContext* browser_context,
438 GURL* url_to_load,
439 GURL* virtual_url,
440 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42441 // Allow the browser URL handler to rewrite the URL. This will, for example,
442 // remove "view-source:" from the beginning of the URL to get the URL that
443 // will actually be loaded. This real URL won't be shown to the user, just
444 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31445 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42446 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
447 url_to_load, browser_context, reverse_on_redirect);
448}
449
450#if DCHECK_IS_ON()
451// Helper sanity check function used in debug mode.
452void ValidateRequestMatchesEntry(NavigationRequest* request,
453 NavigationEntryImpl* entry) {
454 if (request->frame_tree_node()->IsMainFrame()) {
455 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
456 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31457 ui::PageTransitionFromInt(request->common_params().transition),
458 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42459 }
Nasko Oskovc36327d2019-01-03 23:23:04460 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42461 entry->should_clear_history_list());
462 DCHECK_EQ(request->common_params().has_user_gesture,
463 entry->has_user_gesture());
464 DCHECK_EQ(request->common_params().base_url_for_data_url,
465 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04466 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42467 entry->GetCanLoadLocalResources());
468 DCHECK_EQ(request->common_params().started_from_context_menu,
469 entry->has_started_from_context_menu());
470
471 FrameNavigationEntry* frame_entry =
472 entry->GetFrameEntry(request->frame_tree_node());
473 if (!frame_entry) {
474 NOTREACHED();
475 return;
476 }
477
Camille Lamy5193caa2018-10-12 11:59:42478 DCHECK_EQ(request->common_params().method, frame_entry->method());
479
Nasko Oskovc36327d2019-01-03 23:23:04480 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42481 if (redirect_size == frame_entry->redirect_chain().size()) {
482 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04483 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42484 frame_entry->redirect_chain()[i]);
485 }
486 } else {
487 NOTREACHED();
488 }
489}
490#endif // DCHECK_IS_ON()
491
Dave Tapuska8bfd84c2019-03-26 20:47:16492// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20493// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16494bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20495 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16496 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20497 DCHECK(sandboxed_initiator_rfh);
498 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
499 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16500 for (auto& item : navigations) {
501 bool within_subtree = false;
502 // Check whether this NavigationRequest affects a frame within the
503 // sandboxed frame's subtree by walking up the tree looking for the
504 // sandboxed frame.
505 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03506 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20507 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16508 within_subtree = true;
509 break;
510 }
511 }
512 if (!within_subtree)
513 return false;
514 }
515 return true;
516}
517
[email protected]e9ba4472008-09-14 15:42:43518} // namespace
519
arthursonzogni66f711c2019-10-08 14:40:36520// NavigationControllerImpl::PendingEntryRef------------------------------------
521
522NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
523 base::WeakPtr<NavigationControllerImpl> controller)
524 : controller_(controller) {}
525
526NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
527 if (!controller_) // Can be null with interstitials.
528 return;
529
530 controller_->PendingEntryRefDeleted(this);
531}
532
[email protected]d202a7c2012-01-04 07:53:47533// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29534
[email protected]23a918b2014-07-15 09:51:36535const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23536
[email protected]765b35502008-08-21 00:51:20537// static
[email protected]d202a7c2012-01-04 07:53:47538size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23539 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20540
[email protected]e6fec472013-05-14 05:29:02541// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20542// when testing.
543static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29544
[email protected]71fde352011-12-29 03:29:56545// static
dcheng9bfa5162016-04-09 01:00:57546std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
547 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10548 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07549 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21550 absl::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10551 ui::PageTransition transition,
552 bool is_renderer_initiated,
553 const std::string& extra_headers,
554 BrowserContext* browser_context,
555 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
556 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21557 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Sharon Yang242ef822023-05-15 21:07:32558 absl::nullopt /* source_process_site_url */, transition,
559 is_renderer_initiated, extra_headers, browser_context,
560 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10561}
562
563// static
564std::unique_ptr<NavigationEntryImpl>
565NavigationControllerImpl::CreateNavigationEntry(
566 const GURL& url,
567 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07568 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21569 absl::optional<GURL> initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:32570 absl::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57571 ui::PageTransition transition,
572 bool is_renderer_initiated,
573 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09574 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17575 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
576 bool rewrite_virtual_urls) {
577 GURL url_to_load = url;
578 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56579 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17580 if (rewrite_virtual_urls) {
581 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
582 &reverse_on_redirect);
583 }
Lukasz Anforowicz641234d52019-11-07 21:07:10584 // Let the NTP override the navigation params and pretend that this is a
585 // browser-initiated, bookmark-like navigation.
586 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32587 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21588 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10589
Patrick Monettef507e982019-06-19 20:18:06590 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28591 nullptr, // The site instance for tabs is sent on navigation
592 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21593 url_to_load, referrer, initiator_origin, initiator_base_url,
594 std::u16string(), transition, is_renderer_initiated,
595 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17596 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42597 entry->SetVirtualURL(virtual_url);
598 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56599 entry->set_update_virtual_url_with_url(reverse_on_redirect);
600 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06601 return entry;
[email protected]71fde352011-12-29 03:29:56602}
603
[email protected]cdcb1dee2012-01-04 00:46:20604// static
605void NavigationController::DisablePromptOnRepost() {
606 g_check_for_repost = false;
607}
608
[email protected]c5b88d82012-10-06 17:03:33609base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
610 base::Time t) {
611 // If |t| is between the water marks, we're in a run of duplicates
612 // or just getting out of it, so increase the high-water mark to get
613 // a time that probably hasn't been used before and return it.
614 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35615 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33616 return high_water_mark_;
617 }
618
619 // Otherwise, we're clear of the last duplicate run, so reset the
620 // water marks.
621 low_water_mark_ = high_water_mark_ = t;
622 return t;
623}
624
ckitagawa0faa5e42020-06-17 17:30:54625NavigationControllerImpl::ScopedShowRepostDialogForTesting::
626 ScopedShowRepostDialogForTesting()
627 : was_disallowed_(g_check_for_repost) {
628 g_check_for_repost = true;
629}
630
631NavigationControllerImpl::ScopedShowRepostDialogForTesting::
632 ~ScopedShowRepostDialogForTesting() {
633 g_check_for_repost = was_disallowed_;
634}
635
Nate Chapin9eb16be72022-09-23 22:54:31636NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
637 base::SafeRef<NavigationControllerImpl> controller)
638 : controller_(controller) {
639 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
640 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
641 frame_tree_node_id_to_keys_.insert(
642 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
643 if (auto* frame_entry = frame_tree_node->current_frame_host()
644 ->last_committed_frame_entry()) {
645 frame_tree_node_id_to_doc_seq_nos_.insert(
646 {frame_tree_node->frame_tree_node_id(),
647 frame_entry->document_sequence_number()});
648 }
649 }
650 PopulateKeySet(Direction::kBack);
651 PopulateKeySet(Direction::kForward);
652}
653
654void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
655 Direction direction) {
656 // Keep track of which FrameTreeNodes may still have relevant API keys in
657 // additional FrameNavigationEntries.
658 std::set<FrameTreeNode*> nodes_to_process;
659 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
660 nodes_to_process.insert(node);
661 }
662
663 const int offset = direction == Direction::kForward ? 1 : -1;
664 const int start = direction == Direction::kForward
665 ? controller_->GetLastCommittedEntryIndex()
666 : controller_->GetLastCommittedEntryIndex() - 1;
667 for (int i = start;
668 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
669 i += offset) {
670 std::set<FrameTreeNode*> nodes_to_continue_processing;
671
672 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
673 entry->ForEachFrameEntry([this, &nodes_to_process,
674 &nodes_to_continue_processing,
675 &entry](FrameNavigationEntry* frame_entry) {
676 // Find the |node| that matches |frame_entry|, if any.
677 FrameTreeNode* node = nullptr;
678 if (frame_entry == entry->root_node()->frame_entry) {
679 node = controller_->frame_tree().root();
680 } else {
681 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
682 if (it == names_to_nodes_.end())
683 return;
684 node = it->second;
685 }
686
687 // Skip this node if a previous step determine there are no longer
688 // relevant navigation API keys in this direction.
689 if (nodes_to_process.find(node) == nodes_to_process.end())
690 return;
691
692 // Stop processing |node| if we reach a point where it's cross-origin.
693 // See also PopulateSingleNavigationApiHistoryEntryVector().
694 url::Origin frame_entry_origin =
695 frame_entry->committed_origin().value_or(url::Origin::Resolve(
696 frame_entry->url(),
697 frame_entry->initiator_origin().value_or(url::Origin())));
698 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
699 return;
700
701 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
702 frame_entry->navigation_api_key());
703 // Mark |node| as needing more processing for the next entry.
704 nodes_to_continue_processing.insert(node);
705
706 // Check whether |node| went cross-document. If so, its children are
707 // no longer the same conceptual iframe as the current one, and
708 // should no longer be processed. This check is intentionally done
709 // after processing the current |node|, which may still have relevant
710 // discarded API keys.
711 if (frame_entry->document_sequence_number() !=
712 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50713 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31714 nodes_to_process.erase(descendant);
715 }
716 });
717
718 nodes_to_process.swap(nodes_to_continue_processing);
719 }
720}
721
722NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
723 std::set<std::string> all_keys;
724 // Find all remaining navigation API keys after some entries have been
725 // removed.
726 for (auto& entry : controller_->entries_) {
727 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
728 all_keys.insert(frame_entry->navigation_api_key());
729 });
730 }
731
732 // Notify each frame in the renderer of any disposed navigation API keys.
733 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
734 std::vector<std::string> disposed_keys;
735 for (const auto& key : id_to_keys.second) {
736 if (all_keys.find(key) == all_keys.end())
737 disposed_keys.push_back(key);
738 }
739 if (disposed_keys.empty())
740 continue;
741
742 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
743 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
744 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
745 }
746}
747
[email protected]d202a7c2012-01-04 07:53:47748NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00749 BrowserContext* browser_context,
750 FrameTree& frame_tree,
751 NavigationControllerDelegate* delegate)
752 : frame_tree_(frame_tree),
753 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57754 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22755 ssl_manager_(this),
Lei Zhang96031532019-10-10 19:05:47756 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)) {
[email protected]3d7474ff2011-07-27 17:47:37757 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29758}
759
[email protected]d202a7c2012-01-04 07:53:47760NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00761 // The NavigationControllerImpl might be called inside its delegate
762 // destructor. Calling it is not valid anymore.
763 delegate_ = nullptr;
764 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29765}
766
Matt Falkenhagen548ed1562021-07-06 01:38:26767WebContents* NavigationControllerImpl::DeprecatedGetWebContents() {
768 return delegate_->DeprecatedGetWebContents();
[email protected]fbc5e5f92012-01-02 06:08:32769}
770
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57771BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55772 return browser_context_;
773}
774
[email protected]d202a7c2012-01-04 07:53:47775void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30776 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36777 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57778 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47779 // Note that it's possible for `entries_` to contain multiple entries at this
780 // point, as Restore() might be called on a NavigationController that is
781 // already used (e.g. due to WebView's restoreState() API), not only for fresh
782 // NavigationControllers. These entries are not cleared to preserve legacy
783 // behavior and also because `pending_entry_` might point to one of the
784 // pre-existing entries. An exception for this is when `entries_` contains
785 // only the initial NavigationEntry, which must be removed.
786
787 // Do not proceed if selected_navigation will be out of bounds for the updated
788 // entries_ list, since it will be assigned to last_committed_entry_index_ and
789 // used to index entries_.
790 // TODO(https://crbug.com/1287624): Consider also returning early if entries
791 // is empty, since there should be no work to do (rather than marking the
792 // existing entries as needing reload). Also consider returning early if the
793 // selected index is -1, which represents a no-committed-entry state.
794 if (selected_navigation < -1 ||
795 selected_navigation >=
796 base::checked_cast<int>(entries->size() + entries_.size())) {
797 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24798 }
Charlie Reis23c26da2022-01-29 00:57:47799
Rakina Zata Amni46087a12022-11-11 08:28:38800 // There will always be at least one entry (new NavigationControllers will
801 // have the initial NavigationEntry).
802 if (selected_navigation == -1)
803 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47804
Rakina Zata Amni46087a12022-11-11 08:28:38805 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
806 // If we are on the initial NavigationEntry, it must be the only entry in
807 // the list. Since it's impossible to do a history navigation to the
808 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
809 // `pending_entry` might be set for a new non-history navigation).
810 // Note that we should not clear `entries_` if `entries` is empty (when
811 // InitialNavigationEntry mode is enabled), since that would leave us
812 // without any NavigationEntry.
813 CHECK_EQ(1, GetEntryCount());
814 CHECK_EQ(-1, pending_entry_index_);
815 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47816 }
[email protected]ce3fa3c2009-04-20 19:55:57817
[email protected]ce3fa3c2009-04-20 19:55:57818 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44819 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03820 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47821 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43822 if (entry->GetURL().is_empty()) {
823 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01824 // persisting the initial NavigationEntry [which is no longer possible but
825 // some old persisted sessions might still contain it] or when the
826 // serializer failed to write the URL because it's too long). Trying to
827 // restore and navigate to an entry with an empty URL will result in
828 // crashes, so change the URL to about:blank. See also
829 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43830 entry->SetURL(GURL(url::kAboutBlankURL));
831 }
dcheng36b6aec92015-12-26 06:16:36832 entries_.push_back(
833 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47834 }
avif16f85a72015-11-13 18:25:03835
836 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
837 // cleared out safely.
838 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57839
840 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36841 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57842}
843
toyoshim6142d96f2016-12-19 09:07:25844void NavigationControllerImpl::Reload(ReloadType reload_type,
845 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03846 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
847 (int)reload_type);
848 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
849 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28850 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28851 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32852 int current_index = -1;
853
Carlos IL42b416592019-10-07 23:10:36854 if (entry_replaced_by_post_commit_error_) {
855 // If there is an entry that was replaced by a currently active post-commit
856 // error navigation, this can't be the initial navigation.
857 DCHECK(!IsInitialNavigation());
858 // If the current entry is a post commit error, we reload the entry it
859 // replaced instead. We leave the error entry in place until a commit
860 // replaces it, but the pending entry points to the original entry in the
861 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
862 // case that pending_entry_ != entries_[pending_entry_index_].
863 entry = entry_replaced_by_post_commit_error_.get();
864 current_index = GetCurrentEntryIndex();
865 } else if (IsInitialNavigation() && pending_entry_) {
866 // If we are reloading the initial navigation, just use the current
867 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32868 entry = pending_entry_;
869 // The pending entry might be in entries_ (e.g., after a Clone), so we
870 // should also update the current_index.
871 current_index = pending_entry_index_;
872 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00873 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32874 current_index = GetCurrentEntryIndex();
875 if (current_index != -1) {
creis3da03872015-02-20 21:12:32876 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32877 }
[email protected]979a4bc2013-04-24 01:27:15878 }
[email protected]241db352013-04-22 18:04:05879
[email protected]59167c22013-06-03 18:07:32880 // If we are no where, then we can't reload. TODO(darin): We should add a
881 // CanReload method.
882 if (!entry)
883 return;
884
Rakina Zata Amnif297a802022-01-18 03:53:43885 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
886 // We should never navigate to an existing initial NavigationEntry that is
887 // the initial NavigationEntry for the initial empty document that hasn't
888 // been overridden by the synchronous about:blank commit, to preserve
889 // legacy behavior where trying to reload when the main frame is on the
890 // initial empty document won't result in a navigation. See also
891 // https://crbug.com/1277414.
892 return;
893 }
894
Aran Gilman37d11632019-10-08 23:07:15895 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30896 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07897 // they really want to do this. If they do, the dialog will call us back
898 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57899 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02900
[email protected]106a0812010-03-18 00:15:12901 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57902 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47903 return;
initial.commit09911bf2008-07-26 23:55:29904 }
Lei Zhang96031532019-10-10 19:05:47905
Wang Huia25efabc2022-09-24 17:27:22906 // Set ReloadType for |entry|.
907 entry->set_reload_type(reload_type);
908
Lei Zhang96031532019-10-10 19:05:47909 if (!IsInitialNavigation())
910 DiscardNonCommittedEntries();
911
912 pending_entry_ = entry;
913 pending_entry_index_ = current_index;
914 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
915
Nate Chapin45f620582021-09-30 17:45:43916 // location.reload() goes through BeginNavigation, so all reloads triggered
917 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13918 NavigateToExistingPendingEntry(
919 reload_type,
920 /*initiator_rfh=*/nullptr,
921 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
922 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29923}
924
[email protected]d202a7c2012-01-04 07:53:47925void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48926 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12927}
928
[email protected]d202a7c2012-01-04 07:53:47929void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49930 // If the pending reload type has been cleared by another navigation
931 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48932 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49933 return;
[email protected]106a0812010-03-18 00:15:12934 }
Wang Hui96ab1012022-10-11 02:05:49935 Reload(pending_reload_, false);
936 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12937}
938
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57939bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09940 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11941}
942
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57943bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38944 // Check that we're on the initial NavigationEntry and that this is not a
945 // cloned tab.
946 return IsInitialNavigation() && GetEntryCount() == 1 &&
947 GetLastCommittedEntry()->IsInitialEntry() &&
948 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40949}
950
Aran Gilman37d11632019-10-08 23:07:15951NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
952 int nav_entry_id) const {
avi254eff02015-07-01 08:27:58953 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:03954 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:58955}
956
Adithya Srinivasan9b0c99c2021-08-10 15:19:45957NavigationEntryImpl*
958NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
959 int nav_entry_id) const {
960 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
961 if (entry)
962 return entry;
963 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:52964 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:45965 : nullptr;
966}
967
W. James MacLeanc07dc41b2022-07-25 18:52:16968void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:57969 const url::Origin& origin) {
970 for (int i = 0; i < GetEntryCount(); i++) {
971 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:16972 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57973 }
974 if (entry_replaced_by_post_commit_error_) {
975 // It's possible we could come back to this entry if the error
976 // page/interstitial goes away.
977 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:16978 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57979 }
W. James MacLean1c40862c2020-04-27 21:05:57980}
981
avi25764702015-06-23 15:43:37982void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:57983 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:00984 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:37985 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:27986 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:20987}
988
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57989NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:47990 if (pending_entry_)
991 return pending_entry_;
992 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:20993}
994
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57995NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:32996 // The pending entry is safe to return for new (non-history), browser-
997 // initiated navigations. Most renderer-initiated navigations should not
998 // show the pending entry, to prevent URL spoof attacks.
999 //
1000 // We make an exception for renderer-initiated navigations in new tabs, as
1001 // long as no other page has tried to access the initial empty document in
1002 // the new tab. If another page modifies this blank page, a URL spoof is
1003 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321004 bool safe_to_show_pending =
1005 pending_entry_ &&
1006 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091007 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321008 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461009 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321010
1011 // Also allow showing the pending entry for history navigations in a new tab,
1012 // such as Ctrl+Back. In this case, no existing page is visible and no one
1013 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151014 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1015 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321016 safe_to_show_pending = true;
1017
1018 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191019 return pending_entry_;
1020 return GetLastCommittedEntry();
1021}
1022
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571023int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201024 if (pending_entry_index_ != -1)
1025 return pending_entry_index_;
1026 return last_committed_entry_index_;
1027}
1028
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571029NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381030 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031031 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201032}
1033
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571034bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351035 const std::string& mime_type = frame_tree_->root()
1036 ->current_frame_host()
1037 ->GetPage()
1038 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531039 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1040 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271041 NavigationEntry* visible_entry = GetVisibleEntry();
1042 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391043 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161044}
1045
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571046int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271047 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451048 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271049 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551050 return last_committed_entry_index_;
1051}
1052
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571053int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451054 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291055 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551056 return static_cast<int>(entries_.size());
1057}
1058
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571059NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371060 if (index < 0 || index >= GetEntryCount())
1061 return nullptr;
1062
avif16f85a72015-11-13 18:25:031063 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251064}
1065
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571066NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471067 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201068}
1069
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571070int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461071 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031072}
1073
Kevin McNee3b3a56192023-03-17 14:40:591074absl::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031075 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591076 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1077 return index;
1078 }
Shivani Sharma298d12852019-01-22 20:04:031079 }
Kevin McNee3b3a56192023-03-17 14:40:591080 return absl::nullopt;
1081}
1082
1083bool NavigationControllerImpl::CanGoBack() {
1084 return GetIndexForGoBack().has_value();
1085}
1086
1087absl::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
1088 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1089 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1090 return index;
1091 }
1092 }
1093 return absl::nullopt;
[email protected]765b35502008-08-21 00:51:201094}
1095
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571096bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591097 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201098}
1099
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571100bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031101 int index = GetIndexForOffset(offset);
1102 return index >= 0 && index < GetEntryCount();
1103}
1104
Xiaohan Wang7f8052e02022-01-14 18:44:281105#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151106bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151107 if (offset == 0)
1108 return true;
1109 int increment = offset > 0 ? 1 : -1;
1110 int non_skippable_entries = 0;
1111 for (int index = GetIndexForOffset(increment);
1112 index >= 0 && index < GetEntryCount(); index += increment) {
1113 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1114 non_skippable_entries++;
1115
1116 if (non_skippable_entries == std::abs(offset))
1117 return true;
1118 }
1119 return false;
1120}
1121#endif
1122
[email protected]d202a7c2012-01-04 07:53:471123void NavigationControllerImpl::GoBack() {
Kevin McNee3b3a56192023-03-17 14:40:591124 const absl::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061125
Kevin McNeeedc481c2023-04-27 22:30:581126 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211127
Kevin McNee3b3a56192023-03-17 14:40:591128 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201129}
1130
[email protected]d202a7c2012-01-04 07:53:471131void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161132 // Note that at least one entry (the last one) will be non-skippable since
1133 // entries are marked skippable only when they add another entry because of
1134 // redirect or pushState.
Kevin McNee3b3a56192023-03-17 14:40:591135 const absl::optional<int> target_index = GetIndexForGoForward();
1136
Kevin McNeeedc481c2023-04-27 22:30:581137 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591138
1139 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201140}
1141
[email protected]d202a7c2012-01-04 07:53:471142void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131143 GoToIndex(index, /*initiator_rfh=*/nullptr,
1144 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
1145 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161146}
1147
Nate Chapinbf682fa32022-09-26 22:41:201148void NavigationControllerImpl::GoToIndex(
1149 int index,
1150 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131151 absl::optional<blink::scheduler::TaskAttributionId>
1152 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201153 const std::string* navigation_api_key) {
Rakina Zata Amnid605d462022-06-01 10:17:031154 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
sunjian30574a62017-03-21 21:39:441155 TRACE_EVENT0("browser,navigation,benchmark",
1156 "NavigationControllerImpl::GoToIndex");
[email protected]765b35502008-08-21 00:51:201157 if (index < 0 || index >= static_cast<int>(entries_.size())) {
Rakina Zata Amni4595c36a2023-02-01 03:51:181158 // We've seen reports of this NOTREACHED being hit on Android WebView, where
1159 // we won't get the log message below. The following code ensures that
1160 // `index` and `entries_size` will show up on the minidump for that case.
1161 base::debug::Alias(&index);
1162 const size_t entries_size = entries_.size();
1163 base::debug::Alias(&entries_size);
1164 NOTREACHED() << "Index " << index
1165 << " is out of bounds, entries_.size() is " << entries_size;
[email protected]765b35502008-08-21 00:51:201166 return;
1167 }
1168
Rakina Zata Amnif297a802022-01-18 03:53:431169 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1170 // We should never navigate to an existing initial NavigationEntry that is
1171 // the initial NavigationEntry for the initial empty document that hasn't
1172 // been overridden by the synchronous about:blank commit, to preserve
1173 // legacy behavior where trying to reload when the main frame is on the
1174 // initial empty document won't result in a navigation. See also
1175 // https://crbug.com/1277414.
1176 return;
1177 }
1178
[email protected]cbab76d2008-10-13 22:42:471179 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201180
arthursonzogni5c4c202d2017-04-25 23:41:271181 DCHECK_EQ(nullptr, pending_entry_);
1182 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431183
arthursonzogni5c4c202d2017-04-25 23:41:271184 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201185 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271186 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1187 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201188 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131189 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201190 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201191}
1192
[email protected]d202a7c2012-01-04 07:53:471193void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121194 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031195 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201196 return;
1197
[email protected]9ba14052012-06-22 23:50:031198 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201199}
1200
Nate Chapinbf682fa32022-09-26 22:41:201201void NavigationControllerImpl::GoToOffsetFromRenderer(
1202 int offset,
Yoav Weiss8c573952022-11-17 17:35:131203 RenderFrameHostImpl* initiator_rfh,
1204 absl::optional<blink::scheduler::TaskAttributionId>
1205 soft_navigation_heuristics_task_id) {
Nate Chapin758e5e482023-05-02 00:22:551206 // If the renderer sent an out-of-bounds offset, cancel and notify the
1207 // renderer.
1208 if (!CanGoToOffset(offset)) {
1209 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
1210 /*navigation_api_key=*/std::string(),
1211 blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapin45f620582021-09-30 17:45:431212 return;
Nate Chapin758e5e482023-05-02 00:22:551213 }
Nate Chapin45f620582021-09-30 17:45:431214
Nate Chapinbf682fa32022-09-26 22:41:201215 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131216 soft_navigation_heuristics_task_id,
1217 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431218}
1219
Xiaohan Wang7f8052e02022-01-14 18:44:281220#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151221void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1222 // Note: This is actually reached in unit tests.
1223 if (!CanGoToOffsetWithSkipping(offset))
1224 return;
1225
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421226 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151227 GoToIndex(GetIndexForOffset(offset));
1228 return;
1229 }
1230 int increment = offset > 0 ? 1 : -1;
1231 // Find the offset without counting skippable entries.
1232 int target_index = GetIndexForOffset(increment);
1233 int non_skippable_entries = 0;
1234 for (int index = target_index; index >= 0 && index < GetEntryCount();
1235 index += increment) {
1236 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1237 non_skippable_entries++;
1238
1239 if (non_skippable_entries == std::abs(offset)) {
1240 target_index = index;
1241 break;
1242 }
1243 }
1244
1245 GoToIndex(target_index);
1246}
1247#endif
1248
[email protected]41374f12013-07-24 02:49:281249bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151250 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281251 return false;
[email protected]6a13a6c2011-12-20 21:47:121252
[email protected]43032342011-03-21 14:10:311253 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281254 return true;
[email protected]cbab76d2008-10-13 22:42:471255}
1256
Michael Thiessen9b14d512019-09-23 21:19:471257void NavigationControllerImpl::PruneForwardEntries() {
1258 DiscardNonCommittedEntries();
1259 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471260 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471261 if (num_removed <= 0)
1262 return;
Nate Chapin9eb16be72022-09-23 22:54:311263 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471264 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1265 NotifyPrunedEntries(this, remove_start_index /* start index */,
1266 num_removed /* count */);
1267}
1268
Aran Gilman37d11632019-10-08 23:07:151269void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1270 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321271 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311272 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511273 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1274 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321275 }
1276}
1277
Harkiran Bolariaba823e42021-05-21 18:30:361278base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1279 const GURL& url,
1280 const Referrer& referrer,
1281 ui::PageTransition transition,
1282 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471283 LoadURLParams params(url);
1284 params.referrer = referrer;
1285 params.transition_type = transition;
1286 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361287 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471288}
1289
Harkiran Bolariaba823e42021-05-21 18:30:361290base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1291 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061292 if (params.is_renderer_initiated)
1293 DCHECK(params.initiator_origin.has_value());
1294
naskob8744d22014-08-28 17:07:431295 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151296 "NavigationControllerImpl::LoadURLWithParams", "url",
1297 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291298 bool is_explicit_navigation =
1299 GetContentClient()->browser()->IsExplicitNavigation(
1300 params.transition_type);
1301 if (HandleDebugURL(params.url, params.transition_type,
1302 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431303 // If Telemetry is running, allow the URL load to proceed as if it's
1304 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491305 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431306 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361307 return nullptr;
[email protected]47752982014-07-29 08:01:431308 }
[email protected]8bf1048012012-02-08 01:22:181309
[email protected]cf002332012-08-14 19:17:471310 // Checks based on params.load_type.
1311 switch (params.load_type) {
1312 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431313 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471314 break;
1315 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261316 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471317 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361318 return nullptr;
[email protected]cf002332012-08-14 19:17:471319 }
1320 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461321 }
[email protected]e47ae9472011-10-13 19:48:341322
[email protected]e47ae9472011-10-13 19:48:341323 // The user initiated a load, we don't need to reload anymore.
1324 needs_reload_ = false;
1325
Harkiran Bolariaba823e42021-05-21 18:30:361326 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441327}
1328
Mohamed Abdelhalim833de902019-09-16 17:41:451329bool NavigationControllerImpl::PendingEntryMatchesRequest(
1330 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191331 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451332 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191333}
1334
[email protected]d202a7c2012-01-04 07:53:471335bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321336 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071337 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331338 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441339 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251340 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471341 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131342 NavigationRequest* navigation_request) {
1343 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331344
1345 // Note: validation checks and renderer kills due to invalid commit messages
1346 // must happen before getting here, in
1347 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1348 // effects of the navigation have already occurred.
1349
[email protected]cd2e15742013-03-08 04:08:311350 is_initial_navigation_ = false;
1351
Wang Hui96ab1012022-10-11 02:05:491352 // Any pending request to repost a form submission is no longer valid, since a
1353 // different NavigationEntry is committing.
1354 pending_reload_ = ReloadType::NONE;
1355
[email protected]0e8db942008-09-24 21:21:481356 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431357 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451358 if (entry_replaced_by_post_commit_error_) {
1359 // Same document navigation events with a post-commit error should already
1360 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1361 // reaching here.
1362 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331363
Rakina Zata Amnie2d31312022-11-18 03:38:451364 // Any commit while a post-commit error page is showing should put the
1365 // original entry back, replacing the error page's entry. This includes
1366 // reloads, where the original entry was used as the pending entry and
1367 // should now be at the correct index at commit time.
1368 entries_[last_committed_entry_index_] =
1369 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481370 }
Rakina Zata Amnie2d31312022-11-18 03:38:451371 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1372 details->previous_entry_index = GetLastCommittedEntryIndex();
1373 if (PendingEntryMatchesRequest(navigation_request) &&
1374 pending_entry_->GetIsOverridingUserAgent() !=
1375 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1376 overriding_user_agent_changed = true;
1377 }
1378#if BUILDFLAG(IS_ANDROID)
1379 // TODO(crbug.com/1266277): Clean up the logic of setting
1380 // |overriding_user_agent_changed| post-launch.
1381 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1382 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
1383 // Must honor user agent overrides in the |navigation_request|, such as
1384 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1385 // result, besides comparing |pending_entry_|'s user agent against
1386 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1387 // agent against LastCommittedEntry's.
1388 if (navigation_request->is_overriding_user_agent() !=
1389 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1390 overriding_user_agent_changed = true;
1391 }
1392 }
1393#endif // BUILDFLAG(IS_ANDROID)
[email protected]ecd9d8702008-08-28 22:10:171394
Dave Tapuskaa2ab4f252021-07-08 21:31:281395 bool is_main_frame_navigation = !rfh->GetParent();
1396
Alexander Timind2f2e4f22019-04-02 20:04:531397 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1398 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281399 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141400 // BackForwardCacheMetrics to be associated with the new navigation's
1401 // NavigationEntry, by either creating a new object or reusing the previous
1402 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281403 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Arthur Sonzognif6785ec2022-12-05 10:11:501404 if (navigation_request->frame_tree_node()->frame_tree().type() ==
Dave Tapuskaa2ab4f252021-07-08 21:31:281405 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141406 back_forward_cache_metrics = BackForwardCacheMetrics::
1407 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281408 GetLastCommittedEntry(), is_main_frame_navigation,
1409 params.document_sequence_number);
1410 }
Yuzu Saijo29f96ca92022-12-08 04:54:121411
Alexander Timind2f2e4f22019-04-02 20:04:531412 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281413 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451414 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1415 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531416 }
1417 }
1418
Rakina Zata Amnifd8370b2022-11-14 13:32:251419 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1420 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091421 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251422 details->did_replace_entry =
1423 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091424
fdegans9caf66a2015-07-30 21:10:421425 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111426 // except for restored entries. This should be true even if the current commit
1427 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291428 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481429 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081430 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111431
1432 // Only make changes based on the pending entry if the NavigationRequest
1433 // matches it. Otherwise, the pending entry may be for a different request
1434 // (e.g., if a slow history navigation is pending while an auto-subframe
1435 // commit occurs).
1436 if (PendingEntryMatchesRequest(navigation_request)) {
1437 // It is no longer necessary to consider the pending entry as restored.
1438 if (pending_entry_->IsRestored()) {
1439 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1440 was_restored = true;
1441 }
[email protected]e9ba4472008-09-14 15:42:431442
Charlie Reisf8cde712022-10-20 16:25:091443 // If the SiteInstance has changed from the matching pending entry, this
1444 // must be treated as a new navigation with replacement. Set the replacement
1445 // bit here and ClassifyNavigation will identify this case and return
1446 // NEW_ENTRY.
1447 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1448 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1449 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251450 // TODO(nasko,creis,rakina): Move this to happen before committing the
1451 // navigation. This is a bit complicated because we don't currently
1452 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091453 details->did_replace_entry = true;
1454 }
Nasko Oskovaee2f862018-06-15 00:05:521455 }
[email protected]bcd904482012-02-01 01:54:221456
[email protected]e9ba4472008-09-14 15:42:431457 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101458 NavigationType navigation_type =
1459 ClassifyNavigation(rfh, params, navigation_request);
1460 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451461
Rakina Zata Amnie2d31312022-11-18 03:38:451462 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451463 // Ensure that this navigation does not add a navigation entry, since
1464 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1465 // beyond the last committed one. Therefore, `should_replace_current_entry`
1466 // should be set, which replaces the current entry, or this should be a
1467 // reload, which does not create a new entry.
1468 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1469 // navigation that is restored will not be creating a new entry anyways, so
1470 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1471 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1472 // pointed out in the issue.
Rakina Zata Amnifd8370b2022-11-14 13:32:251473 DCHECK(navigation_request->common_params().should_replace_current_entry ||
shivanigithub189833f2022-04-27 18:08:451474 navigation_request->GetReloadType() != ReloadType::NONE ||
Miyoung Shin3299cbf2022-11-22 01:41:101475 navigation_type == NAVIGATION_TYPE_AUTO_SUBFRAME);
shivanigithub189833f2022-04-27 18:08:451476 }
1477
Rakina Zata Amnie2d31312022-11-18 03:38:451478 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551479 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241480 // This is a subframe navigation on the initial empty document, which used
1481 // to not have a NavigationEntry to attach to. Now it can attach to the
1482 // initial NavigationEntry, and we must ensure that its NavigationEntry
1483 // will keep the "initial NavigationEntry" status and won't append a new
1484 // NavigationEntry (it should always do replacement instead).
1485 // See also https://crbug.com/1277414.
1486 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551487 // Subframe navigation on initial NavigationEntry must not append a new
1488 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1489 // means every subframe navigation that happens while we're on the initial
1490 // NavigationEntry will always reuse the existing NavigationEntry and
1491 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101492 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1493 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551494 // This is a navigation that modifies the initial NavigationEntry, either
1495 // for a replacement or a reload. The initial NavigationEntry should
1496 // retain its "initial NavigationEntry" status in this case.
1497 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241498 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251499 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1500 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241501 // This is a synchronous about:blank navigation on the main frame, which
1502 // used to not create a NavigationEntry when we have no NavigationEntry on
1503 // FrameTree creation. We now have the initial NavigationEntry and are on
1504 // the initial NavigationEntry. To preserve old behavior, we should still
1505 // keep the "initial" status for the new NavigationEntry that we will
1506 // create for this navigation, so that subframe navigations under the
1507 // synchronously committed about:blank document will never append new
1508 // NavigationEntry, and instead will just reuse the initial
1509 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1510 // See also https://crbug.com/1277414.
1511 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551512 }
1513 }
1514 DCHECK(!details->should_stay_as_initial_entry ||
1515 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201516
eugenebutee08663a2017-04-27 17:43:121517 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441518 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121519
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071520 details->is_prerender_activation =
1521 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241522 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1523 ->GetOutermostMainFrame()
1524 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071525
Peter Boströmd7592132019-01-30 04:50:311526 // Make sure we do not discard the pending entry for a different ongoing
1527 // navigation when a same document commit comes in unexpectedly from the
1528 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1529 // other navigation types. See https://crbug.com/900036.
1530 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061531 bool keep_pending_entry =
1532 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101533 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061534 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311535
Miyoung Shin3299cbf2022-11-22 01:41:101536 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061537 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491538 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051539 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001540 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431541 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061542 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491543 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1544 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001545 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431546 break;
[email protected]8ff00d72012-10-23 19:12:211547 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471548 RendererDidNavigateNewSubframe(
1549 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001550 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431551 break;
[email protected]8ff00d72012-10-23 19:12:211552 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391553 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251554 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001555 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081556 // We don't send a notification about auto-subframe PageState during
1557 // UpdateStateForFrame, since it looks like nothing has changed. Send
1558 // it here at commit time instead.
1559 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431560 return false;
creis59d5a47cb2016-08-24 23:57:191561 }
[email protected]e9ba4472008-09-14 15:42:431562 break;
Aran Gilman37d11632019-10-08 23:07:151563 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431564 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151565 break;
[email protected]765b35502008-08-21 00:51:201566 }
1567
[email protected]688aa65c62012-09-28 04:32:221568 // At this point, we know that the navigation has just completed, so
1569 // record the time.
1570 //
1571 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261572 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331573 base::Time timestamp =
1574 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1575 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131576 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221577
Peter Boströmd7592132019-01-30 04:50:311578 // If we aren't keeping the pending entry, there shouldn't be one at this
1579 // point. Clear it again in case any error cases above forgot to do so.
1580 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1581 // been cleared instead of protecting against it.
1582 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551583 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141584
[email protected]e9ba4472008-09-14 15:42:431585 // All committed entries should have nonempty content state so WebKit doesn't
1586 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471587 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321588 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221589 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441590 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141591
Alexander Timind2f2e4f22019-04-02 20:04:531592 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1593 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281594 if (back_forward_cache_metrics &&
1595 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531596 active_entry->set_back_forward_cache_metrics(
1597 std::move(back_forward_cache_metrics));
1598 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281599
1600 // `back_forward_cache_metrics()` may return null as we do not record
1601 // back-forward cache metrics for navigations in non-primary frame trees.
1602 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141603 // TODO(https://crbug.com/1338089): Remove this.
1604 // These are both only available from details at this point, so we capture
1605 // them here.
1606 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101607 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141608 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1609 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281610 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1611 navigation_request,
1612 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1613 }
naskoc7533512016-05-06 17:01:121614
Charles Reisc0507202017-09-21 00:40:021615 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1616 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1617 // A mismatch can occur if the renderer lies or due to a unique name collision
1618 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121619 FrameNavigationEntry* frame_entry =
1620 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021621 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1622 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031623 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081624 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1625 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031626 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201627
1628 // Remember the bindings the renderer process has at this point, so that
1629 // we do not grant this entry additional bindings if we come back to it.
1630 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301631 }
[email protected]132e281a2012-07-31 18:32:441632
[email protected]97d8f0d2013-10-29 16:49:211633 // Once it is committed, we no longer need to track several pieces of state on
1634 // the entry.
naskoc7533512016-05-06 17:01:121635 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131636
[email protected]49bd30e62011-03-22 20:12:591637 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221638 // TODO(creis): This check won't pass for subframes until we create entries
1639 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001640 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421641 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591642
[email protected]e9ba4472008-09-14 15:42:431643 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001644 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001645 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311646 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531647
arthursonzogni7ddc6542021-04-09 09:16:501648 active_entry->SetIsOverridingUserAgent(
1649 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031650
[email protected]93f230e02011-06-01 14:40:001651 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291652
aelias100c9192017-01-13 00:01:431653 if (overriding_user_agent_changed)
1654 delegate_->UpdateOverridingUserAgent();
1655
creis03b48002015-11-04 00:54:561656 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1657 // one knows the latest NavigationEntry it is showing (whether it has
1658 // committed anything in this navigation or not). This allows things like
1659 // state and title updates from RenderFrames to apply to the latest relevant
1660 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381661 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031662 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381663 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431664
1665 if (navigation_request->IsPrerenderedPageActivation()) {
1666 BroadcastHistoryOffsetAndLength();
1667 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1668 // is activated. As a result, a "prerenderingchange" event listener sees the
1669 // history.length which is not updated yet. We should guarantee that
1670 // history's length and offset should be updated before a
1671 // "prerenderingchange" event listener runs. One possible approach is to use
1672 // the same IPC which "prerenderingchange" uses, and propagate history's
1673 // length and offset together with that.
1674 }
1675
[email protected]e9ba4472008-09-14 15:42:431676 return true;
initial.commit09911bf2008-07-26 23:55:291677}
1678
[email protected]8ff00d72012-10-23 19:12:211679NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321680 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101681 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241682 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591683 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511684 "ClassifyNavigation");
1685
avi7c6f35e2015-05-08 17:52:381686 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241687 // A new entry. We may or may not have a corresponding pending entry, and
1688 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001689 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491690 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061691 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381692 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241693 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511694 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381695 return NAVIGATION_TYPE_NEW_SUBFRAME;
1696 }
1697
Charlie Reisc0f17d2d2021-01-12 18:52:491698 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381699 DCHECK(!params.history_list_was_cleared);
1700
avi39c1edd32015-06-04 20:06:001701 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381702 // All manual subframes would be did_create_new_entry and handled above, so
1703 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081704 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1705 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381706 }
1707
Rakina Zata Amnif6950d552020-11-24 03:26:101708 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1709 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381710 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1711 // create a new page.
1712
Hayato Ito2ae49442021-07-02 02:59:251713 // This main frame navigation is not a history navigation (since
1714 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1715 // reload or a replacement navigation, which will modify the existing entry.
1716 //
Nasko Oskov332593c2018-08-16 17:21:341717 // TODO(nasko): With error page isolation, reloading an existing session
1718 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491719 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341720 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511721 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491722 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061723 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381724 }
1725
Charlie Reisf8cde712022-10-20 16:25:091726 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521727 // If the SiteInstance of the |pending_entry_| does not match the
1728 // SiteInstance that got committed, treat this as a new navigation with
1729 // replacement. This can happen if back/forward/reload encounters a server
1730 // redirect to a different site or an isolated error page gets successfully
1731 // reloaded into a different SiteInstance.
1732 if (pending_entry_->site_instance() &&
1733 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491734 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061735 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521736 }
creis77c9aa32015-09-25 19:59:421737
Nasko Oskovaee2f862018-06-15 00:05:521738 if (pending_entry_index_ == -1) {
1739 // In this case, we have a pending entry for a load of a new URL but Blink
1740 // didn't do a new navigation (params.did_create_new_entry). First check
1741 // to make sure Blink didn't treat a new cross-process navigation as
1742 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161743 // we must treat it as NEW rather than the converted reload case below,
1744 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451745 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161746 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061747 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521748 }
1749
1750 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161751 // We will create a pending entry, but NavigateWithoutEntry will convert
1752 // it to a reload since it's the same page and not create a new entry for
1753 // it. (The user doesn't want to have a new back/forward entry when they
1754 // do this.) Therefore we want to just ignore the pending entry and go
1755 // back to where we were (the "existing entry").
1756 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061757 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521758 }
avi7c6f35e2015-05-08 17:52:381759 }
1760
Rakina Zata Amni153d5702021-09-13 22:48:001761 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381762 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491763 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1764 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161765 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061766 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381767 }
1768
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121769 if (navigation_request->DidEncounterError() &&
1770 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101771 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381772 // If the renderer was going to a new pending entry that got cleared because
1773 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491774 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381775 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511776 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491777 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061778 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381779 }
1780
Charlie Reisc0f17d2d2021-01-12 18:52:491781 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101782 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511783 trace_return.traced_value()->SetInteger("existing_entry_index",
1784 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381785 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441786 // The renderer has committed a navigation to an entry that no longer
1787 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491788 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061789 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381790 }
1791
avi7c6f35e2015-05-08 17:52:381792 // Since we weeded out "new" navigations above, we know this is an existing
1793 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491794 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061795 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381796}
1797
Rakina Zata Amni3460d382021-10-29 00:43:371798void NavigationControllerImpl::UpdateNavigationEntryDetails(
1799 NavigationEntryImpl* entry,
1800 RenderFrameHostImpl* rfh,
1801 const mojom::DidCommitProvisionalLoadParams& params,
1802 NavigationRequest* request,
1803 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001804 bool is_new_entry,
1805 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371806 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171807 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371808 entry->AddOrUpdateFrameEntry(
1809 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571810 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371811 rfh->GetSiteInstance(), nullptr, params.url,
1812 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171813 Referrer(*params.referrer),
1814 request ? request->common_params().initiator_origin : params.origin,
W. James MacLean23e90a12022-12-21 04:38:211815 request ? request->common_params().initiator_base_url : absl::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171816 request ? request->GetRedirectChain() : redirects, params.page_state,
1817 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amniafd3c6582021-11-30 06:19:171818 (request ? request->GetSubresourceWebBundleNavigationInfo() : nullptr),
Rakina Zata Amni3460d382021-10-29 00:43:371819 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171820 rfh, request && request->IsSameDocument(),
1821 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371822
1823 if (rfh->GetParent()) {
1824 // Only modify the NavigationEntry for main frame navigations.
1825 return;
1826 }
1827 if (entry->update_virtual_url_with_url())
1828 UpdateVirtualURLToURL(entry, params.url);
1829 // Don't use the page type from the pending entry. Some interstitial page
1830 // may have set the type to interstitial. Once we commit, however, the page
1831 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171832 entry->set_page_type((request && request->DidEncounterError())
1833 ? PAGE_TYPE_ERROR
1834 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431835 if (commit_details && commit_details->should_stay_as_initial_entry) {
1836 // Retain the "initial NavigationEntry" status.
1837 if (request->IsSameDocument()) {
1838 // If this is for a same-document navigation, the NavigationEntry must be
1839 // reused and should already be marked as the initial NavigationEntry.
1840 DCHECK(entry->IsInitialEntry());
1841 } else {
1842 // If this is for a cross-document navigation, it can be caused by a
1843 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1844 // "for synchronous about:blank" in the latter case, and also when it is
1845 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1846 // is not for a synchronous about:blank commit.
1847 NavigationEntryImpl::InitialNavigationEntryState new_state =
1848 NavigationEntryImpl::InitialNavigationEntryState::
1849 kInitialNotForSynchronousAboutBlank;
1850 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1851 request->is_synchronous_renderer_commit()) {
1852 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1853 kInitialForSynchronousAboutBlank;
1854 }
1855 entry->set_initial_navigation_entry_state(new_state);
1856 }
1857 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1858 // Remove the "initial NavigationEntry" status.
1859 entry->set_initial_navigation_entry_state(
1860 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001861 }
Rakina Zata Amniddf10502022-01-15 02:56:551862
Rakina Zata Amni3460d382021-10-29 00:43:371863 if (is_new_entry) {
1864 // Some properties of the NavigationEntry are only set when the entry is
1865 // new (we aren't reusing it).
1866 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171867 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1868 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371869 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1870 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1871 } else {
1872 // We are reusing the NavigationEntry. The site instance will normally be
1873 // the same except for a few cases:
1874 // 1) session restore, when no site instance will be assigned or
1875 // 2) redirect, when the site instance is reset.
1876 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1877 entry->site_instance() == rfh->GetSiteInstance());
1878 }
1879}
1880
Rakina Zata Amniafd3c6582021-11-30 06:19:171881void NavigationControllerImpl::CreateInitialEntry() {
1882 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031883 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171884 auto params = mojom::DidCommitProvisionalLoadParams::New();
1885 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1886 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1887 // before we have initial NavigationEntries.
1888 params->url = GURL::EmptyGURL();
1889 params->http_status_code = 0;
1890 params->url_is_unreachable = false;
1891 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171892 params->post_id = -1;
1893 params->embedding_token = base::UnguessableToken::Create();
1894 params->navigation_token = base::UnguessableToken::Create();
1895 params->did_create_new_entry = true;
1896 params->origin = rfh->GetLastCommittedOrigin();
1897 params->should_update_history = true;
1898 params->item_sequence_number = 0;
1899 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151900 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171901 params->transition = is_in_fenced_frame_tree
1902 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1903 : ui::PAGE_TRANSITION_LINK;
1904 params->referrer = blink::mojom::Referrer::New();
1905
Rakina Zata Amniafd3c6582021-11-30 06:19:171906 auto new_entry = std::make_unique<NavigationEntryImpl>(
1907 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381908 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211909 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1910 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1911 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171912 UpdateNavigationEntryDetails(
1913 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001914 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1915 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171916
1917 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1918 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001919 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171920}
1921
Charlie Reisc0f17d2d2021-01-12 18:52:491922void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321923 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071924 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361925 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441926 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471927 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001928 NavigationRequest* request,
1929 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571930 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071931 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451932 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:521933 absl::optional<GURL> initiator_base_url;
1934 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
1935 initiator_base_url = request->common_params().initiator_base_url;
1936 }
Lukasz Anforowicz435bcb582019-07-12 20:50:061937
creisf49dfc92016-07-26 17:05:181938 // First check if this is an in-page navigation. If so, clone the current
1939 // entry instead of looking at the pending entry, because the pending entry
1940 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451941 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301942 FrameNavigationEntry* previous_frame_entry =
1943 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451944 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481945 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571946 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:081947 rfh->GetSiteInstance(), nullptr, params.url,
1948 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:211949 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:091950 request->GetRedirectChain(), params.page_state, params.method,
1951 params.post_id, nullptr /* blob_url_loader_factory */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:481952 request->GetSubresourceWebBundleNavigationInfo(),
Antonio Sartori78a749f2020-11-30 12:03:391953 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301954 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:571955 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:301956 // FrameNavigationEntry.
1957 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:571958 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:031959
creisf49dfc92016-07-26 17:05:181960 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:031961 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:521962 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1963 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571964 // TODO(jam): we had one report of this with a URL that was redirecting to
1965 // only tildes. Until we understand that better, don't copy the cert in
1966 // this case.
1967 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571968 }
creisf49dfc92016-07-26 17:05:181969
Patrick Monette50e8bd82019-06-13 22:40:451970 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1971 // that |frame_entry| should now have a reference count of exactly 2: one
1972 // due to the local variable |frame_entry|, and another due to |new_entry|
1973 // also retaining one. This should never fail, because it's the main frame.
1974 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181975 }
1976
Harkiran Bolaria59290d62021-03-17 01:53:011977 // If this is an activation navigation from a prerendered page, transfer the
1978 // new entry from an entry already created and stored in the
1979 // NavigationRequest. |new_entry| will not have been set prior to this as
1980 // |is_same_document| is mutually exclusive with
1981 // |IsPrerenderedPageActivation|.
1982 if (request->IsPrerenderedPageActivation()) {
1983 DCHECK(!is_same_document);
1984 DCHECK(!new_entry);
1985 new_entry = request->TakePrerenderNavigationEntry();
1986 DCHECK(new_entry);
1987 }
1988
Charlie Reisc0f17d2d2021-01-12 18:52:491989 // Only make a copy of the pending entry if it is appropriate for the new
1990 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451991 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041992 // 1. The SiteInstance hasn't been assigned to something else.
1993 // 2. The pending entry was intended as a new entry, rather than being a
1994 // history navigation that was interrupted by an unrelated,
1995 // renderer-initiated navigation.
1996 // TODO(csharrison): Investigate whether we can remove some of the coarser
1997 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451998 if (!new_entry && PendingEntryMatchesRequest(request) &&
1999 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342000 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432001 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352002 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432003
Camille Lamy62b826012019-02-26 09:15:472004 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452005 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182006 }
2007
Charlie Reisc0f17d2d2021-01-12 18:52:492008 // For cross-document commits with no matching pending entry, create a new
2009 // entry.
creisf49dfc92016-07-26 17:05:182010 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062011 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072012 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212013 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582014 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452015 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172016 nullptr, // blob_url_loader_factory
2017 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242018
2019 // Find out whether the new entry needs to update its virtual URL on URL
2020 // change and set up the entry accordingly. This is needed to correctly
2021 // update the virtual URL when replaceState is called after a pushState.
2022 GURL url = params.url;
2023 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492024 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412025 // update the virtual URL based on the new URL. For example, this is needed
2026 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2027 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372028 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2029 &url, browser_context_, &needs_update);
2030 new_entry->set_update_virtual_url_with_url(needs_update);
2031
Camille Lamy62b826012019-02-26 09:15:472032 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452033 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432034 }
2035
Harkiran Bolaria59290d62021-03-17 01:53:012036 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
2037 // for prerendered contents, if any. This is because prerendering/activation
2038 // technically won't be creating a new document. Unlike BFCache, prerendering
2039 // creates a new NavigationEntry rather than using an existing one.
2040 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372041 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2042 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002043 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082044
Harkiran Bolaria59290d62021-03-17 01:53:012045 // history.pushState() is classified as a navigation to a new page, but sets
2046 // is_same_document to true. In this case, we already have the title and
2047 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452048 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012049 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2050 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2051 }
[email protected]3a868f212014-08-09 10:41:192052 }
[email protected]ff64b3e2014-05-31 04:07:332053
[email protected]60d6cca2013-04-30 08:47:132054 DCHECK(!params.history_list_was_cleared || !replace_entry);
2055 // The browser requested to clear the session history when it initiated the
2056 // navigation. Now we know that the renderer has updated its state accordingly
2057 // and it is safe to also clear the browser side history.
2058 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552059 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132060 entries_.clear();
2061 last_committed_entry_index_ = -1;
2062 }
2063
Nasko Oskovaee2f862018-06-15 00:05:522064 // If this is a new navigation with replacement and there is a
2065 // pending_entry_ which matches the navigation reported by the renderer
2066 // process, then it should be the one replaced, so update the
2067 // last_committed_entry_index_ to use it.
2068 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092069 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522070 last_committed_entry_index_ = pending_entry_index_;
2071 }
2072
Alexander Timine3ec4192020-04-20 16:39:402073 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412074 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402075 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052076
Yuzu Saijoa725585f2022-11-28 04:14:032077 // If this is a history navigation and the old entry has an existing
2078 // back/forward cache metrics object, keep using the old one so that the
2079 // reasons logged from the last time the page navigated gets preserved.
2080 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2081 request)) {
2082 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2083 // because some tests do not have a pending entry.
2084 NavigationEntryImpl* entry =
2085 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2086 if (entry && entry->back_forward_cache_metrics()) {
2087 scoped_refptr<BackForwardCacheMetrics> metrics =
2088 entry->TakeBackForwardCacheMetrics();
2089 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2090 }
2091 }
2092
Carlos IL42b416592019-10-07 23:10:362093 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312094 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152095 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432096}
2097
Charlie Reisc0f17d2d2021-01-12 18:52:492098void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322099 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072100 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362101 bool is_same_document,
jam48cea9082017-02-15 06:13:292102 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452103 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002104 bool keep_pending_entry,
2105 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562106 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2107 << "that a last committed entry exists.";
2108
[email protected]e9ba4472008-09-14 15:42:432109 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002110 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432111
Charlie Reis7e2cb6d2021-01-26 01:27:162112 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002113 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162114 // We're guaranteed to have a last committed entry if intended_as_new_entry
2115 // is true.
avicbdc4c12015-07-01 16:07:112116 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162117
2118 // If the NavigationRequest matches a new pending entry and is classified as
2119 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2120 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092121 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162122 // Note: The pending entry will usually have a real ReloadType here, but
2123 // it can still be ReloadType::NONE in cases that
2124 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2125
2126 // If we classified this correctly, the SiteInstance should not have
2127 // changed.
2128 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2129
2130 // For converted reloads, we assign the entry's unique ID to be that of
2131 // the new one. Since this is always the result of a user action, we want
2132 // to dismiss infobars, etc. like a regular user-initiated navigation.
2133 entry->set_unique_id(pending_entry_->GetUniqueID());
2134
2135 // The extra headers may have changed due to reloading with different
2136 // headers.
2137 entry->set_extra_headers(pending_entry_->extra_headers());
2138 }
2139 // Otherwise, this was intended as a new entry but the pending entry was
2140 // lost in the meantime and no new entry was created. We are stuck at the
2141 // last committed entry.
2142
2143 // Even if this is a converted reload from pressing enter in the omnibox,
2144 // the server could redirect, requiring an update to the SSL status. If this
2145 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452146 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162147 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472148 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452149 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162150 }
Rakina Zata Amnif6950d552020-11-24 03:26:102151 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112152 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102153 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162154
eugenebut604866f2017-05-10 21:35:362155 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452156 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362157 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2158 // this was a restored same document navigation entry, then it won't have
2159 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2160 // navigated it.
jam48cea9082017-02-15 06:13:292161 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522162 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2163 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292164 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2165 was_restored) {
2166 entry->GetSSL() = last_entry->GetSSL();
2167 }
2168 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452169 // In rapid back/forward navigations |request| sometimes won't have a cert
2170 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192171 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452172 if (request->GetSSLInfo().has_value() &&
2173 request->GetSSLInfo()->is_valid()) {
2174 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522175 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2176 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192177 entry->GetSSL() = SSLStatus();
2178 }
jam48cea9082017-02-15 06:13:292179 }
avicbdc4c12015-07-01 16:07:112180 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272181 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572182 // navigations that are EXISTING_ENTRY are same-document navigations that
2183 // result in replacement (e.g. history.replaceState(), location.replace(),
2184 // forced replacements for trivial session history contexts). For these
2185 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112186 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102187
Mikel Astizba9cf2fd2017-12-17 10:38:102188 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2189 // to avoid misleading interpretations (e.g. URLs paired with
2190 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2191 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2192 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2193
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572194 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102195
eugenebut604866f2017-05-10 21:35:362196 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452197 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362198 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472199 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452200 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112201 }
2202 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432203
Rakina Zata Amni3460d382021-10-29 00:43:372204 UpdateNavigationEntryDetails(entry, rfh, params, request,
2205 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002206 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302207
[email protected]5ccd4dc2012-10-24 02:28:142208 // The redirected to page should not inherit the favicon from the previous
2209 // page.
eugenebut604866f2017-05-10 21:35:362210 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482211 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142212
Charlie Reis951f43372023-05-05 00:30:072213 // Update the last committed index to reflect the committed entry. Do this
2214 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2215 // delegate sees the correct committed index when notified of navigation
2216 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2217 // https://crbug.com/1439948.)
2218 if (base::FeatureList::IsEnabled(
2219 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2220 last_committed_entry_index_ = GetIndexOfEntry(entry);
2221 }
2222
Peter Boströmd7592132019-01-30 04:50:312223 // We should also usually discard the pending entry if it corresponds to a
2224 // different navigation, since that one is now likely canceled. In rare
2225 // cases, we leave the pending entry for another navigation in place when we
2226 // know it is still ongoing, to avoid a flicker in the omnibox (see
2227 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432228 //
2229 // Note that we need to use the "internal" version since we don't want to
2230 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312231 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002232 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392233
Charlie Reis951f43372023-05-05 00:30:072234 if (!base::FeatureList::IsEnabled(
2235 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2236 // Update the last committed index to reflect the committed entry.
2237 // (This is legacy behavior, in case the kill-switch needs to be used.)
2238 last_committed_entry_index_ = GetIndexOfEntry(entry);
2239 }
[email protected]e9ba4472008-09-14 15:42:432240}
2241
[email protected]d202a7c2012-01-04 07:53:472242void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322243 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072244 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362245 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472246 bool replace_entry,
2247 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002248 NavigationRequest* request,
2249 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262250 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2251 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552252 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2253 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112254
[email protected]e9ba4472008-09-14 15:42:432255 // Manual subframe navigations just get the current entry cloned so the user
2256 // can go back or forward to it. The actual subframe information will be
2257 // stored in the page state for each of those entries. This happens out of
2258 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092259 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2260 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382261
Mikel Astizba9cf2fd2017-12-17 10:38:102262 // The DCHECK below documents the fact that we don't know of any situation
2263 // where |replace_entry| is true for subframe navigations. This simplifies
2264 // reasoning about the replacement struct for subframes (see
2265 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2266 DCHECK(!replace_entry);
2267
Patrick Monette50e8bd82019-06-13 22:40:452268 // This FrameNavigationEntry might not end up being used in the
2269 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072270 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452271 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:522272 absl::optional<GURL> initiator_base_url;
2273 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2274 initiator_base_url = request->common_params().initiator_base_url;
2275 }
Nate Chapin63db0d12022-01-20 22:03:302276 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2277 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2278 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572279 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302280 if (is_same_document) {
2281 FrameNavigationEntry* previous_frame_entry =
2282 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572283 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302284 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572285 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302286 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572287 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302288 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572289 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302290 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572291 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302292 policy_container_policies->referrer_policy);
2293 }
2294
Patrick Monette50e8bd82019-06-13 22:40:452295 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482296 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572297 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082298 rfh->GetSiteInstance(), nullptr, params.url,
2299 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212300 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2301 request->GetRedirectChain(), params.page_state, params.method,
2302 params.post_id, nullptr /* blob_url_loader_factory */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482303 request->GetSubresourceWebBundleNavigationInfo(),
Domenic Denicolacc094fb2022-03-16 23:40:572304 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032305
creisce0ef3572017-01-26 17:53:082306 std::unique_ptr<NavigationEntryImpl> new_entry =
2307 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452308 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032309 frame_tree_->root());
creise062d542015-08-25 02:01:552310
Alexander Timine3ec4192020-04-20 16:39:402311 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412312 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402313 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472314
creisce0ef3572017-01-26 17:53:082315 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452316 // to replace, which can happen due to a unique name change. See
2317 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2318 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382319
Dave Tapuska87696ae2021-11-18 18:48:312320 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152321 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432322}
2323
[email protected]d202a7c2012-01-04 07:53:472324bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322325 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072326 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392327 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252328 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002329 NavigationRequest* request,
2330 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292331 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2332 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2333
[email protected]e9ba4472008-09-14 15:42:432334 // We're guaranteed to have a previously committed entry, and we now need to
2335 // handle navigation inside of a subframe in it without creating a new entry.
2336 DCHECK(GetLastCommittedEntry());
2337
creis913c63ce2016-07-16 19:52:522338 // For newly created subframes, we don't need to send a commit notification.
2339 // This is only necessary for history navigations in subframes.
2340 bool send_commit_notification = false;
2341
Rakina Zata Amnif6950d552020-11-24 03:26:102342 // If |nav_entry_id| is non-zero and matches an existing entry, this
2343 // is a history navigation. Update the last committed index accordingly. If
2344 // we don't recognize the |nav_entry_id|, it might be a recently
2345 // pruned entry. We'll handle it below.
2346 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2347 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472348 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062349 // Make sure that a subframe commit isn't changing the main frame's
2350 // origin. Otherwise the renderer process may be confused, leading to a
2351 // URL spoof. We can't check the path since that may change
2352 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572353 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2354 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242355 // We should use checks similar to RenderFrameHostImpl's
2356 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2357 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572358 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2359 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2360 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2361 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522362 current_top_url.DeprecatedGetOriginAsURL() !=
2363 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442364 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512365 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062366 }
creis3cdc3b02015-05-29 23:00:472367
creis913c63ce2016-07-16 19:52:522368 // We only need to discard the pending entry in this history navigation
2369 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062370 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002371 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522372
2373 // History navigations should send a commit notification.
2374 send_commit_notification = true;
avi98405c22015-05-21 20:47:062375 }
[email protected]e9ba4472008-09-14 15:42:432376 }
[email protected]f233e4232013-02-23 00:55:142377
creisce0ef3572017-01-26 17:53:082378 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2379 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372380 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2381 // exists), or we may want to clobber it and create a new one. We update in
2382 // cases where the corresponding FrameNavigationEntry is conceptually similar
2383 // to the document described by the commit params: same-document
2384 // navigations, history traversal to an existing entry, and reloads (including
2385 // a "soft reload" where we navigate to the same url without flagging it as a
2386 // reload). But in the case of a different document that is not logically
2387 // related to the committed FrameNavigationEntry's document (cross-document,
2388 // not same url, not a reload, not a history traversal), we replace rather
2389 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252390 //
Nate Chapin9f169072021-06-09 19:32:372391 // In the case where we update, the FrameNavigationEntry will potentially be
2392 // shared across multiple NavigationEntries, and any updates will be reflected
2393 // in all of those NavigationEntries. In the replace case, any existing
2394 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252395 //
2396 // When navigating away from the initial empty document, we also update rather
2397 // than replace. Either update or replace will overwrite the initial empty
2398 // document state for |last_committed|, but if the FrameNavigationEntry for
2399 // the initial empty document is shared across multiple NavigationEntries (due
2400 // to a navigation in another frame), we want to make sure we overwrite the
2401 // initial empty document state everywhere this FrameNavigationEntry is used,
2402 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452403 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372404 FrameNavigationEntry* last_committed_frame_entry =
2405 last_committed->GetFrameEntry(rfh->frame_tree_node());
2406 NavigationEntryImpl::UpdatePolicy update_policy =
2407 NavigationEntryImpl::UpdatePolicy::kUpdate;
2408 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312409 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372410 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252411 last_committed_frame_entry->url() != params.url &&
2412 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372413 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2414 }
2415
Rakina Zata Amni3460d382021-10-29 00:43:372416 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002417 update_policy, false /* is_new_entry */,
2418 commit_details);
creis625a0c7d2015-03-24 23:17:122419
creis913c63ce2016-07-16 19:52:522420 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432421}
2422
[email protected]d202a7c2012-01-04 07:53:472423int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232424 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032425 for (size_t i = 0; i < entries_.size(); ++i) {
2426 if (entries_[i].get() == entry)
2427 return i;
2428 }
2429 return -1;
[email protected]765b35502008-08-21 00:51:202430}
2431
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572432void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242433 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572434 NavigationControllerImpl* source =
2435 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572436 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382437 DCHECK_EQ(1, GetEntryCount());
2438 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472439 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172440 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572441
Francois Dorayeaace782017-06-21 16:37:242442 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442443 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572444 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572445
Fergal Dalya1d569972021-03-16 03:24:532446 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302447 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532448 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2449 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302450 }
[email protected]4e6419c2010-01-15 04:50:342451
Lukasz Anforowicz0de0f452020-12-02 19:57:152452 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572453}
2454
Aran Gilman37d11632019-10-08 23:07:152455void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2456 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162457 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012458 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162459
[email protected]d202a7c2012-01-04 07:53:472460 NavigationControllerImpl* source =
2461 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252462
avi2b177592014-12-10 02:08:022463 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012464 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252465
[email protected]474f8512013-05-31 22:31:162466 // We now have one entry, possibly with a new pending entry. Ensure that
2467 // adding the entries from source won't put us over the limit.
2468 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572469 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572470 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252471
Carlos IL4dea8902020-05-26 15:14:292472 // Insert the entries from source. Ignore any pending entry, since it has not
2473 // committed in source.
[email protected]474f8512013-05-31 22:31:162474 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172475 DCHECK_NE(max_source_index, -1);
2476 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572477
2478 // Ignore the source's current entry if merging with replacement.
2479 // TODO(davidben): This should preserve entries forward of the current
2480 // too. http://crbug.com/317872
2481 if (replace_entry && max_source_index > 0)
2482 max_source_index--;
2483
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572484 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252485
2486 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552487 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142488
Hayato Ito2c8c08d02021-06-23 03:38:432489 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252490}
2491
[email protected]79368982013-11-13 01:11:012492bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162493 // If there is no last committed entry, we cannot prune. Even if there is a
2494 // pending entry, it may not commit, leaving this WebContents blank, despite
2495 // possibly giving it new entries via CopyStateFromAndPrune.
2496 if (last_committed_entry_index_ == -1)
2497 return false;
[email protected]9350602e2013-02-26 23:27:442498
[email protected]474f8512013-05-31 22:31:162499 // We cannot prune if there is a pending entry at an existing entry index.
2500 // It may not commit, so we have to keep the last committed entry, and thus
2501 // there is no sensible place to keep the pending entry. It is ok to have
2502 // a new pending entry, which can optionally commit as a new navigation.
2503 if (pending_entry_index_ != -1)
2504 return false;
2505
[email protected]474f8512013-05-31 22:31:162506 return true;
2507}
2508
[email protected]79368982013-11-13 01:11:012509void NavigationControllerImpl::PruneAllButLastCommitted() {
2510 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162511
avi2b177592014-12-10 02:08:022512 DCHECK_EQ(0, last_committed_entry_index_);
2513 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442514
Hayato Ito2c8c08d02021-06-23 03:38:432515 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442516}
2517
[email protected]79368982013-11-13 01:11:012518void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162519 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012520 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262521
Nate Chapin9eb16be72022-09-23 22:54:312522 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2523
[email protected]474f8512013-05-31 22:31:162524 // Erase all entries but the last committed entry. There may still be a
2525 // new pending entry after this.
2526 entries_.erase(entries_.begin(),
2527 entries_.begin() + last_committed_entry_index_);
2528 entries_.erase(entries_.begin() + 1, entries_.end());
2529 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262530}
2531
Christian Dullweber1af31e62018-02-22 11:49:482532void NavigationControllerImpl::DeleteNavigationEntries(
2533 const DeletionPredicate& deletionPredicate) {
2534 // It is up to callers to check the invariants before calling this.
2535 CHECK(CanPruneAllButLastCommitted());
2536 std::vector<int> delete_indices;
2537 for (size_t i = 0; i < entries_.size(); i++) {
2538 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572539 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482540 delete_indices.push_back(i);
2541 }
2542 }
2543 if (delete_indices.empty())
2544 return;
2545
2546 if (delete_indices.size() == GetEntryCount() - 1U) {
2547 PruneAllButLastCommitted();
2548 } else {
2549 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382550 for (const auto& index : base::Reversed(delete_indices)) {
2551 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482552 }
Hayato Ito2c8c08d02021-06-23 03:38:432553 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482554 }
2555 delegate()->NotifyNavigationEntriesDeleted();
2556}
2557
Shivani Sharma883f5f32019-02-12 18:20:012558bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2559 auto* entry = GetEntryAtIndex(index);
2560 return entry && entry->should_skip_on_back_forward_ui();
2561}
2562
Carlos Caballero35ce710c2019-09-19 10:59:452563BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2564 return back_forward_cache_;
2565}
2566
William Liu055a3542023-04-02 17:21:192567NavigationEntryScreenshotCache*
2568NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
2569 CHECK_EQ(frame_tree_->type(), FrameTree::Type::kPrimary);
2570 if (!nav_entry_screenshot_cache_ && AreBackForwardTransitionsEnabled()) {
2571 nav_entry_screenshot_cache_ =
2572 std::make_unique<NavigationEntryScreenshotCache>(
2573 BrowserContextImpl::From(browser_context_)
2574 ->GetNavigationEntryScreenshotManager()
2575 ->GetSafeRef(),
2576 this);
2577 }
2578 return nav_entry_screenshot_cache_.get();
2579}
2580
clamy987a3752018-05-03 17:36:262581void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2582 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2583 // progress, since this will cause a use-after-free. (We only allow this
2584 // when the tab is being destroyed for shutdown, since it won't return to
2585 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032586 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262587
2588 if (was_failure && pending_entry_) {
2589 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2590 } else {
2591 failed_pending_entry_id_ = 0;
2592 }
2593
2594 if (pending_entry_) {
2595 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332596 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262597 pending_entry_index_ = -1;
2598 pending_entry_ = nullptr;
2599 }
arthursonzogni66f711c2019-10-08 14:40:362600
2601 // Ensure any refs to the current pending entry are ignored if they get
2602 // deleted, by clearing the set of known refs. All future pending entries will
2603 // only be affected by new refs.
2604 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262605}
2606
2607void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2608 if (pending_entry_)
2609 pending_entry_->set_ssl_error(error);
2610}
2611
Xiaohan Wang7f8052e02022-01-14 18:44:282612#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422613// static
2614bool NavigationControllerImpl::ValidateDataURLAsString(
2615 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2616 if (!data_url_as_string)
2617 return false;
2618
2619 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2620 return false;
2621
2622 // The number of characters that is enough for validating a data: URI.
2623 // From the GURL's POV, the only important part here is scheme, it doesn't
2624 // check the actual content. Thus we can take only the prefix of the url, to
2625 // avoid unneeded copying of a potentially long string.
2626 const size_t kDataUriPrefixMaxLen = 64;
2627 GURL data_url(
2628 std::string(data_url_as_string->front_as<char>(),
2629 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2630 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2631 return false;
2632
2633 return true;
2634}
2635#endif
2636
Shivani Sharma194877032019-03-07 17:52:472637void NavigationControllerImpl::NotifyUserActivation() {
2638 // When a user activation occurs, ensure that all adjacent entries for the
2639 // same document clear their skippable bit, so that the history manipulation
2640 // intervention does not apply to them.
shivanigithub99368382021-06-16 18:33:372641 if (base::FeatureList::IsEnabled(
2642 features::kDebugHistoryInterventionNoUserActivation)) {
2643 return;
2644 }
2645
Shivani Sharmac4cc8922019-04-18 03:11:172646 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472647}
2648
clamy987a3752018-05-03 17:36:262649bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2650 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332651 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2652 blink::LocalFrameToken initiator_frame_token,
2653 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262654 NavigationEntryImpl* entry =
2655 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2656 if (!entry)
2657 return false;
2658
2659 FrameNavigationEntry* frame_entry =
2660 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2661 if (!frame_entry)
2662 return false;
2663
Camille Lamy5193caa2018-10-12 11:59:422664 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572665 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232666 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332667 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2668 initiator_process_id);
clamyea99ea12018-05-28 13:54:232669
2670 if (!request)
2671 return false;
2672
arthursonzognif046d4a2019-12-12 19:08:102673 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412674
Rakina Zata Amni1c83b082023-02-08 01:09:002675 SCOPED_CRASH_KEY_STRING256(
2676 "Bug1400009", "req_url",
2677 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2678 SCOPED_CRASH_KEY_NUMBER(
2679 "Bug1400009", "nav_entry_si",
2680 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2681 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2682 frame_entry->site_instance()
2683 ? ((int)frame_entry->site_instance()->GetId())
2684 : -1);
2685 bool has_sig =
2686 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2687 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2688 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2689 has_sig ? (!!frame_tree_->GetRenderViewHost(
2690 frame_entry->site_instance()->group()))
2691 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052692 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2693 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232694
2695 return true;
clamy987a3752018-05-03 17:36:262696}
2697
Tsuyoshi Horo52fd08e2020-07-07 07:03:452698bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2699 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2700 if (!entry)
2701 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432702
2703 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2704 // We should never navigate to an existing initial NavigationEntry that is
2705 // the initial NavigationEntry for the initial empty document that hasn't
2706 // been overridden by the synchronous about:blank commit, to preserve
2707 // legacy behavior where trying to reload when the main frame is on the
2708 // initial empty document won't result in a navigation. See also
2709 // https://crbug.com/1277414.
2710 return false;
2711 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452712 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2713 if (!frame_entry)
2714 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142715 ReloadType reload_type = ReloadType::NORMAL;
2716 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452717 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142718 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452719 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432720 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332721 absl::nullopt /* initiator_frame_token */,
2722 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452723 if (!request)
2724 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052725 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452726 return true;
2727}
2728
clamy987a3752018-05-03 17:36:262729void NavigationControllerImpl::NavigateFromFrameProxy(
2730 RenderFrameHostImpl* render_frame_host,
2731 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022732 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452733 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072734 const absl::optional<url::Origin>& initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212735 const absl::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262736 bool is_renderer_initiated,
2737 SiteInstance* source_site_instance,
2738 const Referrer& referrer,
2739 ui::PageTransition page_transition,
2740 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252741 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262742 const std::string& method,
2743 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092744 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142745 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212746 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502747 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392748 const absl::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292749 blink::mojom::NavigationInitiatorActivationAndAdStatus
2750 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222751 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492752 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462753 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452754 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582755 bool is_container_initiated,
2756 absl::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582757 if (is_renderer_initiated)
2758 DCHECK(initiator_origin.has_value());
2759
clamy987a3752018-05-03 17:36:262760 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582761
Rakina Zata Amni2322f4f82022-01-24 13:24:242762 // Don't allow an entry replacement if there is no entry to replace.
2763 // http://crbug.com/457149
2764 if (GetEntryCount() == 0)
2765 should_replace_current_entry = false;
2766
clamy987a3752018-05-03 17:36:262767 // Create a NavigationEntry for the transfer, without making it the pending
2768 // entry. Subframe transfers should have a clone of the last committed entry
2769 // with a FrameNavigationEntry for the target frame. Main frame transfers
2770 // should have a new NavigationEntry.
2771 // TODO(creis): Make this unnecessary by creating (and validating) the params
2772 // directly, passing them to the destination RenderFrameHost. See
2773 // https://crbug.com/536906.
2774 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262775 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262776 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452777 DCHECK(GetLastCommittedEntry());
2778 entry = GetLastCommittedEntry()->Clone();
2779 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172780 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2781 // Renderer-initiated navigation that target a remote frame are currently
2782 // classified as browser-initiated when this one has already navigated.
2783 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372784 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2785 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2786 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2787 // same-document navigation), they will still be present in the
2788 // committed NavigationEntry that will be referenced to construct the new
2789 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262790 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082791 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582792 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072793 absl::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212794 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto22a27b142023-02-10 06:42:492795 blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482796 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori79d549d2021-02-18 12:59:542797 nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262798 } else {
2799 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172800 // If `node` is the outermost main frame, it rewrites a virtual url in order
2801 // to adjust the original input url if needed. For inner frames such as
2802 // fenced frames or subframes, they don't rewrite urls as the urls are not
2803 // input urls by users.
2804 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:322805 absl::optional<GURL> source_process_site_url = absl::nullopt;
2806 if (source_site_instance && source_site_instance->HasProcess()) {
2807 source_process_site_url =
2808 source_site_instance->GetProcess()->GetProcessLock().site_url();
2809 }
clamy987a3752018-05-03 17:36:262810 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212811 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322812 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212813 extra_headers, browser_context_, blob_url_loader_factory,
2814 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262815 entry->root_node()->frame_entry->set_source_site_instance(
2816 static_cast<SiteInstanceImpl*>(source_site_instance));
2817 entry->root_node()->frame_entry->set_method(method);
2818 }
clamy987a3752018-05-03 17:36:262819
Camille Lamy5193caa2018-10-12 11:59:422820 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452821 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262822 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422823 override_user_agent = true;
clamy987a3752018-05-03 17:36:262824 }
2825 // TODO(creis): Set user gesture and intent received timestamp on Android.
2826
2827 // We may not have successfully added the FrameNavigationEntry to |entry|
2828 // above (per https://crbug.com/608402), in which case we create it from
2829 // scratch. This works because we do not depend on |frame_entry| being inside
2830 // |entry| during NavigateToEntry. This will go away when we shortcut this
2831 // further in https://crbug.com/536906.
2832 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2833 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452834 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082835 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582836 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072837 absl::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212838 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto22a27b142023-02-10 06:42:492839 blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482840 nullptr /* subresource_web_bundle_navigation_info */,
Nate Chapin63db0d12022-01-20 22:03:302841 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572842 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262843 }
2844
Camille Lamy5193caa2018-10-12 11:59:422845 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022846 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452847 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292848 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212849 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422850 params.source_site_instance = source_site_instance;
2851 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2852 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032853 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422854 params.referrer = referrer;
2855 /* params.redirect_chain: skip */
2856 params.extra_headers = extra_headers;
2857 params.is_renderer_initiated = is_renderer_initiated;
2858 params.override_user_agent = UA_OVERRIDE_INHERIT;
2859 /* params.base_url_for_data_url: skip */
2860 /* params.virtual_url_for_data_url: skip */
2861 /* params.data_url_as_string: skip */
2862 params.post_data = post_body;
2863 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582864 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422865 /* params.frame_name: skip */
2866 // TODO(clamy): See if user gesture should be propagated to this function.
2867 params.has_user_gesture = false;
2868 params.should_clear_history_list = false;
2869 params.started_from_context_menu = false;
2870 /* params.navigation_ui_data: skip */
2871 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222872 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542873 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212874 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412875 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502876 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292877 params.initiator_activation_and_ad_status =
2878 initiator_activation_and_ad_status;
Camille Lamy5193caa2018-10-12 11:59:422879
2880 std::unique_ptr<NavigationRequest> request =
2881 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032882 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142883 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392884 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492885 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582886 is_unfenced_top_navigation, is_container_initiated,
2887 embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232888
2889 if (!request)
2890 return;
2891
Garrett Tanzerbb8db412022-09-27 21:59:462892 // Force the navigation to take place in a new browsing instance.
2893 // This is used by _unfencedTop in fenced frames to ensure that navigations
2894 // leaving the fenced context create a new browsing instance.
2895 if (force_new_browsing_instance) {
2896 request->coop_status().ForceBrowsingInstanceSwap();
2897 }
2898
Arthur Hemery948742762019-09-18 10:06:242899 // At this stage we are proceeding with this navigation. If this was renderer
2900 // initiated with user gesture, we need to make sure we clear up potential
2901 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2902 DiscardNonCommittedEntries();
2903
Lukasz Anforowicz9ee83c272020-12-01 20:14:052904 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262905}
2906
[email protected]d1198fd2012-08-13 22:50:192907void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252908 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212909 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192910 if (!session_storage_namespace)
2911 return;
2912
2913 // We can't overwrite an existing SessionStorage without violating spec.
2914 // Attempts to do so may give a tab access to another tab's session storage
2915 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152916 bool successful_insert =
2917 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252918 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052919 static_cast<SessionStorageNamespaceImpl*>(
2920 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302921 .second;
2922 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192923}
2924
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572925bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452926 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032927 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462928}
2929
Aran Gilman37d11632019-10-08 23:07:152930SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252931 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302932 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252933 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032934 DOMStorageContextWrapper* context_wrapper =
2935 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2936
2937 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252938 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032939 if (it != session_storage_namespace_map_.end()) {
2940 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152941 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2942 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472943
michaelnbacbcbd2016-02-09 00:32:032944 return it->second.get();
2945 }
2946
2947 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102948 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2949 SessionStorageNamespaceImpl::Create(context_wrapper);
2950 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2951 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252952 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102953 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302954
Daniel Murphy31bbb8b12018-02-07 21:44:102955 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302956}
2957
2958SessionStorageNamespace*
2959NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252960 return GetSessionStorageNamespace(
2961 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302962}
2963
2964const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572965NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302966 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552967}
[email protected]d202a7c2012-01-04 07:53:472968
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572969bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562970 return needs_reload_;
2971}
[email protected]a26023822011-12-29 00:23:552972
[email protected]46bb5e9c2013-10-03 22:16:472973void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412974 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2975}
2976
2977void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472978 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412979 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542980
2981 if (last_committed_entry_index_ != -1) {
2982 entries_[last_committed_entry_index_]->SetTransitionType(
2983 ui::PAGE_TRANSITION_RELOAD);
2984 }
[email protected]46bb5e9c2013-10-03 22:16:472985}
2986
[email protected]d202a7c2012-01-04 07:53:472987void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572988 DCHECK_LT(index, GetEntryCount());
2989 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312990 DiscardNonCommittedEntries();
2991
Nate Chapin9eb16be72022-09-23 22:54:312992 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:312993 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122994 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312995 last_committed_entry_index_--;
2996}
2997
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572998NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272999 // If there is no pending_entry_, there should be no pending_entry_index_.
3000 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3001
3002 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363003 // at that index. An exception is while a reload of a post commit error page
3004 // is ongoing; in that case pending entry will point to the entry replaced
3005 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273006 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363007 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3008 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273009
[email protected]022af742011-12-28 18:37:253010 return pending_entry_;
3011}
3012
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573013int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273014 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273015 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553016 return pending_entry_index_;
3017}
3018
avi25764702015-06-23 15:43:373019void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573020 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363021 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313022 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003023 bool in_fenced_frame_tree,
3024 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313025 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3026 // set because:
3027 // 1) They don't influence the history of the outer page.
3028 // 2) They are always replace only navigation (there is always only one entry
3029 // in their history stack).
3030 // 3) Are not top level navigations and appear similar to iframes.
3031 // Navigations of the fenced frame might create a new NavigationEntry, which
3032 // will call this function. Non fenced frame navigations will never have
3033 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3034 // InsertOrReplaceEntry.
3035 DCHECK_EQ(in_fenced_frame_tree,
3036 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3037 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203038
avi5cad4912015-06-19 05:25:443039 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3040 // need to keep continuity with the pending entry, so copy the pending entry's
3041 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3042 // then the renderer navigated on its own, independent of the pending entry,
3043 // so don't copy anything.
3044 if (pending_entry_ && pending_entry_index_ == -1)
3045 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203046
Rakina Zata Amnia4e27222021-12-22 01:05:003047 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203048
creisee17e932015-07-17 17:56:223049 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453050 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103051 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573052 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363053 // If the new entry is a post-commit error page, we store the current last
3054 // committed entry to the side so that we can put it back when navigating
3055 // away from the error.
3056 if (was_post_commit_error) {
3057 DCHECK(!entry_replaced_by_post_commit_error_);
3058 entry_replaced_by_post_commit_error_ =
3059 std::move(entries_[last_committed_entry_index_]);
3060 }
dcheng36b6aec92015-12-26 06:16:363061 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223062 return;
3063 }
[email protected]765b35502008-08-21 00:51:203064
creis37979a62015-08-04 19:48:183065 // We shouldn't see replace == true when there's no committed entries.
3066 DCHECK(!replace);
3067
Michael Thiessen9b14d512019-09-23 21:19:473068 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203069
Shivani Sharmad8c8d652019-02-13 17:27:573070 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203071
dcheng36b6aec92015-12-26 06:16:363072 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203073 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293074}
3075
Shivani Sharmad8c8d652019-02-13 17:27:573076void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163077 if (entries_.size() < max_entry_count())
3078 return;
3079
3080 DCHECK_EQ(max_entry_count(), entries_.size());
3081 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573082 CHECK_EQ(pending_entry_index_, -1);
3083
3084 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423085 // Retrieve the oldest skippable entry.
3086 for (; index < GetEntryCount(); index++) {
3087 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3088 break;
Shivani Sharmad8c8d652019-02-13 17:27:573089 }
3090
3091 // If there is no skippable entry or if it is the last committed entry then
3092 // fall back to pruning the oldest entry. It is not safe to prune the last
3093 // committed entry.
3094 if (index == GetEntryCount() || index == last_committed_entry_index_)
3095 index = 0;
3096
3097 bool should_succeed = RemoveEntryAtIndex(index);
3098 DCHECK_EQ(true, should_succeed);
3099
3100 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253101}
3102
clamy3cb9bea92018-07-10 12:42:023103void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163104 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203105 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:133106 absl::optional<blink::scheduler::TaskAttributionId>
3107 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203108 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503109 TRACE_EVENT0("navigation",
3110 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273111 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023112 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363113 if (pending_entry_index_ != -1) {
3114 // The pending entry may not be in entries_ if a post-commit error page is
3115 // showing.
3116 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3117 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3118 }
Gyuyoung Kim107c2a02021-04-13 01:49:303119 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573120 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013121 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033122 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573123 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133124 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3125 // the same as the top level frame being navigated.
3126 if (root->current_frame_host() != initiator_rfh) {
3127 soft_navigation_heuristics_task_id = absl::nullopt;
3128 }
Arthur Sonzogni620cec62018-12-13 13:08:573129
[email protected]83c2e232011-10-07 21:36:463130 // If we were navigating to a slow-to-commit page, and the user performs
3131 // a session history navigation to the last committed page, RenderViewHost
3132 // will force the throbber to start, but WebKit will essentially ignore the
3133 // navigation, and won't send a message to stop the throbber. To prevent this
3134 // from happening, we drop the navigation here and stop the slow-to-commit
3135 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023136 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083137 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273138 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033139 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123140
[email protected]83c2e232011-10-07 21:36:463141 DiscardNonCommittedEntries();
3142 return;
3143 }
3144
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333145 absl::optional<blink::LocalFrameToken> initiator_frame_token;
3146 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3147 if (initiator_rfh) {
3148 initiator_frame_token = initiator_rfh->GetFrameToken();
3149 initiator_process_id = initiator_rfh->GetProcess()->GetID();
3150 DCHECK(initiator_frame_token);
3151 }
3152
creisce0ef3572017-01-26 17:53:083153 // Compare FrameNavigationEntries to see which frames in the tree need to be
3154 // navigated.
clamy3cb9bea92018-07-10 12:42:023155 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3156 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333157 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3158 initiator_process_id, soft_navigation_heuristics_task_id,
3159 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303160
3161 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573162 // We were unable to match any frames to navigate. This can happen if a
3163 // history navigation targets a subframe that no longer exists
3164 // (https://crbug.com/705550). In this case, we need to update the current
3165 // history entry to the pending one but keep the main document loaded. We
3166 // also need to ensure that observers are informed about the updated
3167 // current history entry (e.g., for greying out back/forward buttons), and
3168 // that renderer processes update their history offsets. The easiest way
3169 // to do all that is to schedule a "redundant" same-document navigation in
3170 // the main frame.
3171 //
3172 // Note that we don't want to remove this history entry, as it might still
3173 // be valid later, since a frame that it's targeting may be recreated.
3174 //
3175 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3176 // need to repeat history navigations until finding the one that works.
3177 // Consider changing this behavior to keep looking for the first valid
3178 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023179 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423180 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573181 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573182 ReloadType::NONE /* reload_type */,
3183 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433184 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333185 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023186 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573187 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023188 DiscardPendingEntry(false);
3189 return;
3190 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573191 same_document_loads.push_back(std::move(navigation_request));
3192
3193 // Sanity check that we never take this branch for any kinds of reloads,
3194 // as those should've queued a different-document load in the main frame.
3195 DCHECK(!is_forced_reload);
3196 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303197 }
3198
Nate Chapinbf682fa32022-09-26 22:41:203199 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163200 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203201 if (initiator_rfh && initiator_rfh->IsSandboxed(
3202 network::mojom::WebSandboxFlags::kTopNavigation)) {
3203 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3204 initiator_rfh, same_document_loads) &&
3205 DoesSandboxNavigationStayWithinSubtree(
3206 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503207 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163208 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203209 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3210 initiator_rfh,
3211 navigates_inside_tree
3212 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3213 : blink::mojom::WebFeature::
3214 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523215
3216 // If the navigation occurred outside the tree discard it because
3217 // the sandboxed frame didn't have permission to navigate outside
3218 // its tree. If it is possible that the navigation is both inside and
3219 // outside the frame tree and we discard it entirely because we don't
3220 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143221 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203222 // If a |navigation_api_key| was provided, this navigation originated from
3223 // the navigation API. Notify the renderer that the navigation was
3224 // cancelled so the navigation API can fire an error event and reject the
3225 // relevant promise.
3226 if (navigation_api_key) {
3227 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3228 *navigation_api_key,
3229 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3230 }
Dave Tapuska855c1e12019-08-23 20:45:523231 DiscardPendingEntry(false);
3232 return;
3233 }
Dave Tapuska8bfd84c2019-03-26 20:47:163234 }
3235
Nate Chapin6c43c022023-02-13 23:32:423236 // If it is possible that this traverse may involve a same-document navigation
3237 // in the initiator and there is a Navigation API key involved, then we may
3238 // need to notify the initiator if it fails. (The early returns above either
3239 // do not involve these cases or already notify the initiator.)
3240 // The event only needs to fire for the initiator, and only if the initiator
3241 // itself is performing a same-document navigation (because the event will not
3242 // fire if it navigates cross-document).
3243 if (navigation_api_key) {
3244 for (auto& item : same_document_loads) {
3245 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3246 item->set_pending_navigation_api_key(*navigation_api_key);
3247 break;
3248 }
3249 }
3250 }
3251
Carlos Caballero539a421c2020-07-06 10:25:573252 // BackForwardCache:
3253 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563254 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573255 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3256 DCHECK_EQ(reload_type, ReloadType::NONE);
3257 auto navigation_request = CreateNavigationRequestFromEntry(
3258 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3259 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333260 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3261 initiator_process_id);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053262 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573263
3264 return;
3265 }
3266
3267 // History navigation might try to reuse a specific BrowsingInstance, already
3268 // used by a page in the cache. To avoid having two different main frames that
3269 // live in the same BrowsingInstance, evict the all pages with this
3270 // BrowsingInstance from the cache.
3271 //
3272 // For example, take the following scenario:
3273 //
3274 // A1 = Some page on a.com
3275 // A2 = Some other page on a.com
3276 // B3 = An uncacheable page on b.com
3277 //
3278 // Then the following navigations occur:
3279 // A1->A2->B3->A1
3280 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3281 // take its place) and A1 will be created in the same BrowsingInstance (and
3282 // SiteInstance), as A2.
3283 //
3284 // If we didn't do anything, both A1 and A2 would remain alive in the same
3285 // BrowsingInstance/SiteInstance, which is unsupported by
3286 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3287 // A2 from the cache.
3288 if (pending_entry_->site_instance()) {
3289 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3290 pending_entry_->site_instance());
3291 }
3292
Rakina Zata Amnid605d462022-06-01 10:17:033293 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3294 pending_entry_ && pending_entry_->IsRestored());
3295 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3296 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3297 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3298 pending_entry_index_);
3299 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3300 last_committed_entry_index_);
3301 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3302 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3303 pending_entry_ && pending_entry_->IsInitialEntry());
3304 SCOPED_CRASH_KEY_BOOL(
3305 "nav_reentrancy", "pending_entry_initial2",
3306 pending_entry_ &&
3307 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3308 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3309 IsInitialNavigation());
3310 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3311 IsInitialBlankNavigation());
3312 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3313 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3314 (int)pending_reload_);
3315
clamy3cb9bea92018-07-10 12:42:023316 // This call does not support re-entrancy. See http://crbug.com/347742.
3317 CHECK(!in_navigate_to_pending_entry_);
3318 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303319
Rakina Zata Amnid605d462022-06-01 10:17:033320 // If the navigation-reentrancy is caused by calling
3321 // NavigateToExistingPendingEntry twice, this will note the previous call's
3322 // pending entry's ID.
3323 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3324 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3325
arthursonzogni66f711c2019-10-08 14:40:363326 // It is not possible to delete the pending NavigationEntry while navigating
3327 // to it. Grab a reference to delay potential deletion until the end of this
3328 // function.
3329 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3330
Nate Chapin154b14b2023-02-17 18:28:163331 // If there is a main-frame same-document history navigation, we may defer
3332 // the subframe history navigations in order to give JS in the main frame the
3333 // opportunity to cancel the entire traverse via the navigate event. In that
3334 // case, we need to stash the main frame request's navigation token on the
3335 // subframes, so they can look up the main frame request and defer themselves
3336 // until it completes.
3337 if (!same_document_loads.empty() &&
3338 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3339 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3340 // The token will only be returned in cases where deferring the navigation
3341 // is necessary.
3342 if (auto main_frame_same_document_token =
3343 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3344 for (auto& item : same_document_loads) {
3345 if (item.get() != main_frame_request) {
3346 item->set_main_frame_same_document_history_token(
3347 main_frame_same_document_token);
3348 }
3349 }
3350 for (auto& item : different_document_loads) {
3351 item->set_main_frame_same_document_history_token(
3352 main_frame_same_document_token);
3353 }
3354 }
3355 }
3356
creis4e2ecb72015-06-20 00:46:303357 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023358 for (auto& item : same_document_loads) {
3359 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053360 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303361 }
clamy3cb9bea92018-07-10 12:42:023362 for (auto& item : different_document_loads) {
3363 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053364 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303365 }
clamy3cb9bea92018-07-10 12:42:023366
3367 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303368}
3369
Alex Moshchuk3a4e77a2020-05-29 21:32:573370NavigationControllerImpl::HistoryNavigationAction
3371NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303372 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573373 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423374 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583375 // Only active and prerendered documents are allowed to navigate in their
3376 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423377 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013378 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583379 // - If the document is in pending deletion, the browser already committed
3380 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3381 // - If the document is in back-forward cache, it's not allowed to navigate
3382 // as it should remain frozen. Ignore the request and evict the document
3383 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423384 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583385 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423386 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113387 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3388 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423389 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113390 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423391 }
arthursonzogni03f76152019-02-12 10:35:203392
Alex Moshchuk3a4e77a2020-05-29 21:32:573393 // Reloads should result in a different-document load. Note that reloads may
3394 // also happen via the |needs_reload_| mechanism where the reload_type is
3395 // NONE, so detect this by comparing whether we're going to the same
3396 // entry that we're currently on. Similarly to above, only main frames
3397 // should reach this. Note that subframes support reloads, but that's done
3398 // via a different path that doesn't involve FindFramesToNavigate (see
3399 // RenderFrameHost::Reload()).
3400 if (reload_type != ReloadType::NONE ||
3401 pending_entry_index_ == last_committed_entry_index_) {
3402 DCHECK(frame->IsMainFrame());
3403 return HistoryNavigationAction::kDifferentDocument;
3404 }
3405
Alex Moshchuk47d1a4bd2020-06-01 22:15:343406 // If there is no new FrameNavigationEntry for the frame, ignore the
3407 // load. For example, this may happen when going back to an entry before a
3408 // frame was created. Suppose we commit a same-document navigation that also
3409 // results in adding a new subframe somewhere in the tree. If we go back,
3410 // the new subframe will be missing a FrameNavigationEntry in the previous
3411 // NavigationEntry, but we shouldn't delete or change what's loaded in
3412 // it.
3413 //
Alex Moshchuke65c39272020-06-03 17:55:373414 // Note that in this case, there is no need to keep looking for navigations
3415 // in subframes, which would be missing FrameNavigationEntries as well.
3416 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343417 // It's important to check this before checking |old_item| below, since both
3418 // might be null, and in that case we still shouldn't change what's loaded in
3419 // this frame. Note that scheduling any loads assumes that |new_item| is
3420 // non-null. See https://crbug.com/1088354.
3421 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3422 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373423 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343424
Charlie Reisa474fb62022-03-17 02:31:363425 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3426 // which history item it is currently on, since this may be different than the
3427 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3428 // (e.g., if a history navigation is targeting multiple frames and only some
3429 // have committed so far).
creis4e2ecb72015-06-20 00:46:303430 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363431 frame->current_frame_host()->last_committed_frame_entry();
3432 if (!old_item) {
3433 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3434 // fall back to the last committed NavigationEntry's record for this frame.
3435 // This may happen in cases like the initial state of the RenderFrameHost.
3436 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3437 // accurate FrameNavigationEntry and eliminate this case.
3438 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3439 }
3440 // If neither approach finds a FrameNavigationEntry, schedule a
3441 // different-document load.
3442 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573443 if (!old_item)
3444 return HistoryNavigationAction::kDifferentDocument;
3445
Alex Moshchuk3a4e77a2020-05-29 21:32:573446 // If the new item is not in the same SiteInstance, schedule a
3447 // different-document load. Newly restored items may not have a SiteInstance
3448 // yet, in which case it will be assigned on first commit.
3449 if (new_item->site_instance() &&
3450 new_item->site_instance() != old_item->site_instance())
3451 return HistoryNavigationAction::kDifferentDocument;
3452
3453 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313454 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3455 // that we do this even if the history navigation would not be modifying this
3456 // frame were it live.
3457 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573458 return HistoryNavigationAction::kDifferentDocument;
3459
3460 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313461 // Starting a navigation after a crash early-promotes the speculative
3462 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3463 // committed yet, so we can not possibly perform a same-document history
3464 // navigation. The frame would need to be reloaded with a cross-document
3465 // navigation.
3466 if (!frame->current_frame_host()->has_committed_any_navigation())
3467 return HistoryNavigationAction::kDifferentDocument;
3468
creis54131692016-08-12 18:32:253469 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493470 // sequence number but different item sequence number.
3471 if (new_item->document_sequence_number() ==
3472 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573473 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493474 }
avib48cb312016-05-05 21:35:003475
Alex Moshchuk3a4e77a2020-05-29 21:32:573476 // Otherwise, if both item and document sequence numbers differ, this
3477 // should be a different document load.
3478 return HistoryNavigationAction::kDifferentDocument;
3479 }
3480
3481 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373482 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573483 DCHECK_EQ(new_item->document_sequence_number(),
3484 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373485 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573486}
3487
3488void NavigationControllerImpl::FindFramesToNavigate(
3489 FrameTreeNode* frame,
3490 ReloadType reload_type,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333491 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
3492 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133493 absl::optional<blink::scheduler::TaskAttributionId>
3494 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573495 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3496 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3497 DCHECK(pending_entry_);
3498 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3499
3500 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3501
3502 if (action == HistoryNavigationAction::kSameDocument) {
3503 std::unique_ptr<NavigationRequest> navigation_request =
3504 CreateNavigationRequestFromEntry(
3505 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133506 /*is_same_document_history_load=*/true,
3507 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333508 initiator_frame_token, initiator_process_id,
3509 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573510 if (navigation_request) {
3511 // Only add the request if was properly created. It's possible for the
3512 // creation to fail in certain cases, e.g. when the URL is invalid.
3513 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303514 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573515 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473516 std::unique_ptr<NavigationRequest> navigation_request =
3517 CreateNavigationRequestFromEntry(
3518 frame, pending_entry_, new_item, reload_type,
3519 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433520 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333521 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473522 if (navigation_request) {
3523 // Only add the request if was properly created. It's possible for the
3524 // creation to fail in certain cases, e.g. when the URL is invalid.
3525 different_document_loads->push_back(std::move(navigation_request));
3526 }
3527 // For a different document, the subframes will be destroyed, so there's
3528 // no need to consider them.
3529 return;
Alex Moshchuke65c39272020-06-03 17:55:373530 } else if (action == HistoryNavigationAction::kStopLooking) {
3531 return;
creis4e2ecb72015-06-20 00:46:303532 }
3533
Yoav Weiss8c573952022-11-17 17:35:133534 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3535 // we currently only support soft navigation heuristics for the top level
3536 // frame.
creis4e2ecb72015-06-20 00:46:303537 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333538 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3539 initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133540 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
Nate Chapin45f620582021-09-30 17:45:433541 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303542 }
3543}
3544
Harkiran Bolariaba823e42021-05-21 18:30:363545base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243546 const LoadURLParams& params) {
3547 // Find the appropriate FrameTreeNode.
3548 FrameTreeNode* node = nullptr;
3549 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3550 !params.frame_name.empty()) {
3551 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033552 ? frame_tree_->FindByID(params.frame_tree_node_id)
3553 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503554 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243555 }
3556
3557 // If no FrameTreeNode was specified, navigate the main frame.
3558 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033559 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243560
Camille Lamy5193caa2018-10-12 11:59:423561 // Compute overrides to the LoadURLParams for |override_user_agent|,
3562 // |should_replace_current_entry| and |has_user_gesture| that will be used
3563 // both in the creation of the NavigationEntry and the NavigationRequest.
3564 // Ideally, the LoadURLParams themselves would be updated, but since they are
3565 // passed as a const reference, this is not possible.
3566 // TODO(clamy): When we only create a NavigationRequest, move this to
3567 // CreateNavigationRequestFromLoadURLParams.
3568 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3569 GetLastCommittedEntry());
3570
Rakina Zata Amnie2d31312022-11-18 03:38:453571 // An entry replacement must happen if the current browsing context should
3572 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333573 bool should_replace_current_entry =
3574 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453575 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423576
clamy21718cc22018-06-13 13:34:243577 // Javascript URLs should not create NavigationEntries. All other navigations
3578 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243579 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373580 std::unique_ptr<NavigationEntryImpl> entry =
3581 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3582 should_replace_current_entry,
3583 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243584 DiscardPendingEntry(false);
3585 SetPendingEntry(std::move(entry));
3586 }
3587
Tim Judkins59548192023-05-17 17:51:203588 // Renderer-debug URLs are sent to the current renderer process immediately
3589 // for processing and don't need to create a NavigationRequest. Note: this
3590 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243591 // renderer-debug URLs.
3592 // Note: we intentionally leave the pending entry in place for renderer debug
3593 // URLs, unlike the cases below where we clear it if the navigation doesn't
3594 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303595 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483596 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3597 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153598 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203599 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483600 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363601 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483602 }
3603
clamy21718cc22018-06-13 13:34:243604 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363605 return nullptr;
clamy21718cc22018-06-13 13:34:243606 }
3607
Antonio Sartori78a749f2020-11-30 12:03:393608 DCHECK(pending_entry_);
3609
clamy21718cc22018-06-13 13:34:243610 // Convert navigations to the current URL to a reload.
3611 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3612 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3613 // DevTools sometimes issues navigations to main frames that they do not
3614 // expect to see treated as reload, and it only works because they pass a
3615 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3616 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543617 ReloadType reload_type = params.reload_type;
3618 if (reload_type == ReloadType::NONE &&
3619 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043620 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243621 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243622 params.load_type ==
3623 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543624 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243625 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473626 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393627
3628 // If this is a reload of an existing FrameNavigationEntry and we had a
3629 // policy container for it, then we should copy it into the pending entry,
3630 // so that it is copied to the navigation request in
3631 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453632 FrameNavigationEntry* previous_frame_entry =
3633 GetLastCommittedEntry()->GetFrameEntry(node);
3634 if (previous_frame_entry &&
3635 previous_frame_entry->policy_container_policies()) {
3636 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3637 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393638 }
3639 }
3640
3641 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173642 // document, then we should copy the document polices from RenderFrameHost's
3643 // PolicyContainerHost. The NavigationRequest will create a new
3644 // PolicyContainerHost with the document policies from the |pending_entry_|,
3645 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3646 // the navigation. This way, we ensure that we keep enforcing the right
3647 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453648 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393649 if (node->current_frame_host() &&
3650 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193651 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163652 node->current_frame_host()
3653 ->policy_container_host()
3654 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233655 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393656 }
clamy21718cc22018-06-13 13:34:243657 }
3658
3659 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263660 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243661
Tsuyoshi Horo167ca6432022-03-09 05:16:393662 // This will be used to set the Navigation Timing API navigationStart
3663 // parameter for browser navigations in new tabs (intents, tabs opened through
3664 // "Open link in new tab"). If the navigation must wait on the current
3665 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3666 // will be updated when the BeforeUnload ack is received.
3667 const auto navigation_start_time = base::TimeTicks::Now();
3668
Camille Lamy5193caa2018-10-12 11:59:423669 std::unique_ptr<NavigationRequest> request =
3670 CreateNavigationRequestFromLoadParams(
3671 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143672 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393673 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3674 navigation_start_time);
clamy21718cc22018-06-13 13:34:243675
3676 // If the navigation couldn't start, return immediately and discard the
3677 // pending NavigationEntry.
3678 if (!request) {
3679 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363680 return nullptr;
clamy21718cc22018-06-13 13:34:243681 }
3682
Camille Lamy5193caa2018-10-12 11:59:423683#if DCHECK_IS_ON()
3684 // Safety check that NavigationRequest and NavigationEntry match.
3685 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3686#endif
3687
clamy21718cc22018-06-13 13:34:243688 // This call does not support re-entrancy. See http://crbug.com/347742.
3689 CHECK(!in_navigate_to_pending_entry_);
3690 in_navigate_to_pending_entry_ = true;
3691
arthursonzogni66f711c2019-10-08 14:40:363692 // It is not possible to delete the pending NavigationEntry while navigating
3693 // to it. Grab a reference to delay potential deletion until the end of this
3694 // function.
3695 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3696
Harkiran Bolariaba823e42021-05-21 18:30:363697 base::WeakPtr<NavigationHandle> created_navigation_handle(
3698 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053699 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243700
3701 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363702 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243703}
3704
clamyea99ea12018-05-28 13:54:233705void NavigationControllerImpl::HandleRendererDebugURL(
3706 FrameTreeNode* frame_tree_node,
3707 const GURL& url) {
3708 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243709 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3710 // the renderer process is not live, unless it is the initial navigation
3711 // of the tab.
clamyea99ea12018-05-28 13:54:233712 if (!IsInitialNavigation()) {
3713 DiscardNonCommittedEntries();
3714 return;
3715 }
Fergal Dalyecd3b0202020-06-25 01:57:373716 // The current frame is always a main frame. If IsInitialNavigation() is
3717 // true then there have been no navigations and any frames of this tab must
3718 // be in the same renderer process. If that has crashed then the only frame
3719 // that can be revived is the main frame.
3720 frame_tree_node->render_manager()
3721 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233722 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223723
3724 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3725 // notification, so set is loading to true here to properly surface it when
3726 // the renderer process is done handling the URL.
3727 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3728 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223729 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223730 }
clamyea99ea12018-05-28 13:54:233731 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3732}
3733
clamy21718cc22018-06-13 13:34:243734std::unique_ptr<NavigationEntryImpl>
3735NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3736 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423737 const LoadURLParams& params,
3738 bool override_user_agent,
3739 bool should_replace_current_entry,
3740 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393741 // Browser initiated navigations might not have a blob_url_loader_factory set
3742 // in params even if the navigation is to a blob URL. If that happens, lookup
3743 // the correct url loader factory to use here.
3744 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483745 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473746 // Resolve the blob URL in the storage partition associated with the target
3747 // frame. This is the storage partition the URL will be loaded in, and only
3748 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393749 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473750 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393751 }
3752
clamy21718cc22018-06-13 13:34:243753 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443754 // extra_headers in params are \n separated; navigation entries want \r\n.
3755 std::string extra_headers_crlf;
3756 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243757
3758 // For subframes, create a pending entry with a corresponding frame entry.
3759 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453760 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243761 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083762 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243763 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073764 params.url, absl::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213765 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3766 "GET", -1, blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:483767 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori78a749f2020-11-30 12:03:393768 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163769 // a conversion of a new navigation into a reload, we will set the right
3770 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193771 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243772 } else {
3773 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173774 // If `node` is the outermost main frame, it rewrites a virtual url in order
3775 // to adjust the original input url if needed. For inner frames such as
3776 // fenced frames or subframes, they don't rewrite urls as the urls are not
3777 // input urls by users.
3778 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323779 scoped_refptr<SiteInstance> source_site_instance =
3780 params.source_site_instance;
3781 absl::optional<GURL> source_process_site_url = absl::nullopt;
3782 if (source_site_instance && source_site_instance->HasProcess()) {
3783 source_process_site_url =
3784 source_site_instance->GetProcess()->GetProcessLock().site_url();
3785 }
clamy21718cc22018-06-13 13:34:243786 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063787 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323788 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213789 params.transition_type, params.is_renderer_initiated,
3790 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3791 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243792 entry->set_source_site_instance(
3793 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3794 entry->SetRedirectChain(params.redirect_chain);
3795 }
3796
3797 // Set the FTN ID (only used in non-site-per-process, for tests).
3798 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243799 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423800 entry->SetIsOverridingUserAgent(override_user_agent);
3801 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543802 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243803
clamy21718cc22018-06-13 13:34:243804 switch (params.load_type) {
3805 case LOAD_TYPE_DEFAULT:
3806 break;
3807 case LOAD_TYPE_HTTP_POST:
3808 entry->SetHasPostData(true);
3809 entry->SetPostData(params.post_data);
3810 break;
3811 case LOAD_TYPE_DATA:
3812 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3813 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283814#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243815 entry->SetDataURLAsString(params.data_url_as_string);
3816#endif
3817 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3818 break;
clamy21718cc22018-06-13 13:34:243819 }
3820
3821 // TODO(clamy): NavigationEntry is meant for information that will be kept
3822 // after the navigation ended and therefore is not appropriate for
3823 // started_from_context_menu. Move started_from_context_menu to
3824 // NavigationUIData.
3825 entry->set_started_from_context_menu(params.started_from_context_menu);
3826
3827 return entry;
3828}
3829
clamyea99ea12018-05-28 13:54:233830std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423831NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3832 FrameTreeNode* node,
3833 const LoadURLParams& params,
3834 bool override_user_agent,
3835 bool should_replace_current_entry,
3836 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143837 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423838 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573839 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393840 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223841 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493842 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453843 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583844 bool is_container_initiated,
3845 absl::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573846 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283847 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533848 // All renderer-initiated navigations must have an initiator_origin.
3849 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513850
Camille Lamy5193caa2018-10-12 11:59:423851 GURL url_to_load;
3852 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323853
Camille Lamy2baa8022018-10-19 16:43:173854 // For main frames, rewrite the URL if necessary and compute the virtual URL
3855 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263856 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423857 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173858 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423859 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423860
Camille Lamy2baa8022018-10-19 16:43:173861 // For DATA loads, override the virtual URL.
3862 if (params.load_type == LOAD_TYPE_DATA)
3863 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423864
Camille Lamy2baa8022018-10-19 16:43:173865 if (virtual_url.is_empty())
3866 virtual_url = url_to_load;
3867
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573868 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283869
Aran Gilman249eb122019-12-02 23:32:463870 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3871 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3872 // return different results, leading to a different URL in the
3873 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3874 // pending NavigationEntry, as we'll only make one call to
3875 // RewriteUrlForNavigation.
3876 VLOG_IF(1, (url_to_load != frame_entry->url()))
3877 << "NavigationRequest and FrameEntry have different URLs: "
3878 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283879
Camille Lamy2baa8022018-10-19 16:43:173880 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423881 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173882 // NavigationRequest.
3883 } else {
3884 url_to_load = params.url;
3885 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243886 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173887 }
Camille Lamy5193caa2018-10-12 11:59:423888
Ehsan Karamad44fc72112019-02-26 18:15:473889 if (node->render_manager()->is_attaching_inner_delegate()) {
3890 // Avoid starting any new navigations since this node is now preparing for
3891 // attaching an inner delegate.
3892 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203893 }
Camille Lamy5193caa2018-10-12 11:59:423894
Alex Moshchuk99242832023-05-22 17:21:443895 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:423896 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:443897 }
Camille Lamy5193caa2018-10-12 11:59:423898
danakjd83d706d2020-11-25 22:11:123899 // Look for a pending commit that is to another document in this
3900 // FrameTreeNode. If one exists, then the last committed URL will not be the
3901 // current URL by the time this navigation commits.
3902 bool has_pending_cross_document_commit =
3903 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213904 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123905
Minggang Wangb9f3fa92021-07-01 15:30:313906 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493907 /*old_url=*/node->current_url(),
3908 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3909 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133910 /*is_same_document_history_load=*/false,
3911 is_embedder_initiated_fenced_frame_navigation,
3912 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423913
3914 // Create the NavigationParams based on |params|.
3915
Hiroki Nakagawa4ed61282021-06-18 05:37:233916 bool is_view_source_mode = entry->IsViewSourceMode();
3917 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293918
Antonio Sartori6984c742021-08-26 08:03:413919 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:293920
Hiroki Nakagawa4ed61282021-06-18 05:37:233921 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293922 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253923 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293924
Minggang Wangb9f3fa92021-07-01 15:30:313925 blink::mojom::CommonNavigationParamsPtr common_params =
3926 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:213927 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513928 blink::mojom::Referrer::New(params.referrer.url,
3929 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213930 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513931 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393932 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513933 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143934 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413935 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273936 false /* has_text_fragment_token */,
3937 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3938 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513939 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:053940 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423941
Minggang Wangb9f3fa92021-07-01 15:30:313942 blink::mojom::CommitNavigationParamsPtr commit_params =
3943 blink::mojom::CommitNavigationParams::New(
Rakina Zata Amnic7367852022-11-07 17:10:403944 absl::nullopt,
Ari Chivukula43d2cf82023-01-24 03:16:073945 // The correct storage key and session storage key will be computed
3946 // before committing the navigation.
3947 blink::StorageKey(), blink::StorageKey(), override_user_agent,
3948 params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323949 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503950 std::vector<net::RedirectInfo>(), params.post_content_type,
3951 common_params->url, common_params->method,
3952 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313953 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133954 entry->GetSubframeUniqueNames(node),
3955 /*intended_as_new_entry=*/true,
3956 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143957 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3958 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:133959 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313960 params.should_clear_history_list,
3961 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223962 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:133963 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:513964 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283965#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:133966 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143967#endif
Yoav Weiss8c573952022-11-17 17:35:133968 /*is_browser_initiated=*/!params.is_renderer_initiated,
Yoav Weiss8c573952022-11-17 17:35:133969 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:073970 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133971 /*force_enabled_origin_trials=*/std::vector<std::string>(),
3972 /*origin_agent_cluster=*/false,
3973 /*origin_agent_cluster_left_as_default=*/true,
3974 /*enabled_client_hints=*/
3975 std::vector<network::mojom::WebClientHintsType>(),
3976 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
3977 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:013978 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:133979 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:583980 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:133981 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:133982 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:283983 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:133984 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:443985 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:423986 network::mojom::NavigationDeliveryType::kDefault,
Yoav Weiss8c573952022-11-17 17:35:133987 /*view_transition_state=*/absl::nullopt,
sbinglera07ae732022-12-02 20:49:053988 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
3989 /*modified_runtime_features=*/
Garrett Tanzer29de7112022-12-06 21:26:323990 base::flat_map<::blink::mojom::RuntimeFeatureState, bool>(),
Yuzu Saijo29f96ca92022-12-08 04:54:123991 /*fenced_frame_properties=*/absl::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:053992 /*not_restored_reasons=*/nullptr,
3993 /*load_with_storage_access=*/false);
Xiaohan Wang7f8052e02022-01-14 18:44:283994#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423995 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143996 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423997 }
3998#endif
3999
Lucas Furukawa Gadania9c45682019-07-31 22:05:144000 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074001 commit_params->navigation_timing->system_entropy_at_navigation_start =
4002 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4003 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424004
Camille Lamy5193caa2018-10-12 11:59:424005 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4006 std::string extra_headers_crlf;
4007 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094008
Alex Moshchuk9321e6a2022-12-07 21:58:314009 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144010 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084011 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094012 params.initiator_frame_token, params.initiator_process_id,
4013 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214014 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294015 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454016 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584017 is_container_initiated, embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:094018 navigation_request->set_from_download_cross_origin_redirect(
4019 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554020 navigation_request->set_force_new_browsing_instance(
4021 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:094022 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424023}
4024
4025std::unique_ptr<NavigationRequest>
4026NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234027 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574028 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234029 FrameNavigationEntry* frame_entry,
4030 ReloadType reload_type,
4031 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434032 bool is_history_navigation_in_new_child_frame,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334033 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
4034 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:134035 absl::optional<blink::scheduler::TaskAttributionId>
4036 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344037 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234038 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434039 // We should never navigate to an existing initial NavigationEntry that is the
4040 // initial NavigationEntry for the initial empty document that hasn't been
4041 // overridden by the synchronous about:blank commit, to preserve previous
4042 // behavior where trying to reload when the main frame is on the initial empty
4043 // document won't result in a navigation.
4044 // See also https://crbug.com/1277414.
4045 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324046
clamyea99ea12018-05-28 13:54:234047 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:014048 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574049 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:234050 // We may have been redirected when navigating to the current URL.
4051 // Use the URL the user originally intended to visit as signaled by the
4052 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:014053 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574054 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:234055 dest_referrer = Referrer();
clamyea99ea12018-05-28 13:54:234056 }
4057
Ehsan Karamad44fc72112019-02-26 18:15:474058 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4059 // Avoid starting any new navigations since this node is now preparing for
4060 // attaching an inner delegate.
4061 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204062 }
4063
Alex Moshchuk99242832023-05-22 17:21:444064 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4065 dest_url)) {
clamyea99ea12018-05-28 13:54:234066 return nullptr;
4067 }
4068
clamyea99ea12018-05-28 13:54:234069 // This will be used to set the Navigation Timing API navigationStart
4070 // parameter for browser navigations in new tabs (intents, tabs opened through
4071 // "Open link in new tab"). If the navigation must wait on the current
4072 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4073 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074074
clamyea99ea12018-05-28 13:54:234075 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074076 const auto navigation_start_system_entropy =
4077 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4078 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234079
danakjd83d706d2020-11-25 22:11:124080 // Look for a pending commit that is to another document in this
4081 // FrameTreeNode. If one exists, then the last committed URL will not be the
4082 // current URL by the time this navigation commits.
4083 bool has_pending_cross_document_commit =
4084 frame_tree_node->render_manager()
4085 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494086 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214087 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124088
Minggang Wangb9f3fa92021-07-01 15:30:314089 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124090 /*old_url=*/frame_tree_node->current_url(),
4091 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:494092 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494093 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134094 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494095 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424096
4097 // A form submission may happen here if the navigation is a
4098 // back/forward/reload navigation that does a form resubmission.
4099 scoped_refptr<network::ResourceRequestBody> request_body;
4100 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:504101 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
4102 // entry. This way, it could be directly retrieved here. Right now, it is only
4103 // partially recovered when request.method == "POST" and request.body exists.
4104 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424105 if (frame_entry->method() == "POST") {
4106 request_body = frame_entry->GetPostData(&post_content_type);
4107 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304108 post_content_type = std::string(
4109 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504110 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424111 }
4112
4113 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314114 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514115 entry->ConstructCommonNavigationParams(
4116 *frame_entry, request_body, dest_url,
4117 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384118 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534119 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514120 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554121 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424122
4123 // TODO(clamy): |intended_as_new_entry| below should always be false once
4124 // Reload no longer leads to this being called for a pending NavigationEntry
4125 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314126 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144127 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404128 *frame_entry, common_params->url, common_params->method,
4129 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144130 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534131 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484132 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134133 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074134 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144135 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074136 commit_params->navigation_timing->system_entropy_at_navigation_start =
4137 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4138 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Camille Lamy5193caa2018-10-12 11:59:424139
W. James MacLeanb7d6092682022-10-05 15:23:264140 if (common_params->url.IsAboutSrcdoc()) {
4141 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4142 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594143 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264144 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334145 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314146 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144147 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434148 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334149 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4150 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
4151 absl::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294152 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4153 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474154 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234155}
4156
[email protected]d202a7c2012-01-04 07:53:474157void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214158 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274159 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404160
Takashi Toyoshimaea534ef22021-07-21 03:27:594161 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404162 // location bar will have up-to-date information about the security style
4163 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134164 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404165
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374166 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574167 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:464168
[email protected]b0f724c2013-09-05 04:21:134169 // TODO(avi): Remove. http://crbug.com/170921
4170 NotificationDetails notification_details =
4171 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154172 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4173 Source<NavigationController>(this),
4174 notification_details);
initial.commit09911bf2008-07-26 23:55:294175}
4176
initial.commit09911bf2008-07-26 23:55:294177// static
[email protected]d202a7c2012-01-04 07:53:474178size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234179 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154180 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214181 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234182}
4183
[email protected]d202a7c2012-01-04 07:53:474184void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224185 if (is_active && needs_reload_)
4186 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294187}
4188
[email protected]d202a7c2012-01-04 07:53:474189void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034190 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4191 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294192 if (!needs_reload_)
4193 return;
4194
Bo Liucdfa4b12018-11-06 00:21:444195 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4196 needs_reload_type_);
4197
initial.commit09911bf2008-07-26 23:55:294198 // Calling Reload() results in ignoring state, and not loading.
4199 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4200 // cached state.
avicc872d7242015-08-19 21:26:344201 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134202 NavigateToExistingPendingEntry(
4203 ReloadType::NONE,
4204 /*initiator_rfh=*/nullptr,
4205 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4206 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454207 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434208 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274209 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344210 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134211 NavigateToExistingPendingEntry(
4212 ReloadType::NONE,
4213 /*initiator_rfh=*/nullptr,
4214 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4215 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344216 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434217 // We should never navigate to an existing initial NavigationEntry that is
4218 // the initial NavigationEntry for the initial empty document that hasn't
4219 // been overridden by the synchronous about:blank commit, to preserve
4220 // legacy behavior where trying to reload when the main frame is on the
4221 // initial empty document won't result in a navigation. See also
4222 // https://crbug.com/1277414. If there is something to reload, the
4223 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4224 // it here.
avicc872d7242015-08-19 21:26:344225 needs_reload_ = false;
4226 }
initial.commit09911bf2008-07-26 23:55:294227}
4228
Kevin McNeeccca6172021-10-19 17:11:144229base::WeakPtr<NavigationHandle>
4230NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364231 RenderFrameHost* render_frame_host,
4232 const GURL& url,
4233 const std::string& error_page_html,
4234 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134235 RenderFrameHostImpl* rfhi =
4236 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584237
4238 // Only active documents can load post-commit error pages:
4239 // - If the document is in pending deletion, the browser already committed to
4240 // destroying this RenderFrameHost so ignore loading the error page.
4241 // - If the document is in back-forward cache, it's not allowed to navigate as
4242 // it should remain frozen. Ignore the request and evict the document from
4243 // back-forward cache.
4244 // - If the document is prerendering, it can navigate but when loading error
4245 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114246 if (rfhi->IsInactiveAndDisallowActivation(
4247 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144248 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114249 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584250
Rakina Zata Amni919b7922020-12-11 09:03:134251 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414252
Minggang Wangb9f3fa92021-07-01 15:30:314253 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434254 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594255 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4256 // the frame actually committed (e.g. iframe with "src" set to a
4257 // slow-responding URL). We should rewrite the URL to about:blank in this
4258 // case, as the renderer will only think a page is an error page if it has a
4259 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134260 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314261 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434262 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334263 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414264
Mike Jacksone2aa7af2023-05-17 06:45:074265 commit_params->navigation_timing->system_entropy_at_navigation_start =
4266 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4267 node, blink::mojom::SystemEntropy::kNormal);
4268
arthursonzogni70ac7302020-05-28 08:49:054269 // Error pages have a fully permissive FramePolicy.
4270 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4271 // error pages.
4272 commit_params->frame_policy = blink::FramePolicy();
4273
John Delaney131ad362019-08-08 21:57:414274 std::unique_ptr<NavigationRequest> navigation_request =
4275 NavigationRequest::CreateBrowserInitiated(
4276 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094277 false /* was_opener_suppressed */, "" /* extra_headers */,
4278 nullptr /* frame_entry */, nullptr /* entry */,
4279 false /* is_form_submission */, nullptr /* navigation_ui_data */,
4280 absl::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364281 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414282 navigation_request->set_net_error(error);
Charlie Reis09952ee2022-12-08 16:35:074283 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414284 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144285
4286 // Calling BeginNavigation may destroy the NavigationRequest.
4287 base::WeakPtr<NavigationRequest> created_navigation_request(
4288 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414289 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144290 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414291}
4292
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574293void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214294 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094295 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154296 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144297 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294298}
4299
[email protected]d202a7c2012-01-04 07:53:474300void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364301 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474302 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4303 // represent a no-committed-entry state.
4304 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364305 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474306 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4307 // if `entries_` contains pre-existing entries from the NavigationController
4308 // before restore, which would not be removed and will be at the front of the
4309 // entries list, causing the index to be off by the amount of pre-existing
4310 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294311 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294312}
[email protected]765b35502008-08-21 00:51:204313
arthursonzogni69a6a1b2019-09-17 09:23:004314void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004315 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4316}
4317
4318void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4319 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474320 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104321 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4322 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294323 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474324 return;
Michael Thiessenc5676d22019-09-25 22:32:104325 }
avi45a72532015-04-07 21:01:454326 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314327
4328 if (!delegate_)
4329 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374330 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484331}
4332
avi7c6f35e2015-05-08 17:52:384333int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4334 int nav_entry_id) const {
4335 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4336 if (entries_[i]->GetUniqueID() == nav_entry_id)
4337 return i;
4338 }
4339 return -1;
4340}
4341
[email protected]d202a7c2012-01-04 07:53:474342void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574343 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254344 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574345 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574346 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4347 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254348 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374349 // Normally, cloning a NavigationEntryImpl results in sharing
4350 // FrameNavigationEntries between the original and the clone. However, when
4351 // cloning from a different NavigationControllerImpl, we want to fork the
4352 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374353 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574354 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254355 }
Rakina Zata Amnie2d31312022-11-18 03:38:454356 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274357 DCHECK(pending_entry_index_ == -1 ||
4358 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254359}
[email protected]c5b88d82012-10-06 17:03:334360
4361void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184362 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334363 get_timestamp_callback_ = get_timestamp_callback;
4364}
[email protected]8ff00d72012-10-23 19:12:214365
Shivani Sharmaffb32b82019-04-09 16:58:474366// History manipulation intervention:
4367void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474368 bool replace_entry,
4369 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404370 bool is_renderer_initiated,
4371 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454372 // Note that for a subframe, previous_document_was_activated is true if the
4373 // gesture happened in any subframe (propagated to main frame) or in the main
4374 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474375 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274376 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474377 return;
4378 }
4379 if (last_committed_entry_index_ == -1)
4380 return;
4381
Shivani Sharmac4cc8922019-04-18 03:11:174382 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474383
Alexander Timine3ec4192020-04-20 16:39:404384 // Log UKM with the URL we are navigating away from.
4385 ukm::builders::HistoryManipulationIntervention(
4386 previous_page_load_ukm_source_id)
4387 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474388}
4389
Shivani Sharmac4cc8922019-04-18 03:11:174390void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4391 int reference_index,
4392 bool skippable) {
4393 auto* reference_entry = GetEntryAtIndex(reference_index);
4394 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4395
4396 int64_t document_sequence_number =
4397 reference_entry->root_node()->frame_entry->document_sequence_number();
4398 for (int index = 0; index < GetEntryCount(); index++) {
4399 auto* entry = GetEntryAtIndex(index);
4400 if (entry->root_node()->frame_entry->document_sequence_number() ==
4401 document_sequence_number) {
4402 entry->set_should_skip_on_back_forward_ui(skippable);
4403 }
4404 }
4405}
4406
arthursonzogni66f711c2019-10-08 14:40:364407std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4408NavigationControllerImpl::ReferencePendingEntry() {
4409 DCHECK(pending_entry_);
4410 auto pending_entry_ref =
4411 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4412 pending_entry_refs_.insert(pending_entry_ref.get());
4413 return pending_entry_ref;
4414}
4415
4416void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4417 // Ignore refs that don't correspond to the current pending entry.
4418 auto it = pending_entry_refs_.find(ref);
4419 if (it == pending_entry_refs_.end())
4420 return;
4421 pending_entry_refs_.erase(it);
4422
4423 if (!pending_entry_refs_.empty())
4424 return;
4425
4426 // The pending entry may be deleted before the last PendingEntryRef.
4427 if (!pending_entry_)
4428 return;
4429
4430 // We usually clear the pending entry when the matching NavigationRequest
4431 // fails, so that an arbitrary URL isn't left visible above a committed page.
4432 //
4433 // However, we do preserve the pending entry in some cases, such as on the
4434 // initial navigation of an unmodified blank tab. We also allow the delegate
4435 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4436 // user edit the URL and try again. This may be useful in cases that the
4437 // committed page cannot be attacker-controlled. In these cases, we still
4438 // allow the view to clear the pending entry and typed URL if the user
4439 // requests (e.g., hitting Escape with focus in the address bar).
4440 //
4441 // Do not leave the pending entry visible if it has an invalid URL, since this
4442 // might be formatted in an unexpected or unsafe way.
4443 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364444 bool should_preserve_entry =
4445 (pending_entry_ == GetVisibleEntry()) &&
4446 pending_entry_->GetURL().is_valid() &&
4447 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4448 if (should_preserve_entry)
4449 return;
4450
4451 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374452 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364453}
4454
Titouan Rigoudy6ec70402021-02-02 15:42:194455std::unique_ptr<PolicyContainerPolicies>
4456NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394457 RenderFrameHostImpl* rfh,
4458 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174459 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394460 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454461 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394462 FrameNavigationEntry* previous_frame_entry =
4463 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4464
4465 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4466 // ensure we always have a FrameNavigationEntry here.
4467 if (!previous_frame_entry)
4468 return nullptr;
4469
Titouan Rigoudy6ec70402021-02-02 15:42:194470 const PolicyContainerPolicies* previous_policies =
4471 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394472
Titouan Rigoudy6ec70402021-02-02 15:42:194473 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394474 return nullptr;
4475
4476 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234477 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394478 }
4479
Titouan Rigoudy72f892d2022-05-02 18:21:234480 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394481}
4482
Hayato Ito2c8c08d02021-06-23 03:38:434483void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504484 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434485 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4486 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4487 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504488
4489 auto callback = base::BindRepeating(
4490 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4491 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4492 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4493 }
4494 },
Hayato Ito2c8c08d02021-06-23 03:38:434495 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034496 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504497}
4498
4499void NavigationControllerImpl::DidAccessInitialMainDocument() {
4500 // We may have left a failed browser-initiated navigation in the address bar
4501 // to let the user edit it and try again. Clear it now that content might
4502 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034503 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504504 DiscardPendingEntry(false);
4505
4506 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374507 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504508}
4509
4510void NavigationControllerImpl::UpdateStateForFrame(
4511 RenderFrameHostImpl* rfhi,
4512 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564513 OPTIONAL_TRACE_EVENT1("content",
4514 "NavigationControllerImpl::UpdateStateForFrame",
4515 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504516 // The state update affects the last NavigationEntry associated with the given
4517 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4518 // in the case of an UpdateState from a frame being swapped out). We track
4519 // which entry this is in the RenderFrameHost's nav_entry_id.
4520 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4521 if (!entry)
4522 return;
4523
4524 FrameNavigationEntry* frame_entry =
4525 entry->GetFrameEntry(rfhi->frame_tree_node());
4526 if (!frame_entry)
4527 return;
4528
4529 // The SiteInstance might not match if we do a cross-process navigation with
4530 // replacement (e.g., auto-subframe), in which case the swap out of the old
4531 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4532 // has already been replaced and destroyed.
4533 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4534 return;
4535
4536 if (page_state == frame_entry->page_state())
4537 return; // Nothing to update.
4538
4539 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4540
4541 // The document_sequence_number and item_sequence_number recorded in the
4542 // FrameNavigationEntry should not differ from the one coming with the update,
4543 // since it must come from the same document. Do not update it if a difference
4544 // is detected, as this indicates that |frame_entry| is not the correct one.
4545 blink::ExplodedPageState exploded_state;
4546 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4547 return;
4548
4549 if (exploded_state.top.document_sequence_number !=
4550 frame_entry->document_sequence_number() ||
4551 exploded_state.top.item_sequence_number !=
4552 frame_entry->item_sequence_number()) {
4553 return;
4554 }
4555
4556 frame_entry->SetPageState(page_state);
4557 NotifyEntryChanged(entry);
4558}
4559
Domenic Denicolacd30f5f82022-03-16 21:48:014560std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4561NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574562 Direction direction,
4563 int entry_index,
4564 const url::Origin& pending_origin,
4565 FrameTreeNode* node,
4566 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304567 int64_t pending_item_sequence_number,
4568 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014569 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454570 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174571 // Don't process the initial entry.
4572 DCHECK_EQ(GetEntryCount(), 1);
4573 return entries;
4574 }
Nate Chapind1fe3612021-04-16 20:45:574575 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304576 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574577 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4578 i += offset) {
4579 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414580 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574581 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014582 // An entry should only appear in the navigation API entries if it is for
4583 // the same origin as the document being committed. Check the committed
4584 // origin, or if that is not available (during restore), check against the
4585 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414586 url::Origin frame_entry_origin =
4587 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4588 frame_entry->url(),
4589 frame_entry->initiator_origin().value_or(url::Origin())));
4590 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574591 break;
4592 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4593 continue;
4594 blink::ExplodedPageState exploded_page_state;
4595 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4596 &exploded_page_state)) {
4597 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304598
4599 // If the document represented by this FNE hid its full url from appearing
4600 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014601 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304602 // document).
4603 std::u16string url;
4604 if (pending_document_sequence_number ==
4605 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574606 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304607 url = frame_state.url_string.value_or(std::u16string());
4608 }
4609
Domenic Denicolacd30f5f82022-03-16 21:48:014610 blink::mojom::NavigationApiHistoryEntryPtr entry =
4611 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574612 frame_state.navigation_api_key.value_or(std::u16string()),
4613 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094614 frame_state.item_sequence_number,
4615 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304616 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174617
Nate Chapin63db0d12022-01-20 22:03:304618 DCHECK(entry->url.empty() ||
4619 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574620 entries.push_back(std::move(entry));
4621 previous_item_sequence_number = frame_entry->item_sequence_number();
4622 }
4623 }
4624 // If |entries| was constructed by iterating backwards from
4625 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4626 // earliest-at-the-front. Reverse it.
4627 if (direction == Direction::kBack)
4628 std::reverse(entries.begin(), entries.end());
4629 return entries;
4630}
4631
Domenic Denicolacd30f5f82022-03-16 21:48:014632blink::mojom::NavigationApiHistoryEntryArraysPtr
4633NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554634 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574635 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404636 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444637 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404638 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574639
Nate Chapind1fe3612021-04-16 20:45:574640 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554641 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574642
Nate Chapine82339d02022-05-03 23:48:254643 // NOTE: |entry_index| is the index where this entry will commit if no
4644 // modifications are made between now and DidCommitNavigation. This is used to
4645 // walk |entries_| and determine which entries should be exposed by the
4646 // navigation API. It is important to calculate this correctly, because blink
4647 // will cancel a same-document history commit if it's not present in the
4648 // entries blink knows about.
4649 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574650 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304651 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254652 bool will_create_new_entry = false;
4653 if (GetPendingEntryIndex() != -1) {
4654 entry_index = GetPendingEntryIndex();
4655 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4656 pending_item_sequence_number = frame_entry->item_sequence_number();
4657 pending_document_sequence_number =
4658 frame_entry->document_sequence_number();
4659 }
4660 } else if (request &&
4661 !NavigationTypeUtils::IsReload(
4662 request->common_params().navigation_type) &&
4663 !NavigationTypeUtils::IsHistory(
4664 request->common_params().navigation_type) &&
4665 !request->common_params().should_replace_current_entry &&
4666 !request->common_params()
4667 .is_history_navigation_in_new_child_frame) {
4668 will_create_new_entry = true;
4669 entry_index = GetLastCommittedEntryIndex() + 1;
4670 // Don't set pending_item_sequence_number or
4671 // pending_document_sequence_number in this case - a new unique isn/dsn will
4672 // be calculated in the renderer later.
4673 } else if (GetLastCommittedEntryIndex() != -1) {
4674 entry_index = GetLastCommittedEntryIndex();
4675 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574676 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304677 pending_document_sequence_number =
4678 frame_entry->document_sequence_number();
4679 }
Nate Chapind1fe3612021-04-16 20:45:574680 }
4681
Domenic Denicolacd30f5f82022-03-16 21:48:014682 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254683 if (entry_index == -1) {
4684 // TODO(rakina): Exit early when there is no last committed entry.
4685 // Remove when InitialNavigationEntry ships.
4686 return entry_arrays;
4687 }
4688
Domenic Denicolacd30f5f82022-03-16 21:48:014689 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574690 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374691 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574692
4693 // Don't populate forward entries if they will be truncated by a new entry.
4694 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014695 entry_arrays->forward_entries =
4696 PopulateSingleNavigationApiHistoryEntryVector(
4697 Direction::kForward, entry_index, pending_origin, node,
4698 site_instance.get(), pending_item_sequence_number,
4699 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574700 }
Nate Chapin4e657a472022-02-06 03:38:374701 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574702}
4703
Nate Chapinfbfe5af2021-06-10 17:22:084704NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574705NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084706 FrameNavigationEntry* current_entry,
4707 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574708 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084709 if (!target_entry || !target_entry->committed_origin())
4710 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084711 if (!current_entry->committed_origin()->IsSameOriginWith(
4712 *target_entry->committed_origin())) {
4713 return HistoryNavigationAction::kStopLooking;
4714 }
4715
4716 // NOTE: We don't actually care between kSameDocument and
4717 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574718 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084719 return HistoryNavigationAction::kDifferentDocument;
4720 return HistoryNavigationAction::kKeepLooking;
4721}
4722
Domenic Denicolacc094fb2022-03-16 23:40:574723void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204724 RenderFrameHostImpl* initiator_rfh,
Yoav Weissa7449c3b2022-11-22 15:15:144725 absl::optional<blink::scheduler::TaskAttributionId>
4726 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574727 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204728 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084729 FrameNavigationEntry* current_entry =
4730 GetLastCommittedEntry()->GetFrameEntry(node);
4731 if (!current_entry)
4732 return;
4733
Yoav Weiss8c573952022-11-17 17:35:134734 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4735 // when `navigation.traverseTo()` is called.
4736
Nate Chapinfbfe5af2021-06-10 17:22:084737 // We want to find the nearest matching entry that is contiguously
4738 // same-instance and same-origin. Check back first, then forward.
4739 // TODO(japhet): Link spec here once it exists.
4740 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574741 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084742 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4743 if (result == HistoryNavigationAction::kStopLooking)
4744 break;
4745 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144746 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084747 return;
4748 }
4749 }
4750 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574751 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084752 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4753 if (result == HistoryNavigationAction::kStopLooking)
4754 break;
4755 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144756 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084757 return;
4758 }
4759 }
Nate Chapinbf682fa32022-09-26 22:41:204760
4761 // If we fall through to here, a matching NavigationEntry couldn't be found.
4762 // Notify the renderer that the navigation was cancelled.
4763 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4764 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084765}
4766
Domenic Denicolacc094fb2022-03-16 23:40:574767bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304768 network::mojom::ReferrerPolicy referrer_policy) {
4769 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4770 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4771}
4772
shivanigithubf405bf0d2021-11-05 17:58:334773bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4774 const FrameTreeNode* frame_tree_node) const {
4775 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4776 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544777 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Ali Hijazid87307d2022-11-07 20:15:034778 return frame_tree_->is_prerendering() ||
shivanigithubf405bf0d2021-11-05 17:58:334779 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544780}
4781
Julie Jeongeun Kim0e242242022-11-30 10:45:094782void NavigationControllerImpl::DidChangeReferrerPolicy(
4783 FrameTreeNode* node,
4784 network::mojom::ReferrerPolicy referrer_policy) {
4785 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4786 if (!entry)
4787 return;
4788
4789 // The FrameNavigationEntry may want to change whether to protect its url
4790 // in the navigation API when the referrer policy changes.
4791 entry->set_protect_url_in_navigation_api(
4792 ShouldProtectUrlInNavigationApi(referrer_policy));
4793}
4794
[email protected]8ff00d72012-10-23 19:12:214795} // namespace content