blob: 8c50ae98ac25affab9bd99fb0b47763eabc1a7d8 [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
Camille Lamy5193caa2018-10-12 11:59:42271bool IsValidURLForNavigation(bool is_main_frame,
272 const GURL& virtual_url,
273 const GURL& dest_url) {
274 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
275 if (is_main_frame && !virtual_url.is_valid() && !virtual_url.is_empty()) {
276 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
277 << virtual_url.possibly_invalid_spec();
278 return false;
279 }
280
281 // Don't attempt to navigate to non-empty invalid URLs.
282 if (!dest_url.is_valid() && !dest_url.is_empty()) {
283 LOG(WARNING) << "Refusing to load invalid URL: "
284 << dest_url.possibly_invalid_spec();
285 return false;
286 }
287
288 // The renderer will reject IPC messages with URLs longer than
289 // this limit, so don't attempt to navigate with a longer URL.
290 if (dest_url.spec().size() > url::kMaxURLChars) {
291 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
292 << " characters.";
293 return false;
294 }
295
Aaron Colwell33109c592020-04-21 21:31:19296 // Reject renderer debug URLs because they should have been handled before
297 // we get to this point. This check handles renderer debug URLs
298 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
299 // provides defense-in-depth if a renderer debug URL manages to get here via
300 // some other path. We want to reject the navigation here so it doesn't
301 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30302 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19303 LOG(WARNING) << "Refusing to load renderer debug URL: "
304 << dest_url.possibly_invalid_spec();
305 return false;
306 }
307
Camille Lamy5193caa2018-10-12 11:59:42308 return true;
309}
310
Mikel Astizba9cf2fd2017-12-17 10:38:10311// See replaced_navigation_entry_data.h for details: this information is meant
312// to ensure |*output_entry| keeps track of its original URL (landing page in
313// case of server redirects) as it gets replaced (e.g. history.replaceState()),
314// without overwriting it later, for main frames.
315void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57316 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10317 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17318 if (output_entry->GetReplacedEntryData().has_value() ||
319 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10320 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17321 }
Mikel Astizba9cf2fd2017-12-17 10:38:10322
323 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57324 data.first_committed_url = replaced_entry->GetURL();
325 data.first_timestamp = replaced_entry->GetTimestamp();
326 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29327 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10328}
329
Minggang Wangb9f3fa92021-07-01 15:30:31330blink::mojom::NavigationType GetNavigationType(
331 const GURL& old_url,
332 const GURL& new_url,
333 ReloadType reload_type,
334 NavigationEntryImpl* entry,
335 const FrameNavigationEntry& frame_entry,
336 bool has_pending_cross_document_commit,
337 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49338 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13339 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49340 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23341 // Reload navigations
342 switch (reload_type) {
343 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31344 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23345 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31346 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23347 case ReloadType::ORIGINAL_REQUEST_URL:
Minggang Wangb9f3fa92021-07-01 15:30:31348 return blink::mojom::NavigationType::RELOAD_ORIGINAL_REQUEST_URL;
clamyea99ea12018-05-28 13:54:23349 case ReloadType::NONE:
350 break; // Fall through to rest of function.
351 }
352
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08353 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31354 return entry->GetHasPostData()
355 ? blink::mojom::NavigationType::RESTORE_WITH_POST
356 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23357 }
358
danakjb952ef12021-01-14 19:58:49359 const bool can_be_same_document =
360 // A pending cross-document commit means this navigation will not occur in
361 // the current document, as that document would end up being replaced in
362 // the meantime.
363 !has_pending_cross_document_commit &&
364 // If the current document is an error page, we should always treat it as
365 // a different-document navigation so that we'll attempt to load the
366 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49367 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13368 // If the navigation is an embedder-initiated navigation of a fenced
369 // frame root (i.e. enters a fenced frame tree from outside),
370 // same-document navigations should be disabled because we don't want to
371 // allow information to be joined across multiple embedder-initiated
372 // fenced frame navigations (which may contain separate cross-site data).
373 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49374 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
375 // same-document navigations should be disabled because we want to force
376 // the creation of a new browsing context group.
377 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12378
clamyea99ea12018-05-28 13:54:23379 // History navigations.
380 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12381 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31382 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
383 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23384 }
385 DCHECK(!is_same_document_history_load);
386
387 // A same-document fragment-navigation happens when the only part of the url
388 // that is modified is after the '#' character.
389 //
390 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12391 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23392 //
393 // Note: this check is only valid for navigations that are not history
394 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
395 // history navigation from 'A#foo' to 'A#bar' is not a same-document
396 // navigation, but a different-document one. This is why history navigation
397 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47398 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
399 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12400
401 // The one case where we do the wrong thing here and incorrectly choose
402 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
403 // the renderer is a frameset. All frameset navigations should be
404 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
405 // navigation would do the right thing, as it would send it to the browser and
406 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
407 // into this method). But since we can't tell that case here for browser-
408 // initiated navigations, we have to get the renderer involved. In that case
409 // the navigation would be restarted due to the renderer spending a reply of
410 // mojom::CommitResult::RestartCrossDocument.
411
412 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31413 ? blink::mojom::NavigationType::SAME_DOCUMENT
414 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23415}
416
Camille Lamy5193caa2018-10-12 11:59:42417// Adjusts the original input URL if needed, to get the URL to actually load and
418// the virtual URL, which may differ.
419void RewriteUrlForNavigation(const GURL& original_url,
420 BrowserContext* browser_context,
421 GURL* url_to_load,
422 GURL* virtual_url,
423 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42424 // Allow the browser URL handler to rewrite the URL. This will, for example,
425 // remove "view-source:" from the beginning of the URL to get the URL that
426 // will actually be loaded. This real URL won't be shown to the user, just
427 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31428 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42429 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
430 url_to_load, browser_context, reverse_on_redirect);
431}
432
433#if DCHECK_IS_ON()
434// Helper sanity check function used in debug mode.
435void ValidateRequestMatchesEntry(NavigationRequest* request,
436 NavigationEntryImpl* entry) {
437 if (request->frame_tree_node()->IsMainFrame()) {
438 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
439 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31440 ui::PageTransitionFromInt(request->common_params().transition),
441 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42442 }
Nasko Oskovc36327d2019-01-03 23:23:04443 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42444 entry->should_clear_history_list());
445 DCHECK_EQ(request->common_params().has_user_gesture,
446 entry->has_user_gesture());
447 DCHECK_EQ(request->common_params().base_url_for_data_url,
448 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04449 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42450 entry->GetCanLoadLocalResources());
451 DCHECK_EQ(request->common_params().started_from_context_menu,
452 entry->has_started_from_context_menu());
453
454 FrameNavigationEntry* frame_entry =
455 entry->GetFrameEntry(request->frame_tree_node());
456 if (!frame_entry) {
457 NOTREACHED();
458 return;
459 }
460
Camille Lamy5193caa2018-10-12 11:59:42461 DCHECK_EQ(request->common_params().method, frame_entry->method());
462
Nasko Oskovc36327d2019-01-03 23:23:04463 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42464 if (redirect_size == frame_entry->redirect_chain().size()) {
465 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04466 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42467 frame_entry->redirect_chain()[i]);
468 }
469 } else {
470 NOTREACHED();
471 }
472}
473#endif // DCHECK_IS_ON()
474
Dave Tapuska8bfd84c2019-03-26 20:47:16475// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20476// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16477bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20478 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16479 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20480 DCHECK(sandboxed_initiator_rfh);
481 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
482 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16483 for (auto& item : navigations) {
484 bool within_subtree = false;
485 // Check whether this NavigationRequest affects a frame within the
486 // sandboxed frame's subtree by walking up the tree looking for the
487 // sandboxed frame.
488 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03489 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20490 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16491 within_subtree = true;
492 break;
493 }
494 }
495 if (!within_subtree)
496 return false;
497 }
498 return true;
499}
500
[email protected]e9ba4472008-09-14 15:42:43501} // namespace
502
arthursonzogni66f711c2019-10-08 14:40:36503// NavigationControllerImpl::PendingEntryRef------------------------------------
504
505NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
506 base::WeakPtr<NavigationControllerImpl> controller)
507 : controller_(controller) {}
508
509NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
510 if (!controller_) // Can be null with interstitials.
511 return;
512
513 controller_->PendingEntryRefDeleted(this);
514}
515
[email protected]d202a7c2012-01-04 07:53:47516// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29517
[email protected]23a918b2014-07-15 09:51:36518const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23519
[email protected]765b35502008-08-21 00:51:20520// static
[email protected]d202a7c2012-01-04 07:53:47521size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23522 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20523
[email protected]e6fec472013-05-14 05:29:02524// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20525// when testing.
526static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29527
[email protected]71fde352011-12-29 03:29:56528// static
dcheng9bfa5162016-04-09 01:00:57529std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
530 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10531 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07532 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21533 absl::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10534 ui::PageTransition transition,
535 bool is_renderer_initiated,
536 const std::string& extra_headers,
537 BrowserContext* browser_context,
538 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
539 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21540 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Sharon Yang242ef822023-05-15 21:07:32541 absl::nullopt /* source_process_site_url */, transition,
542 is_renderer_initiated, extra_headers, browser_context,
543 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10544}
545
546// static
547std::unique_ptr<NavigationEntryImpl>
548NavigationControllerImpl::CreateNavigationEntry(
549 const GURL& url,
550 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07551 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21552 absl::optional<GURL> initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:32553 absl::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57554 ui::PageTransition transition,
555 bool is_renderer_initiated,
556 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09557 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17558 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
559 bool rewrite_virtual_urls) {
560 GURL url_to_load = url;
561 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56562 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17563 if (rewrite_virtual_urls) {
564 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
565 &reverse_on_redirect);
566 }
Lukasz Anforowicz641234d52019-11-07 21:07:10567 // Let the NTP override the navigation params and pretend that this is a
568 // browser-initiated, bookmark-like navigation.
569 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32570 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21571 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10572
Patrick Monettef507e982019-06-19 20:18:06573 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28574 nullptr, // The site instance for tabs is sent on navigation
575 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21576 url_to_load, referrer, initiator_origin, initiator_base_url,
577 std::u16string(), transition, is_renderer_initiated,
578 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17579 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42580 entry->SetVirtualURL(virtual_url);
581 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56582 entry->set_update_virtual_url_with_url(reverse_on_redirect);
583 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06584 return entry;
[email protected]71fde352011-12-29 03:29:56585}
586
[email protected]cdcb1dee2012-01-04 00:46:20587// static
588void NavigationController::DisablePromptOnRepost() {
589 g_check_for_repost = false;
590}
591
[email protected]c5b88d82012-10-06 17:03:33592base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
593 base::Time t) {
594 // If |t| is between the water marks, we're in a run of duplicates
595 // or just getting out of it, so increase the high-water mark to get
596 // a time that probably hasn't been used before and return it.
597 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35598 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33599 return high_water_mark_;
600 }
601
602 // Otherwise, we're clear of the last duplicate run, so reset the
603 // water marks.
604 low_water_mark_ = high_water_mark_ = t;
605 return t;
606}
607
ckitagawa0faa5e42020-06-17 17:30:54608NavigationControllerImpl::ScopedShowRepostDialogForTesting::
609 ScopedShowRepostDialogForTesting()
610 : was_disallowed_(g_check_for_repost) {
611 g_check_for_repost = true;
612}
613
614NavigationControllerImpl::ScopedShowRepostDialogForTesting::
615 ~ScopedShowRepostDialogForTesting() {
616 g_check_for_repost = was_disallowed_;
617}
618
Nate Chapin9eb16be72022-09-23 22:54:31619NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
620 base::SafeRef<NavigationControllerImpl> controller)
621 : controller_(controller) {
622 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
623 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
624 frame_tree_node_id_to_keys_.insert(
625 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
626 if (auto* frame_entry = frame_tree_node->current_frame_host()
627 ->last_committed_frame_entry()) {
628 frame_tree_node_id_to_doc_seq_nos_.insert(
629 {frame_tree_node->frame_tree_node_id(),
630 frame_entry->document_sequence_number()});
631 }
632 }
633 PopulateKeySet(Direction::kBack);
634 PopulateKeySet(Direction::kForward);
635}
636
637void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
638 Direction direction) {
639 // Keep track of which FrameTreeNodes may still have relevant API keys in
640 // additional FrameNavigationEntries.
641 std::set<FrameTreeNode*> nodes_to_process;
642 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
643 nodes_to_process.insert(node);
644 }
645
646 const int offset = direction == Direction::kForward ? 1 : -1;
647 const int start = direction == Direction::kForward
648 ? controller_->GetLastCommittedEntryIndex()
649 : controller_->GetLastCommittedEntryIndex() - 1;
650 for (int i = start;
651 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
652 i += offset) {
653 std::set<FrameTreeNode*> nodes_to_continue_processing;
654
655 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
656 entry->ForEachFrameEntry([this, &nodes_to_process,
657 &nodes_to_continue_processing,
658 &entry](FrameNavigationEntry* frame_entry) {
659 // Find the |node| that matches |frame_entry|, if any.
660 FrameTreeNode* node = nullptr;
661 if (frame_entry == entry->root_node()->frame_entry) {
662 node = controller_->frame_tree().root();
663 } else {
664 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
665 if (it == names_to_nodes_.end())
666 return;
667 node = it->second;
668 }
669
670 // Skip this node if a previous step determine there are no longer
671 // relevant navigation API keys in this direction.
672 if (nodes_to_process.find(node) == nodes_to_process.end())
673 return;
674
675 // Stop processing |node| if we reach a point where it's cross-origin.
676 // See also PopulateSingleNavigationApiHistoryEntryVector().
677 url::Origin frame_entry_origin =
678 frame_entry->committed_origin().value_or(url::Origin::Resolve(
679 frame_entry->url(),
680 frame_entry->initiator_origin().value_or(url::Origin())));
681 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
682 return;
683
684 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
685 frame_entry->navigation_api_key());
686 // Mark |node| as needing more processing for the next entry.
687 nodes_to_continue_processing.insert(node);
688
689 // Check whether |node| went cross-document. If so, its children are
690 // no longer the same conceptual iframe as the current one, and
691 // should no longer be processed. This check is intentionally done
692 // after processing the current |node|, which may still have relevant
693 // discarded API keys.
694 if (frame_entry->document_sequence_number() !=
695 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50696 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31697 nodes_to_process.erase(descendant);
698 }
699 });
700
701 nodes_to_process.swap(nodes_to_continue_processing);
702 }
703}
704
705NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
706 std::set<std::string> all_keys;
707 // Find all remaining navigation API keys after some entries have been
708 // removed.
709 for (auto& entry : controller_->entries_) {
710 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
711 all_keys.insert(frame_entry->navigation_api_key());
712 });
713 }
714
715 // Notify each frame in the renderer of any disposed navigation API keys.
716 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
717 std::vector<std::string> disposed_keys;
718 for (const auto& key : id_to_keys.second) {
719 if (all_keys.find(key) == all_keys.end())
720 disposed_keys.push_back(key);
721 }
722 if (disposed_keys.empty())
723 continue;
724
725 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
726 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
727 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
728 }
729}
730
[email protected]d202a7c2012-01-04 07:53:47731NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00732 BrowserContext* browser_context,
733 FrameTree& frame_tree,
734 NavigationControllerDelegate* delegate)
735 : frame_tree_(frame_tree),
736 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57737 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22738 ssl_manager_(this),
Lei Zhang96031532019-10-10 19:05:47739 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)) {
[email protected]3d7474ff2011-07-27 17:47:37740 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29741}
742
[email protected]d202a7c2012-01-04 07:53:47743NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00744 // The NavigationControllerImpl might be called inside its delegate
745 // destructor. Calling it is not valid anymore.
746 delegate_ = nullptr;
747 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29748}
749
Matt Falkenhagen548ed1562021-07-06 01:38:26750WebContents* NavigationControllerImpl::DeprecatedGetWebContents() {
751 return delegate_->DeprecatedGetWebContents();
[email protected]fbc5e5f92012-01-02 06:08:32752}
753
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57754BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55755 return browser_context_;
756}
757
[email protected]d202a7c2012-01-04 07:53:47758void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30759 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36760 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57761 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47762 // Note that it's possible for `entries_` to contain multiple entries at this
763 // point, as Restore() might be called on a NavigationController that is
764 // already used (e.g. due to WebView's restoreState() API), not only for fresh
765 // NavigationControllers. These entries are not cleared to preserve legacy
766 // behavior and also because `pending_entry_` might point to one of the
767 // pre-existing entries. An exception for this is when `entries_` contains
768 // only the initial NavigationEntry, which must be removed.
769
770 // Do not proceed if selected_navigation will be out of bounds for the updated
771 // entries_ list, since it will be assigned to last_committed_entry_index_ and
772 // used to index entries_.
773 // TODO(https://crbug.com/1287624): Consider also returning early if entries
774 // is empty, since there should be no work to do (rather than marking the
775 // existing entries as needing reload). Also consider returning early if the
776 // selected index is -1, which represents a no-committed-entry state.
777 if (selected_navigation < -1 ||
778 selected_navigation >=
779 base::checked_cast<int>(entries->size() + entries_.size())) {
780 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24781 }
Charlie Reis23c26da2022-01-29 00:57:47782
Rakina Zata Amni46087a12022-11-11 08:28:38783 // There will always be at least one entry (new NavigationControllers will
784 // have the initial NavigationEntry).
785 if (selected_navigation == -1)
786 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47787
Rakina Zata Amni46087a12022-11-11 08:28:38788 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
789 // If we are on the initial NavigationEntry, it must be the only entry in
790 // the list. Since it's impossible to do a history navigation to the
791 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
792 // `pending_entry` might be set for a new non-history navigation).
793 // Note that we should not clear `entries_` if `entries` is empty (when
794 // InitialNavigationEntry mode is enabled), since that would leave us
795 // without any NavigationEntry.
796 CHECK_EQ(1, GetEntryCount());
797 CHECK_EQ(-1, pending_entry_index_);
798 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47799 }
[email protected]ce3fa3c2009-04-20 19:55:57800
[email protected]ce3fa3c2009-04-20 19:55:57801 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44802 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03803 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47804 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43805 if (entry->GetURL().is_empty()) {
806 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01807 // persisting the initial NavigationEntry [which is no longer possible but
808 // some old persisted sessions might still contain it] or when the
809 // serializer failed to write the URL because it's too long). Trying to
810 // restore and navigate to an entry with an empty URL will result in
811 // crashes, so change the URL to about:blank. See also
812 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43813 entry->SetURL(GURL(url::kAboutBlankURL));
814 }
dcheng36b6aec92015-12-26 06:16:36815 entries_.push_back(
816 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47817 }
avif16f85a72015-11-13 18:25:03818
819 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
820 // cleared out safely.
821 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57822
823 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36824 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57825}
826
toyoshim6142d96f2016-12-19 09:07:25827void NavigationControllerImpl::Reload(ReloadType reload_type,
828 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03829 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
830 (int)reload_type);
831 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
832 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28833 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28834 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32835 int current_index = -1;
836
Carlos IL42b416592019-10-07 23:10:36837 if (entry_replaced_by_post_commit_error_) {
838 // If there is an entry that was replaced by a currently active post-commit
839 // error navigation, this can't be the initial navigation.
840 DCHECK(!IsInitialNavigation());
841 // If the current entry is a post commit error, we reload the entry it
842 // replaced instead. We leave the error entry in place until a commit
843 // replaces it, but the pending entry points to the original entry in the
844 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
845 // case that pending_entry_ != entries_[pending_entry_index_].
846 entry = entry_replaced_by_post_commit_error_.get();
847 current_index = GetCurrentEntryIndex();
848 } else if (IsInitialNavigation() && pending_entry_) {
849 // If we are reloading the initial navigation, just use the current
850 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32851 entry = pending_entry_;
852 // The pending entry might be in entries_ (e.g., after a Clone), so we
853 // should also update the current_index.
854 current_index = pending_entry_index_;
855 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00856 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32857 current_index = GetCurrentEntryIndex();
858 if (current_index != -1) {
creis3da03872015-02-20 21:12:32859 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32860 }
[email protected]979a4bc2013-04-24 01:27:15861 }
[email protected]241db352013-04-22 18:04:05862
[email protected]59167c22013-06-03 18:07:32863 // If we are no where, then we can't reload. TODO(darin): We should add a
864 // CanReload method.
865 if (!entry)
866 return;
867
Rakina Zata Amnif297a802022-01-18 03:53:43868 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
869 // We should never navigate to an existing initial NavigationEntry that is
870 // the initial NavigationEntry for the initial empty document that hasn't
871 // been overridden by the synchronous about:blank commit, to preserve
872 // legacy behavior where trying to reload when the main frame is on the
873 // initial empty document won't result in a navigation. See also
874 // https://crbug.com/1277414.
875 return;
876 }
877
Aran Gilman37d11632019-10-08 23:07:15878 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30879 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07880 // they really want to do this. If they do, the dialog will call us back
881 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57882 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02883
[email protected]106a0812010-03-18 00:15:12884 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57885 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47886 return;
initial.commit09911bf2008-07-26 23:55:29887 }
Lei Zhang96031532019-10-10 19:05:47888
Wang Huia25efabc2022-09-24 17:27:22889 // Set ReloadType for |entry|.
890 entry->set_reload_type(reload_type);
891
Lei Zhang96031532019-10-10 19:05:47892 if (!IsInitialNavigation())
893 DiscardNonCommittedEntries();
894
895 pending_entry_ = entry;
896 pending_entry_index_ = current_index;
897 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
898
Nate Chapin45f620582021-09-30 17:45:43899 // location.reload() goes through BeginNavigation, so all reloads triggered
900 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13901 NavigateToExistingPendingEntry(
902 reload_type,
903 /*initiator_rfh=*/nullptr,
904 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
905 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29906}
907
[email protected]d202a7c2012-01-04 07:53:47908void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48909 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12910}
911
[email protected]d202a7c2012-01-04 07:53:47912void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49913 // If the pending reload type has been cleared by another navigation
914 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48915 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49916 return;
[email protected]106a0812010-03-18 00:15:12917 }
Wang Hui96ab1012022-10-11 02:05:49918 Reload(pending_reload_, false);
919 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12920}
921
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57922bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09923 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11924}
925
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57926bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38927 // Check that we're on the initial NavigationEntry and that this is not a
928 // cloned tab.
929 return IsInitialNavigation() && GetEntryCount() == 1 &&
930 GetLastCommittedEntry()->IsInitialEntry() &&
931 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40932}
933
Aran Gilman37d11632019-10-08 23:07:15934NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
935 int nav_entry_id) const {
avi254eff02015-07-01 08:27:58936 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:03937 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:58938}
939
Adithya Srinivasan9b0c99c2021-08-10 15:19:45940NavigationEntryImpl*
941NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
942 int nav_entry_id) const {
943 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
944 if (entry)
945 return entry;
946 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:52947 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:45948 : nullptr;
949}
950
W. James MacLeanc07dc41b2022-07-25 18:52:16951void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:57952 const url::Origin& origin) {
953 for (int i = 0; i < GetEntryCount(); i++) {
954 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:16955 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57956 }
957 if (entry_replaced_by_post_commit_error_) {
958 // It's possible we could come back to this entry if the error
959 // page/interstitial goes away.
960 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:16961 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57962 }
W. James MacLean1c40862c2020-04-27 21:05:57963}
964
avi25764702015-06-23 15:43:37965void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:57966 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:00967 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:37968 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:27969 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:20970}
971
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57972NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:47973 if (pending_entry_)
974 return pending_entry_;
975 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:20976}
977
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57978NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:32979 // The pending entry is safe to return for new (non-history), browser-
980 // initiated navigations. Most renderer-initiated navigations should not
981 // show the pending entry, to prevent URL spoof attacks.
982 //
983 // We make an exception for renderer-initiated navigations in new tabs, as
984 // long as no other page has tried to access the initial empty document in
985 // the new tab. If another page modifies this blank page, a URL spoof is
986 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:32987 bool safe_to_show_pending =
988 pending_entry_ &&
989 // Require a new navigation.
avi0dca04d2015-01-26 20:21:09990 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:32991 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:46992 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:32993
994 // Also allow showing the pending entry for history navigations in a new tab,
995 // such as Ctrl+Back. In this case, no existing page is visible and no one
996 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:15997 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
998 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:32999 safe_to_show_pending = true;
1000
1001 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191002 return pending_entry_;
1003 return GetLastCommittedEntry();
1004}
1005
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571006int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201007 if (pending_entry_index_ != -1)
1008 return pending_entry_index_;
1009 return last_committed_entry_index_;
1010}
1011
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571012NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381013 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031014 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201015}
1016
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571017bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351018 const std::string& mime_type = frame_tree_->root()
1019 ->current_frame_host()
1020 ->GetPage()
1021 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531022 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1023 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271024 NavigationEntry* visible_entry = GetVisibleEntry();
1025 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391026 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161027}
1028
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571029int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271030 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451031 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271032 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551033 return last_committed_entry_index_;
1034}
1035
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571036int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451037 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291038 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551039 return static_cast<int>(entries_.size());
1040}
1041
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571042NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371043 if (index < 0 || index >= GetEntryCount())
1044 return nullptr;
1045
avif16f85a72015-11-13 18:25:031046 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251047}
1048
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571049NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471050 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201051}
1052
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571053int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461054 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031055}
1056
Kevin McNee3b3a56192023-03-17 14:40:591057absl::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031058 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591059 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1060 return index;
1061 }
Shivani Sharma298d12852019-01-22 20:04:031062 }
Kevin McNee3b3a56192023-03-17 14:40:591063 return absl::nullopt;
1064}
1065
1066bool NavigationControllerImpl::CanGoBack() {
1067 return GetIndexForGoBack().has_value();
1068}
1069
1070absl::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
1071 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1072 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1073 return index;
1074 }
1075 }
1076 return absl::nullopt;
[email protected]765b35502008-08-21 00:51:201077}
1078
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571079bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591080 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201081}
1082
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571083bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031084 int index = GetIndexForOffset(offset);
1085 return index >= 0 && index < GetEntryCount();
1086}
1087
Xiaohan Wang7f8052e02022-01-14 18:44:281088#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151089bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151090 if (offset == 0)
1091 return true;
1092 int increment = offset > 0 ? 1 : -1;
1093 int non_skippable_entries = 0;
1094 for (int index = GetIndexForOffset(increment);
1095 index >= 0 && index < GetEntryCount(); index += increment) {
1096 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1097 non_skippable_entries++;
1098
1099 if (non_skippable_entries == std::abs(offset))
1100 return true;
1101 }
1102 return false;
1103}
1104#endif
1105
[email protected]d202a7c2012-01-04 07:53:471106void NavigationControllerImpl::GoBack() {
Kevin McNee3b3a56192023-03-17 14:40:591107 const absl::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061108
Kevin McNeeedc481c2023-04-27 22:30:581109 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211110
Kevin McNee3b3a56192023-03-17 14:40:591111 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201112}
1113
[email protected]d202a7c2012-01-04 07:53:471114void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161115 // Note that at least one entry (the last one) will be non-skippable since
1116 // entries are marked skippable only when they add another entry because of
1117 // redirect or pushState.
Kevin McNee3b3a56192023-03-17 14:40:591118 const absl::optional<int> target_index = GetIndexForGoForward();
1119
Kevin McNeeedc481c2023-04-27 22:30:581120 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591121
1122 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201123}
1124
[email protected]d202a7c2012-01-04 07:53:471125void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131126 GoToIndex(index, /*initiator_rfh=*/nullptr,
1127 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
1128 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161129}
1130
Nate Chapinbf682fa32022-09-26 22:41:201131void NavigationControllerImpl::GoToIndex(
1132 int index,
1133 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131134 absl::optional<blink::scheduler::TaskAttributionId>
1135 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201136 const std::string* navigation_api_key) {
Rakina Zata Amnid605d462022-06-01 10:17:031137 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
sunjian30574a62017-03-21 21:39:441138 TRACE_EVENT0("browser,navigation,benchmark",
1139 "NavigationControllerImpl::GoToIndex");
[email protected]765b35502008-08-21 00:51:201140 if (index < 0 || index >= static_cast<int>(entries_.size())) {
Rakina Zata Amni4595c36a2023-02-01 03:51:181141 // We've seen reports of this NOTREACHED being hit on Android WebView, where
1142 // we won't get the log message below. The following code ensures that
1143 // `index` and `entries_size` will show up on the minidump for that case.
1144 base::debug::Alias(&index);
1145 const size_t entries_size = entries_.size();
1146 base::debug::Alias(&entries_size);
1147 NOTREACHED() << "Index " << index
1148 << " is out of bounds, entries_.size() is " << entries_size;
[email protected]765b35502008-08-21 00:51:201149 return;
1150 }
1151
Rakina Zata Amnif297a802022-01-18 03:53:431152 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1153 // We should never navigate to an existing initial NavigationEntry that is
1154 // the initial NavigationEntry for the initial empty document that hasn't
1155 // been overridden by the synchronous about:blank commit, to preserve
1156 // legacy behavior where trying to reload when the main frame is on the
1157 // initial empty document won't result in a navigation. See also
1158 // https://crbug.com/1277414.
1159 return;
1160 }
1161
[email protected]cbab76d2008-10-13 22:42:471162 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201163
arthursonzogni5c4c202d2017-04-25 23:41:271164 DCHECK_EQ(nullptr, pending_entry_);
1165 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431166
arthursonzogni5c4c202d2017-04-25 23:41:271167 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201168 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271169 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1170 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201171 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131172 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201173 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201174}
1175
[email protected]d202a7c2012-01-04 07:53:471176void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121177 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031178 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201179 return;
1180
[email protected]9ba14052012-06-22 23:50:031181 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201182}
1183
Nate Chapinbf682fa32022-09-26 22:41:201184void NavigationControllerImpl::GoToOffsetFromRenderer(
1185 int offset,
Yoav Weiss8c573952022-11-17 17:35:131186 RenderFrameHostImpl* initiator_rfh,
1187 absl::optional<blink::scheduler::TaskAttributionId>
1188 soft_navigation_heuristics_task_id) {
Nate Chapin758e5e482023-05-02 00:22:551189 // If the renderer sent an out-of-bounds offset, cancel and notify the
1190 // renderer.
1191 if (!CanGoToOffset(offset)) {
1192 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
1193 /*navigation_api_key=*/std::string(),
1194 blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapin45f620582021-09-30 17:45:431195 return;
Nate Chapin758e5e482023-05-02 00:22:551196 }
Nate Chapin45f620582021-09-30 17:45:431197
Nate Chapinbf682fa32022-09-26 22:41:201198 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131199 soft_navigation_heuristics_task_id,
1200 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431201}
1202
Xiaohan Wang7f8052e02022-01-14 18:44:281203#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151204void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1205 // Note: This is actually reached in unit tests.
1206 if (!CanGoToOffsetWithSkipping(offset))
1207 return;
1208
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421209 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151210 GoToIndex(GetIndexForOffset(offset));
1211 return;
1212 }
1213 int increment = offset > 0 ? 1 : -1;
1214 // Find the offset without counting skippable entries.
1215 int target_index = GetIndexForOffset(increment);
1216 int non_skippable_entries = 0;
1217 for (int index = target_index; index >= 0 && index < GetEntryCount();
1218 index += increment) {
1219 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1220 non_skippable_entries++;
1221
1222 if (non_skippable_entries == std::abs(offset)) {
1223 target_index = index;
1224 break;
1225 }
1226 }
1227
1228 GoToIndex(target_index);
1229}
1230#endif
1231
[email protected]41374f12013-07-24 02:49:281232bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151233 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281234 return false;
[email protected]6a13a6c2011-12-20 21:47:121235
[email protected]43032342011-03-21 14:10:311236 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281237 return true;
[email protected]cbab76d2008-10-13 22:42:471238}
1239
Michael Thiessen9b14d512019-09-23 21:19:471240void NavigationControllerImpl::PruneForwardEntries() {
1241 DiscardNonCommittedEntries();
1242 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471243 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471244 if (num_removed <= 0)
1245 return;
Nate Chapin9eb16be72022-09-23 22:54:311246 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471247 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1248 NotifyPrunedEntries(this, remove_start_index /* start index */,
1249 num_removed /* count */);
1250}
1251
Aran Gilman37d11632019-10-08 23:07:151252void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1253 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321254 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311255 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511256 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1257 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321258 }
1259}
1260
Harkiran Bolariaba823e42021-05-21 18:30:361261base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1262 const GURL& url,
1263 const Referrer& referrer,
1264 ui::PageTransition transition,
1265 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471266 LoadURLParams params(url);
1267 params.referrer = referrer;
1268 params.transition_type = transition;
1269 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361270 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471271}
1272
Harkiran Bolariaba823e42021-05-21 18:30:361273base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1274 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061275 if (params.is_renderer_initiated)
1276 DCHECK(params.initiator_origin.has_value());
1277
naskob8744d22014-08-28 17:07:431278 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151279 "NavigationControllerImpl::LoadURLWithParams", "url",
1280 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291281 bool is_explicit_navigation =
1282 GetContentClient()->browser()->IsExplicitNavigation(
1283 params.transition_type);
1284 if (HandleDebugURL(params.url, params.transition_type,
1285 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431286 // If Telemetry is running, allow the URL load to proceed as if it's
1287 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491288 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431289 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361290 return nullptr;
[email protected]47752982014-07-29 08:01:431291 }
[email protected]8bf1048012012-02-08 01:22:181292
[email protected]cf002332012-08-14 19:17:471293 // Checks based on params.load_type.
1294 switch (params.load_type) {
1295 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431296 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471297 break;
1298 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261299 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471300 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361301 return nullptr;
[email protected]cf002332012-08-14 19:17:471302 }
1303 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461304 }
[email protected]e47ae9472011-10-13 19:48:341305
[email protected]e47ae9472011-10-13 19:48:341306 // The user initiated a load, we don't need to reload anymore.
1307 needs_reload_ = false;
1308
Harkiran Bolariaba823e42021-05-21 18:30:361309 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441310}
1311
Mohamed Abdelhalim833de902019-09-16 17:41:451312bool NavigationControllerImpl::PendingEntryMatchesRequest(
1313 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191314 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451315 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191316}
1317
[email protected]d202a7c2012-01-04 07:53:471318bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321319 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071320 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331321 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441322 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251323 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471324 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131325 NavigationRequest* navigation_request) {
1326 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331327
1328 // Note: validation checks and renderer kills due to invalid commit messages
1329 // must happen before getting here, in
1330 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1331 // effects of the navigation have already occurred.
1332
[email protected]cd2e15742013-03-08 04:08:311333 is_initial_navigation_ = false;
1334
Wang Hui96ab1012022-10-11 02:05:491335 // Any pending request to repost a form submission is no longer valid, since a
1336 // different NavigationEntry is committing.
1337 pending_reload_ = ReloadType::NONE;
1338
[email protected]0e8db942008-09-24 21:21:481339 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431340 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451341 if (entry_replaced_by_post_commit_error_) {
1342 // Same document navigation events with a post-commit error should already
1343 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1344 // reaching here.
1345 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331346
Rakina Zata Amnie2d31312022-11-18 03:38:451347 // Any commit while a post-commit error page is showing should put the
1348 // original entry back, replacing the error page's entry. This includes
1349 // reloads, where the original entry was used as the pending entry and
1350 // should now be at the correct index at commit time.
1351 entries_[last_committed_entry_index_] =
1352 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481353 }
Rakina Zata Amnie2d31312022-11-18 03:38:451354 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1355 details->previous_entry_index = GetLastCommittedEntryIndex();
1356 if (PendingEntryMatchesRequest(navigation_request) &&
1357 pending_entry_->GetIsOverridingUserAgent() !=
1358 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1359 overriding_user_agent_changed = true;
1360 }
1361#if BUILDFLAG(IS_ANDROID)
1362 // TODO(crbug.com/1266277): Clean up the logic of setting
1363 // |overriding_user_agent_changed| post-launch.
1364 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1365 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
1366 // Must honor user agent overrides in the |navigation_request|, such as
1367 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1368 // result, besides comparing |pending_entry_|'s user agent against
1369 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1370 // agent against LastCommittedEntry's.
1371 if (navigation_request->is_overriding_user_agent() !=
1372 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1373 overriding_user_agent_changed = true;
1374 }
1375 }
1376#endif // BUILDFLAG(IS_ANDROID)
[email protected]ecd9d8702008-08-28 22:10:171377
Dave Tapuskaa2ab4f252021-07-08 21:31:281378 bool is_main_frame_navigation = !rfh->GetParent();
1379
Alexander Timind2f2e4f22019-04-02 20:04:531380 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1381 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281382 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141383 // BackForwardCacheMetrics to be associated with the new navigation's
1384 // NavigationEntry, by either creating a new object or reusing the previous
1385 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281386 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Arthur Sonzognif6785ec2022-12-05 10:11:501387 if (navigation_request->frame_tree_node()->frame_tree().type() ==
Dave Tapuskaa2ab4f252021-07-08 21:31:281388 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141389 back_forward_cache_metrics = BackForwardCacheMetrics::
1390 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281391 GetLastCommittedEntry(), is_main_frame_navigation,
1392 params.document_sequence_number);
1393 }
Yuzu Saijo29f96ca92022-12-08 04:54:121394
Alexander Timind2f2e4f22019-04-02 20:04:531395 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281396 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451397 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1398 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531399 }
1400 }
1401
Rakina Zata Amnifd8370b2022-11-14 13:32:251402 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1403 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091404 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251405 details->did_replace_entry =
1406 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091407
fdegans9caf66a2015-07-30 21:10:421408 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111409 // except for restored entries. This should be true even if the current commit
1410 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291411 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481412 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081413 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111414
1415 // Only make changes based on the pending entry if the NavigationRequest
1416 // matches it. Otherwise, the pending entry may be for a different request
1417 // (e.g., if a slow history navigation is pending while an auto-subframe
1418 // commit occurs).
1419 if (PendingEntryMatchesRequest(navigation_request)) {
1420 // It is no longer necessary to consider the pending entry as restored.
1421 if (pending_entry_->IsRestored()) {
1422 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1423 was_restored = true;
1424 }
[email protected]e9ba4472008-09-14 15:42:431425
Charlie Reisf8cde712022-10-20 16:25:091426 // If the SiteInstance has changed from the matching pending entry, this
1427 // must be treated as a new navigation with replacement. Set the replacement
1428 // bit here and ClassifyNavigation will identify this case and return
1429 // NEW_ENTRY.
1430 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1431 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1432 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251433 // TODO(nasko,creis,rakina): Move this to happen before committing the
1434 // navigation. This is a bit complicated because we don't currently
1435 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091436 details->did_replace_entry = true;
1437 }
Nasko Oskovaee2f862018-06-15 00:05:521438 }
[email protected]bcd904482012-02-01 01:54:221439
[email protected]e9ba4472008-09-14 15:42:431440 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101441 NavigationType navigation_type =
1442 ClassifyNavigation(rfh, params, navigation_request);
1443 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451444
Rakina Zata Amnie2d31312022-11-18 03:38:451445 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451446 // Ensure that this navigation does not add a navigation entry, since
1447 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1448 // beyond the last committed one. Therefore, `should_replace_current_entry`
1449 // should be set, which replaces the current entry, or this should be a
1450 // reload, which does not create a new entry.
1451 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1452 // navigation that is restored will not be creating a new entry anyways, so
1453 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1454 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1455 // pointed out in the issue.
Rakina Zata Amnifd8370b2022-11-14 13:32:251456 DCHECK(navigation_request->common_params().should_replace_current_entry ||
shivanigithub189833f2022-04-27 18:08:451457 navigation_request->GetReloadType() != ReloadType::NONE ||
Miyoung Shin3299cbf2022-11-22 01:41:101458 navigation_type == NAVIGATION_TYPE_AUTO_SUBFRAME);
shivanigithub189833f2022-04-27 18:08:451459 }
1460
Rakina Zata Amnie2d31312022-11-18 03:38:451461 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551462 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241463 // This is a subframe navigation on the initial empty document, which used
1464 // to not have a NavigationEntry to attach to. Now it can attach to the
1465 // initial NavigationEntry, and we must ensure that its NavigationEntry
1466 // will keep the "initial NavigationEntry" status and won't append a new
1467 // NavigationEntry (it should always do replacement instead).
1468 // See also https://crbug.com/1277414.
1469 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551470 // Subframe navigation on initial NavigationEntry must not append a new
1471 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1472 // means every subframe navigation that happens while we're on the initial
1473 // NavigationEntry will always reuse the existing NavigationEntry and
1474 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101475 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1476 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551477 // This is a navigation that modifies the initial NavigationEntry, either
1478 // for a replacement or a reload. The initial NavigationEntry should
1479 // retain its "initial NavigationEntry" status in this case.
1480 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241481 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251482 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1483 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241484 // This is a synchronous about:blank navigation on the main frame, which
1485 // used to not create a NavigationEntry when we have no NavigationEntry on
1486 // FrameTree creation. We now have the initial NavigationEntry and are on
1487 // the initial NavigationEntry. To preserve old behavior, we should still
1488 // keep the "initial" status for the new NavigationEntry that we will
1489 // create for this navigation, so that subframe navigations under the
1490 // synchronously committed about:blank document will never append new
1491 // NavigationEntry, and instead will just reuse the initial
1492 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1493 // See also https://crbug.com/1277414.
1494 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551495 }
1496 }
1497 DCHECK(!details->should_stay_as_initial_entry ||
1498 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201499
eugenebutee08663a2017-04-27 17:43:121500 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441501 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121502
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071503 details->is_prerender_activation =
1504 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241505 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1506 ->GetOutermostMainFrame()
1507 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071508
Peter Boströmd7592132019-01-30 04:50:311509 // Make sure we do not discard the pending entry for a different ongoing
1510 // navigation when a same document commit comes in unexpectedly from the
1511 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1512 // other navigation types. See https://crbug.com/900036.
1513 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061514 bool keep_pending_entry =
1515 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101516 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061517 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311518
Miyoung Shin3299cbf2022-11-22 01:41:101519 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061520 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491521 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051522 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001523 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431524 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061525 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491526 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1527 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001528 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431529 break;
[email protected]8ff00d72012-10-23 19:12:211530 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471531 RendererDidNavigateNewSubframe(
1532 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001533 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431534 break;
[email protected]8ff00d72012-10-23 19:12:211535 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391536 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251537 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001538 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081539 // We don't send a notification about auto-subframe PageState during
1540 // UpdateStateForFrame, since it looks like nothing has changed. Send
1541 // it here at commit time instead.
1542 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431543 return false;
creis59d5a47cb2016-08-24 23:57:191544 }
[email protected]e9ba4472008-09-14 15:42:431545 break;
Aran Gilman37d11632019-10-08 23:07:151546 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431547 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151548 break;
[email protected]765b35502008-08-21 00:51:201549 }
1550
[email protected]688aa65c62012-09-28 04:32:221551 // At this point, we know that the navigation has just completed, so
1552 // record the time.
1553 //
1554 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261555 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331556 base::Time timestamp =
1557 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1558 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131559 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221560
Peter Boströmd7592132019-01-30 04:50:311561 // If we aren't keeping the pending entry, there shouldn't be one at this
1562 // point. Clear it again in case any error cases above forgot to do so.
1563 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1564 // been cleared instead of protecting against it.
1565 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551566 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141567
[email protected]e9ba4472008-09-14 15:42:431568 // All committed entries should have nonempty content state so WebKit doesn't
1569 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471570 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321571 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221572 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441573 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141574
Alexander Timind2f2e4f22019-04-02 20:04:531575 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1576 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281577 if (back_forward_cache_metrics &&
1578 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531579 active_entry->set_back_forward_cache_metrics(
1580 std::move(back_forward_cache_metrics));
1581 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281582
1583 // `back_forward_cache_metrics()` may return null as we do not record
1584 // back-forward cache metrics for navigations in non-primary frame trees.
1585 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141586 // TODO(https://crbug.com/1338089): Remove this.
1587 // These are both only available from details at this point, so we capture
1588 // them here.
1589 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101590 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141591 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1592 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281593 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1594 navigation_request,
1595 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1596 }
naskoc7533512016-05-06 17:01:121597
Charles Reisc0507202017-09-21 00:40:021598 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1599 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1600 // A mismatch can occur if the renderer lies or due to a unique name collision
1601 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121602 FrameNavigationEntry* frame_entry =
1603 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021604 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1605 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031606 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081607 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1608 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031609 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201610
1611 // Remember the bindings the renderer process has at this point, so that
1612 // we do not grant this entry additional bindings if we come back to it.
1613 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301614 }
[email protected]132e281a2012-07-31 18:32:441615
[email protected]97d8f0d2013-10-29 16:49:211616 // Once it is committed, we no longer need to track several pieces of state on
1617 // the entry.
naskoc7533512016-05-06 17:01:121618 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131619
[email protected]49bd30e62011-03-22 20:12:591620 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221621 // TODO(creis): This check won't pass for subframes until we create entries
1622 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001623 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421624 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591625
[email protected]e9ba4472008-09-14 15:42:431626 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001627 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001628 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311629 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531630
arthursonzogni7ddc6542021-04-09 09:16:501631 active_entry->SetIsOverridingUserAgent(
1632 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031633
[email protected]93f230e02011-06-01 14:40:001634 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291635
aelias100c9192017-01-13 00:01:431636 if (overriding_user_agent_changed)
1637 delegate_->UpdateOverridingUserAgent();
1638
creis03b48002015-11-04 00:54:561639 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1640 // one knows the latest NavigationEntry it is showing (whether it has
1641 // committed anything in this navigation or not). This allows things like
1642 // state and title updates from RenderFrames to apply to the latest relevant
1643 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381644 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031645 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381646 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431647
1648 if (navigation_request->IsPrerenderedPageActivation()) {
1649 BroadcastHistoryOffsetAndLength();
1650 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1651 // is activated. As a result, a "prerenderingchange" event listener sees the
1652 // history.length which is not updated yet. We should guarantee that
1653 // history's length and offset should be updated before a
1654 // "prerenderingchange" event listener runs. One possible approach is to use
1655 // the same IPC which "prerenderingchange" uses, and propagate history's
1656 // length and offset together with that.
1657 }
1658
[email protected]e9ba4472008-09-14 15:42:431659 return true;
initial.commit09911bf2008-07-26 23:55:291660}
1661
[email protected]8ff00d72012-10-23 19:12:211662NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321663 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101664 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241665 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591666 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511667 "ClassifyNavigation");
1668
avi7c6f35e2015-05-08 17:52:381669 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241670 // A new entry. We may or may not have a corresponding pending entry, and
1671 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001672 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491673 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061674 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381675 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241676 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511677 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381678 return NAVIGATION_TYPE_NEW_SUBFRAME;
1679 }
1680
Charlie Reisc0f17d2d2021-01-12 18:52:491681 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381682 DCHECK(!params.history_list_was_cleared);
1683
avi39c1edd32015-06-04 20:06:001684 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381685 // All manual subframes would be did_create_new_entry and handled above, so
1686 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081687 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1688 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381689 }
1690
Rakina Zata Amnif6950d552020-11-24 03:26:101691 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1692 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381693 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1694 // create a new page.
1695
Hayato Ito2ae49442021-07-02 02:59:251696 // This main frame navigation is not a history navigation (since
1697 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1698 // reload or a replacement navigation, which will modify the existing entry.
1699 //
Nasko Oskov332593c2018-08-16 17:21:341700 // TODO(nasko): With error page isolation, reloading an existing session
1701 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491702 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341703 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511704 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491705 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061706 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381707 }
1708
Charlie Reisf8cde712022-10-20 16:25:091709 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521710 // If the SiteInstance of the |pending_entry_| does not match the
1711 // SiteInstance that got committed, treat this as a new navigation with
1712 // replacement. This can happen if back/forward/reload encounters a server
1713 // redirect to a different site or an isolated error page gets successfully
1714 // reloaded into a different SiteInstance.
1715 if (pending_entry_->site_instance() &&
1716 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491717 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061718 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521719 }
creis77c9aa32015-09-25 19:59:421720
Nasko Oskovaee2f862018-06-15 00:05:521721 if (pending_entry_index_ == -1) {
1722 // In this case, we have a pending entry for a load of a new URL but Blink
1723 // didn't do a new navigation (params.did_create_new_entry). First check
1724 // to make sure Blink didn't treat a new cross-process navigation as
1725 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161726 // we must treat it as NEW rather than the converted reload case below,
1727 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451728 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161729 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061730 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521731 }
1732
1733 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161734 // We will create a pending entry, but NavigateWithoutEntry will convert
1735 // it to a reload since it's the same page and not create a new entry for
1736 // it. (The user doesn't want to have a new back/forward entry when they
1737 // do this.) Therefore we want to just ignore the pending entry and go
1738 // back to where we were (the "existing entry").
1739 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061740 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521741 }
avi7c6f35e2015-05-08 17:52:381742 }
1743
Rakina Zata Amni153d5702021-09-13 22:48:001744 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381745 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491746 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1747 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161748 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061749 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381750 }
1751
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121752 if (navigation_request->DidEncounterError() &&
1753 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101754 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381755 // If the renderer was going to a new pending entry that got cleared because
1756 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491757 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381758 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511759 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491760 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061761 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381762 }
1763
Charlie Reisc0f17d2d2021-01-12 18:52:491764 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101765 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511766 trace_return.traced_value()->SetInteger("existing_entry_index",
1767 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381768 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441769 // The renderer has committed a navigation to an entry that no longer
1770 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491771 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061772 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381773 }
1774
avi7c6f35e2015-05-08 17:52:381775 // Since we weeded out "new" navigations above, we know this is an existing
1776 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491777 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061778 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381779}
1780
Rakina Zata Amni3460d382021-10-29 00:43:371781void NavigationControllerImpl::UpdateNavigationEntryDetails(
1782 NavigationEntryImpl* entry,
1783 RenderFrameHostImpl* rfh,
1784 const mojom::DidCommitProvisionalLoadParams& params,
1785 NavigationRequest* request,
1786 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001787 bool is_new_entry,
1788 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371789 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171790 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371791 entry->AddOrUpdateFrameEntry(
1792 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571793 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371794 rfh->GetSiteInstance(), nullptr, params.url,
1795 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171796 Referrer(*params.referrer),
1797 request ? request->common_params().initiator_origin : params.origin,
W. James MacLean23e90a12022-12-21 04:38:211798 request ? request->common_params().initiator_base_url : absl::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171799 request ? request->GetRedirectChain() : redirects, params.page_state,
1800 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amniafd3c6582021-11-30 06:19:171801 (request ? request->GetSubresourceWebBundleNavigationInfo() : nullptr),
Rakina Zata Amni3460d382021-10-29 00:43:371802 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171803 rfh, request && request->IsSameDocument(),
1804 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371805
1806 if (rfh->GetParent()) {
1807 // Only modify the NavigationEntry for main frame navigations.
1808 return;
1809 }
1810 if (entry->update_virtual_url_with_url())
1811 UpdateVirtualURLToURL(entry, params.url);
1812 // Don't use the page type from the pending entry. Some interstitial page
1813 // may have set the type to interstitial. Once we commit, however, the page
1814 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171815 entry->set_page_type((request && request->DidEncounterError())
1816 ? PAGE_TYPE_ERROR
1817 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431818 if (commit_details && commit_details->should_stay_as_initial_entry) {
1819 // Retain the "initial NavigationEntry" status.
1820 if (request->IsSameDocument()) {
1821 // If this is for a same-document navigation, the NavigationEntry must be
1822 // reused and should already be marked as the initial NavigationEntry.
1823 DCHECK(entry->IsInitialEntry());
1824 } else {
1825 // If this is for a cross-document navigation, it can be caused by a
1826 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1827 // "for synchronous about:blank" in the latter case, and also when it is
1828 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1829 // is not for a synchronous about:blank commit.
1830 NavigationEntryImpl::InitialNavigationEntryState new_state =
1831 NavigationEntryImpl::InitialNavigationEntryState::
1832 kInitialNotForSynchronousAboutBlank;
1833 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1834 request->is_synchronous_renderer_commit()) {
1835 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1836 kInitialForSynchronousAboutBlank;
1837 }
1838 entry->set_initial_navigation_entry_state(new_state);
1839 }
1840 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1841 // Remove the "initial NavigationEntry" status.
1842 entry->set_initial_navigation_entry_state(
1843 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001844 }
Rakina Zata Amniddf10502022-01-15 02:56:551845
Rakina Zata Amni3460d382021-10-29 00:43:371846 if (is_new_entry) {
1847 // Some properties of the NavigationEntry are only set when the entry is
1848 // new (we aren't reusing it).
1849 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171850 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1851 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371852 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1853 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1854 } else {
1855 // We are reusing the NavigationEntry. The site instance will normally be
1856 // the same except for a few cases:
1857 // 1) session restore, when no site instance will be assigned or
1858 // 2) redirect, when the site instance is reset.
1859 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1860 entry->site_instance() == rfh->GetSiteInstance());
1861 }
1862}
1863
Rakina Zata Amniafd3c6582021-11-30 06:19:171864void NavigationControllerImpl::CreateInitialEntry() {
1865 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031866 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171867 auto params = mojom::DidCommitProvisionalLoadParams::New();
1868 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1869 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1870 // before we have initial NavigationEntries.
1871 params->url = GURL::EmptyGURL();
1872 params->http_status_code = 0;
1873 params->url_is_unreachable = false;
1874 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171875 params->post_id = -1;
1876 params->embedding_token = base::UnguessableToken::Create();
1877 params->navigation_token = base::UnguessableToken::Create();
1878 params->did_create_new_entry = true;
1879 params->origin = rfh->GetLastCommittedOrigin();
1880 params->should_update_history = true;
1881 params->item_sequence_number = 0;
1882 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151883 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171884 params->transition = is_in_fenced_frame_tree
1885 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1886 : ui::PAGE_TRANSITION_LINK;
1887 params->referrer = blink::mojom::Referrer::New();
1888
Rakina Zata Amniafd3c6582021-11-30 06:19:171889 auto new_entry = std::make_unique<NavigationEntryImpl>(
1890 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381891 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211892 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1893 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1894 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171895 UpdateNavigationEntryDetails(
1896 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001897 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1898 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171899
1900 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1901 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001902 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171903}
1904
Charlie Reisc0f17d2d2021-01-12 18:52:491905void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321906 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071907 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361908 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441909 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471910 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001911 NavigationRequest* request,
1912 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571913 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071914 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451915 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:521916 absl::optional<GURL> initiator_base_url;
1917 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
1918 initiator_base_url = request->common_params().initiator_base_url;
1919 }
Lukasz Anforowicz435bcb582019-07-12 20:50:061920
creisf49dfc92016-07-26 17:05:181921 // First check if this is an in-page navigation. If so, clone the current
1922 // entry instead of looking at the pending entry, because the pending entry
1923 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451924 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301925 FrameNavigationEntry* previous_frame_entry =
1926 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451927 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481928 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571929 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:081930 rfh->GetSiteInstance(), nullptr, params.url,
1931 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:211932 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:091933 request->GetRedirectChain(), params.page_state, params.method,
1934 params.post_id, nullptr /* blob_url_loader_factory */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:481935 request->GetSubresourceWebBundleNavigationInfo(),
Antonio Sartori78a749f2020-11-30 12:03:391936 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301937 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:571938 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:301939 // FrameNavigationEntry.
1940 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:571941 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:031942
creisf49dfc92016-07-26 17:05:181943 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:031944 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:521945 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1946 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571947 // TODO(jam): we had one report of this with a URL that was redirecting to
1948 // only tildes. Until we understand that better, don't copy the cert in
1949 // this case.
1950 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571951 }
creisf49dfc92016-07-26 17:05:181952
Patrick Monette50e8bd82019-06-13 22:40:451953 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1954 // that |frame_entry| should now have a reference count of exactly 2: one
1955 // due to the local variable |frame_entry|, and another due to |new_entry|
1956 // also retaining one. This should never fail, because it's the main frame.
1957 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181958 }
1959
Harkiran Bolaria59290d62021-03-17 01:53:011960 // If this is an activation navigation from a prerendered page, transfer the
1961 // new entry from an entry already created and stored in the
1962 // NavigationRequest. |new_entry| will not have been set prior to this as
1963 // |is_same_document| is mutually exclusive with
1964 // |IsPrerenderedPageActivation|.
1965 if (request->IsPrerenderedPageActivation()) {
1966 DCHECK(!is_same_document);
1967 DCHECK(!new_entry);
1968 new_entry = request->TakePrerenderNavigationEntry();
1969 DCHECK(new_entry);
1970 }
1971
Charlie Reisc0f17d2d2021-01-12 18:52:491972 // Only make a copy of the pending entry if it is appropriate for the new
1973 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451974 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041975 // 1. The SiteInstance hasn't been assigned to something else.
1976 // 2. The pending entry was intended as a new entry, rather than being a
1977 // history navigation that was interrupted by an unrelated,
1978 // renderer-initiated navigation.
1979 // TODO(csharrison): Investigate whether we can remove some of the coarser
1980 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451981 if (!new_entry && PendingEntryMatchesRequest(request) &&
1982 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:341983 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:431984 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:351985 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:431986
Camille Lamy62b826012019-02-26 09:15:471987 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451988 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:181989 }
1990
Charlie Reisc0f17d2d2021-01-12 18:52:491991 // For cross-document commits with no matching pending entry, create a new
1992 // entry.
creisf49dfc92016-07-26 17:05:181993 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061994 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:071995 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:211996 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:581997 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:451998 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:171999 nullptr, // blob_url_loader_factory
2000 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242001
2002 // Find out whether the new entry needs to update its virtual URL on URL
2003 // change and set up the entry accordingly. This is needed to correctly
2004 // update the virtual URL when replaceState is called after a pushState.
2005 GURL url = params.url;
2006 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492007 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412008 // update the virtual URL based on the new URL. For example, this is needed
2009 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2010 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372011 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2012 &url, browser_context_, &needs_update);
2013 new_entry->set_update_virtual_url_with_url(needs_update);
2014
Camille Lamy62b826012019-02-26 09:15:472015 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452016 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432017 }
2018
Harkiran Bolaria59290d62021-03-17 01:53:012019 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
2020 // for prerendered contents, if any. This is because prerendering/activation
2021 // technically won't be creating a new document. Unlike BFCache, prerendering
2022 // creates a new NavigationEntry rather than using an existing one.
2023 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372024 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2025 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002026 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082027
Harkiran Bolaria59290d62021-03-17 01:53:012028 // history.pushState() is classified as a navigation to a new page, but sets
2029 // is_same_document to true. In this case, we already have the title and
2030 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452031 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012032 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2033 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2034 }
[email protected]3a868f212014-08-09 10:41:192035 }
[email protected]ff64b3e2014-05-31 04:07:332036
[email protected]60d6cca2013-04-30 08:47:132037 DCHECK(!params.history_list_was_cleared || !replace_entry);
2038 // The browser requested to clear the session history when it initiated the
2039 // navigation. Now we know that the renderer has updated its state accordingly
2040 // and it is safe to also clear the browser side history.
2041 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552042 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132043 entries_.clear();
2044 last_committed_entry_index_ = -1;
2045 }
2046
Nasko Oskovaee2f862018-06-15 00:05:522047 // If this is a new navigation with replacement and there is a
2048 // pending_entry_ which matches the navigation reported by the renderer
2049 // process, then it should be the one replaced, so update the
2050 // last_committed_entry_index_ to use it.
2051 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092052 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522053 last_committed_entry_index_ = pending_entry_index_;
2054 }
2055
Alexander Timine3ec4192020-04-20 16:39:402056 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412057 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402058 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052059
Yuzu Saijoa725585f2022-11-28 04:14:032060 // If this is a history navigation and the old entry has an existing
2061 // back/forward cache metrics object, keep using the old one so that the
2062 // reasons logged from the last time the page navigated gets preserved.
2063 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2064 request)) {
2065 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2066 // because some tests do not have a pending entry.
2067 NavigationEntryImpl* entry =
2068 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2069 if (entry && entry->back_forward_cache_metrics()) {
2070 scoped_refptr<BackForwardCacheMetrics> metrics =
2071 entry->TakeBackForwardCacheMetrics();
2072 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2073 }
2074 }
2075
Carlos IL42b416592019-10-07 23:10:362076 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312077 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152078 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432079}
2080
Charlie Reisc0f17d2d2021-01-12 18:52:492081void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322082 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072083 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362084 bool is_same_document,
jam48cea9082017-02-15 06:13:292085 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452086 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002087 bool keep_pending_entry,
2088 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562089 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2090 << "that a last committed entry exists.";
2091
[email protected]e9ba4472008-09-14 15:42:432092 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002093 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432094
Charlie Reis7e2cb6d2021-01-26 01:27:162095 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002096 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162097 // We're guaranteed to have a last committed entry if intended_as_new_entry
2098 // is true.
avicbdc4c12015-07-01 16:07:112099 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162100
2101 // If the NavigationRequest matches a new pending entry and is classified as
2102 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2103 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092104 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162105 // Note: The pending entry will usually have a real ReloadType here, but
2106 // it can still be ReloadType::NONE in cases that
2107 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2108
2109 // If we classified this correctly, the SiteInstance should not have
2110 // changed.
2111 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2112
2113 // For converted reloads, we assign the entry's unique ID to be that of
2114 // the new one. Since this is always the result of a user action, we want
2115 // to dismiss infobars, etc. like a regular user-initiated navigation.
2116 entry->set_unique_id(pending_entry_->GetUniqueID());
2117
2118 // The extra headers may have changed due to reloading with different
2119 // headers.
2120 entry->set_extra_headers(pending_entry_->extra_headers());
2121 }
2122 // Otherwise, this was intended as a new entry but the pending entry was
2123 // lost in the meantime and no new entry was created. We are stuck at the
2124 // last committed entry.
2125
2126 // Even if this is a converted reload from pressing enter in the omnibox,
2127 // the server could redirect, requiring an update to the SSL status. If this
2128 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452129 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162130 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472131 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452132 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162133 }
Rakina Zata Amnif6950d552020-11-24 03:26:102134 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112135 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102136 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162137
eugenebut604866f2017-05-10 21:35:362138 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452139 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362140 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2141 // this was a restored same document navigation entry, then it won't have
2142 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2143 // navigated it.
jam48cea9082017-02-15 06:13:292144 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522145 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2146 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292147 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2148 was_restored) {
2149 entry->GetSSL() = last_entry->GetSSL();
2150 }
2151 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452152 // In rapid back/forward navigations |request| sometimes won't have a cert
2153 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192154 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452155 if (request->GetSSLInfo().has_value() &&
2156 request->GetSSLInfo()->is_valid()) {
2157 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522158 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2159 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192160 entry->GetSSL() = SSLStatus();
2161 }
jam48cea9082017-02-15 06:13:292162 }
avicbdc4c12015-07-01 16:07:112163 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272164 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572165 // navigations that are EXISTING_ENTRY are same-document navigations that
2166 // result in replacement (e.g. history.replaceState(), location.replace(),
2167 // forced replacements for trivial session history contexts). For these
2168 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112169 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102170
Mikel Astizba9cf2fd2017-12-17 10:38:102171 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2172 // to avoid misleading interpretations (e.g. URLs paired with
2173 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2174 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2175 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2176
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572177 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102178
eugenebut604866f2017-05-10 21:35:362179 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452180 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362181 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472182 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452183 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112184 }
2185 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432186
Rakina Zata Amni3460d382021-10-29 00:43:372187 UpdateNavigationEntryDetails(entry, rfh, params, request,
2188 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002189 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302190
[email protected]5ccd4dc2012-10-24 02:28:142191 // The redirected to page should not inherit the favicon from the previous
2192 // page.
eugenebut604866f2017-05-10 21:35:362193 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482194 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142195
Charlie Reis951f43372023-05-05 00:30:072196 // Update the last committed index to reflect the committed entry. Do this
2197 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2198 // delegate sees the correct committed index when notified of navigation
2199 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2200 // https://crbug.com/1439948.)
2201 if (base::FeatureList::IsEnabled(
2202 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2203 last_committed_entry_index_ = GetIndexOfEntry(entry);
2204 }
2205
Peter Boströmd7592132019-01-30 04:50:312206 // We should also usually discard the pending entry if it corresponds to a
2207 // different navigation, since that one is now likely canceled. In rare
2208 // cases, we leave the pending entry for another navigation in place when we
2209 // know it is still ongoing, to avoid a flicker in the omnibox (see
2210 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432211 //
2212 // Note that we need to use the "internal" version since we don't want to
2213 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312214 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002215 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392216
Charlie Reis951f43372023-05-05 00:30:072217 if (!base::FeatureList::IsEnabled(
2218 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2219 // Update the last committed index to reflect the committed entry.
2220 // (This is legacy behavior, in case the kill-switch needs to be used.)
2221 last_committed_entry_index_ = GetIndexOfEntry(entry);
2222 }
[email protected]e9ba4472008-09-14 15:42:432223}
2224
[email protected]d202a7c2012-01-04 07:53:472225void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322226 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072227 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362228 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472229 bool replace_entry,
2230 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002231 NavigationRequest* request,
2232 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262233 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2234 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552235 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2236 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112237
[email protected]e9ba4472008-09-14 15:42:432238 // Manual subframe navigations just get the current entry cloned so the user
2239 // can go back or forward to it. The actual subframe information will be
2240 // stored in the page state for each of those entries. This happens out of
2241 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092242 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2243 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382244
Mikel Astizba9cf2fd2017-12-17 10:38:102245 // The DCHECK below documents the fact that we don't know of any situation
2246 // where |replace_entry| is true for subframe navigations. This simplifies
2247 // reasoning about the replacement struct for subframes (see
2248 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2249 DCHECK(!replace_entry);
2250
Patrick Monette50e8bd82019-06-13 22:40:452251 // This FrameNavigationEntry might not end up being used in the
2252 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072253 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452254 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:522255 absl::optional<GURL> initiator_base_url;
2256 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2257 initiator_base_url = request->common_params().initiator_base_url;
2258 }
Nate Chapin63db0d12022-01-20 22:03:302259 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2260 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2261 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572262 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302263 if (is_same_document) {
2264 FrameNavigationEntry* previous_frame_entry =
2265 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572266 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302267 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572268 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302269 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572270 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302271 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572272 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302273 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572274 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302275 policy_container_policies->referrer_policy);
2276 }
2277
Patrick Monette50e8bd82019-06-13 22:40:452278 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482279 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572280 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082281 rfh->GetSiteInstance(), nullptr, params.url,
2282 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212283 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2284 request->GetRedirectChain(), params.page_state, params.method,
2285 params.post_id, nullptr /* blob_url_loader_factory */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482286 request->GetSubresourceWebBundleNavigationInfo(),
Domenic Denicolacc094fb2022-03-16 23:40:572287 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032288
creisce0ef3572017-01-26 17:53:082289 std::unique_ptr<NavigationEntryImpl> new_entry =
2290 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452291 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032292 frame_tree_->root());
creise062d542015-08-25 02:01:552293
Alexander Timine3ec4192020-04-20 16:39:402294 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412295 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402296 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472297
creisce0ef3572017-01-26 17:53:082298 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452299 // to replace, which can happen due to a unique name change. See
2300 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2301 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382302
Dave Tapuska87696ae2021-11-18 18:48:312303 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152304 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432305}
2306
[email protected]d202a7c2012-01-04 07:53:472307bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322308 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072309 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392310 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252311 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002312 NavigationRequest* request,
2313 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292314 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2315 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2316
[email protected]e9ba4472008-09-14 15:42:432317 // We're guaranteed to have a previously committed entry, and we now need to
2318 // handle navigation inside of a subframe in it without creating a new entry.
2319 DCHECK(GetLastCommittedEntry());
2320
creis913c63ce2016-07-16 19:52:522321 // For newly created subframes, we don't need to send a commit notification.
2322 // This is only necessary for history navigations in subframes.
2323 bool send_commit_notification = false;
2324
Rakina Zata Amnif6950d552020-11-24 03:26:102325 // If |nav_entry_id| is non-zero and matches an existing entry, this
2326 // is a history navigation. Update the last committed index accordingly. If
2327 // we don't recognize the |nav_entry_id|, it might be a recently
2328 // pruned entry. We'll handle it below.
2329 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2330 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472331 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062332 // Make sure that a subframe commit isn't changing the main frame's
2333 // origin. Otherwise the renderer process may be confused, leading to a
2334 // URL spoof. We can't check the path since that may change
2335 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572336 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2337 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242338 // We should use checks similar to RenderFrameHostImpl's
2339 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2340 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572341 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2342 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2343 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2344 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522345 current_top_url.DeprecatedGetOriginAsURL() !=
2346 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442347 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512348 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062349 }
creis3cdc3b02015-05-29 23:00:472350
creis913c63ce2016-07-16 19:52:522351 // We only need to discard the pending entry in this history navigation
2352 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062353 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002354 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522355
2356 // History navigations should send a commit notification.
2357 send_commit_notification = true;
avi98405c22015-05-21 20:47:062358 }
[email protected]e9ba4472008-09-14 15:42:432359 }
[email protected]f233e4232013-02-23 00:55:142360
creisce0ef3572017-01-26 17:53:082361 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2362 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372363 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2364 // exists), or we may want to clobber it and create a new one. We update in
2365 // cases where the corresponding FrameNavigationEntry is conceptually similar
2366 // to the document described by the commit params: same-document
2367 // navigations, history traversal to an existing entry, and reloads (including
2368 // a "soft reload" where we navigate to the same url without flagging it as a
2369 // reload). But in the case of a different document that is not logically
2370 // related to the committed FrameNavigationEntry's document (cross-document,
2371 // not same url, not a reload, not a history traversal), we replace rather
2372 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252373 //
Nate Chapin9f169072021-06-09 19:32:372374 // In the case where we update, the FrameNavigationEntry will potentially be
2375 // shared across multiple NavigationEntries, and any updates will be reflected
2376 // in all of those NavigationEntries. In the replace case, any existing
2377 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252378 //
2379 // When navigating away from the initial empty document, we also update rather
2380 // than replace. Either update or replace will overwrite the initial empty
2381 // document state for |last_committed|, but if the FrameNavigationEntry for
2382 // the initial empty document is shared across multiple NavigationEntries (due
2383 // to a navigation in another frame), we want to make sure we overwrite the
2384 // initial empty document state everywhere this FrameNavigationEntry is used,
2385 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452386 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372387 FrameNavigationEntry* last_committed_frame_entry =
2388 last_committed->GetFrameEntry(rfh->frame_tree_node());
2389 NavigationEntryImpl::UpdatePolicy update_policy =
2390 NavigationEntryImpl::UpdatePolicy::kUpdate;
2391 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312392 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372393 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252394 last_committed_frame_entry->url() != params.url &&
2395 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372396 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2397 }
2398
Rakina Zata Amni3460d382021-10-29 00:43:372399 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002400 update_policy, false /* is_new_entry */,
2401 commit_details);
creis625a0c7d2015-03-24 23:17:122402
creis913c63ce2016-07-16 19:52:522403 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432404}
2405
[email protected]d202a7c2012-01-04 07:53:472406int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232407 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032408 for (size_t i = 0; i < entries_.size(); ++i) {
2409 if (entries_[i].get() == entry)
2410 return i;
2411 }
2412 return -1;
[email protected]765b35502008-08-21 00:51:202413}
2414
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572415void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242416 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572417 NavigationControllerImpl* source =
2418 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572419 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382420 DCHECK_EQ(1, GetEntryCount());
2421 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472422 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172423 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572424
Francois Dorayeaace782017-06-21 16:37:242425 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442426 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572427 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572428
Fergal Dalya1d569972021-03-16 03:24:532429 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302430 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532431 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2432 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302433 }
[email protected]4e6419c2010-01-15 04:50:342434
Lukasz Anforowicz0de0f452020-12-02 19:57:152435 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572436}
2437
Aran Gilman37d11632019-10-08 23:07:152438void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2439 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162440 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012441 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162442
[email protected]d202a7c2012-01-04 07:53:472443 NavigationControllerImpl* source =
2444 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252445
avi2b177592014-12-10 02:08:022446 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012447 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252448
[email protected]474f8512013-05-31 22:31:162449 // We now have one entry, possibly with a new pending entry. Ensure that
2450 // adding the entries from source won't put us over the limit.
2451 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572452 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572453 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252454
Carlos IL4dea8902020-05-26 15:14:292455 // Insert the entries from source. Ignore any pending entry, since it has not
2456 // committed in source.
[email protected]474f8512013-05-31 22:31:162457 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172458 DCHECK_NE(max_source_index, -1);
2459 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572460
2461 // Ignore the source's current entry if merging with replacement.
2462 // TODO(davidben): This should preserve entries forward of the current
2463 // too. http://crbug.com/317872
2464 if (replace_entry && max_source_index > 0)
2465 max_source_index--;
2466
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572467 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252468
2469 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552470 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142471
Hayato Ito2c8c08d02021-06-23 03:38:432472 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252473}
2474
[email protected]79368982013-11-13 01:11:012475bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162476 // If there is no last committed entry, we cannot prune. Even if there is a
2477 // pending entry, it may not commit, leaving this WebContents blank, despite
2478 // possibly giving it new entries via CopyStateFromAndPrune.
2479 if (last_committed_entry_index_ == -1)
2480 return false;
[email protected]9350602e2013-02-26 23:27:442481
[email protected]474f8512013-05-31 22:31:162482 // We cannot prune if there is a pending entry at an existing entry index.
2483 // It may not commit, so we have to keep the last committed entry, and thus
2484 // there is no sensible place to keep the pending entry. It is ok to have
2485 // a new pending entry, which can optionally commit as a new navigation.
2486 if (pending_entry_index_ != -1)
2487 return false;
2488
[email protected]474f8512013-05-31 22:31:162489 return true;
2490}
2491
[email protected]79368982013-11-13 01:11:012492void NavigationControllerImpl::PruneAllButLastCommitted() {
2493 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162494
avi2b177592014-12-10 02:08:022495 DCHECK_EQ(0, last_committed_entry_index_);
2496 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442497
Hayato Ito2c8c08d02021-06-23 03:38:432498 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442499}
2500
[email protected]79368982013-11-13 01:11:012501void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162502 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012503 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262504
Nate Chapin9eb16be72022-09-23 22:54:312505 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2506
[email protected]474f8512013-05-31 22:31:162507 // Erase all entries but the last committed entry. There may still be a
2508 // new pending entry after this.
2509 entries_.erase(entries_.begin(),
2510 entries_.begin() + last_committed_entry_index_);
2511 entries_.erase(entries_.begin() + 1, entries_.end());
2512 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262513}
2514
Christian Dullweber1af31e62018-02-22 11:49:482515void NavigationControllerImpl::DeleteNavigationEntries(
2516 const DeletionPredicate& deletionPredicate) {
2517 // It is up to callers to check the invariants before calling this.
2518 CHECK(CanPruneAllButLastCommitted());
2519 std::vector<int> delete_indices;
2520 for (size_t i = 0; i < entries_.size(); i++) {
2521 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572522 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482523 delete_indices.push_back(i);
2524 }
2525 }
2526 if (delete_indices.empty())
2527 return;
2528
2529 if (delete_indices.size() == GetEntryCount() - 1U) {
2530 PruneAllButLastCommitted();
2531 } else {
2532 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382533 for (const auto& index : base::Reversed(delete_indices)) {
2534 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482535 }
Hayato Ito2c8c08d02021-06-23 03:38:432536 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482537 }
2538 delegate()->NotifyNavigationEntriesDeleted();
2539}
2540
Shivani Sharma883f5f32019-02-12 18:20:012541bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2542 auto* entry = GetEntryAtIndex(index);
2543 return entry && entry->should_skip_on_back_forward_ui();
2544}
2545
Carlos Caballero35ce710c2019-09-19 10:59:452546BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2547 return back_forward_cache_;
2548}
2549
William Liu055a3542023-04-02 17:21:192550NavigationEntryScreenshotCache*
2551NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
2552 CHECK_EQ(frame_tree_->type(), FrameTree::Type::kPrimary);
2553 if (!nav_entry_screenshot_cache_ && AreBackForwardTransitionsEnabled()) {
2554 nav_entry_screenshot_cache_ =
2555 std::make_unique<NavigationEntryScreenshotCache>(
2556 BrowserContextImpl::From(browser_context_)
2557 ->GetNavigationEntryScreenshotManager()
2558 ->GetSafeRef(),
2559 this);
2560 }
2561 return nav_entry_screenshot_cache_.get();
2562}
2563
clamy987a3752018-05-03 17:36:262564void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2565 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2566 // progress, since this will cause a use-after-free. (We only allow this
2567 // when the tab is being destroyed for shutdown, since it won't return to
2568 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032569 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262570
2571 if (was_failure && pending_entry_) {
2572 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2573 } else {
2574 failed_pending_entry_id_ = 0;
2575 }
2576
2577 if (pending_entry_) {
2578 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332579 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262580 pending_entry_index_ = -1;
2581 pending_entry_ = nullptr;
2582 }
arthursonzogni66f711c2019-10-08 14:40:362583
2584 // Ensure any refs to the current pending entry are ignored if they get
2585 // deleted, by clearing the set of known refs. All future pending entries will
2586 // only be affected by new refs.
2587 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262588}
2589
2590void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2591 if (pending_entry_)
2592 pending_entry_->set_ssl_error(error);
2593}
2594
Xiaohan Wang7f8052e02022-01-14 18:44:282595#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422596// static
2597bool NavigationControllerImpl::ValidateDataURLAsString(
2598 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2599 if (!data_url_as_string)
2600 return false;
2601
2602 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2603 return false;
2604
2605 // The number of characters that is enough for validating a data: URI.
2606 // From the GURL's POV, the only important part here is scheme, it doesn't
2607 // check the actual content. Thus we can take only the prefix of the url, to
2608 // avoid unneeded copying of a potentially long string.
2609 const size_t kDataUriPrefixMaxLen = 64;
2610 GURL data_url(
2611 std::string(data_url_as_string->front_as<char>(),
2612 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2613 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2614 return false;
2615
2616 return true;
2617}
2618#endif
2619
Shivani Sharma194877032019-03-07 17:52:472620void NavigationControllerImpl::NotifyUserActivation() {
2621 // When a user activation occurs, ensure that all adjacent entries for the
2622 // same document clear their skippable bit, so that the history manipulation
2623 // intervention does not apply to them.
shivanigithub99368382021-06-16 18:33:372624 if (base::FeatureList::IsEnabled(
2625 features::kDebugHistoryInterventionNoUserActivation)) {
2626 return;
2627 }
2628
Shivani Sharmac4cc8922019-04-18 03:11:172629 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472630}
2631
clamy987a3752018-05-03 17:36:262632bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2633 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332634 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2635 blink::LocalFrameToken initiator_frame_token,
2636 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262637 NavigationEntryImpl* entry =
2638 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2639 if (!entry)
2640 return false;
2641
2642 FrameNavigationEntry* frame_entry =
2643 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2644 if (!frame_entry)
2645 return false;
2646
Camille Lamy5193caa2018-10-12 11:59:422647 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572648 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232649 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332650 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2651 initiator_process_id);
clamyea99ea12018-05-28 13:54:232652
2653 if (!request)
2654 return false;
2655
arthursonzognif046d4a2019-12-12 19:08:102656 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412657
Rakina Zata Amni1c83b082023-02-08 01:09:002658 SCOPED_CRASH_KEY_STRING256(
2659 "Bug1400009", "req_url",
2660 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2661 SCOPED_CRASH_KEY_NUMBER(
2662 "Bug1400009", "nav_entry_si",
2663 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2664 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2665 frame_entry->site_instance()
2666 ? ((int)frame_entry->site_instance()->GetId())
2667 : -1);
2668 bool has_sig =
2669 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2670 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2671 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2672 has_sig ? (!!frame_tree_->GetRenderViewHost(
2673 frame_entry->site_instance()->group()))
2674 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052675 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2676 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232677
2678 return true;
clamy987a3752018-05-03 17:36:262679}
2680
Tsuyoshi Horo52fd08e2020-07-07 07:03:452681bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2682 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2683 if (!entry)
2684 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432685
2686 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2687 // We should never navigate to an existing initial NavigationEntry that is
2688 // the initial NavigationEntry for the initial empty document that hasn't
2689 // been overridden by the synchronous about:blank commit, to preserve
2690 // legacy behavior where trying to reload when the main frame is on the
2691 // initial empty document won't result in a navigation. See also
2692 // https://crbug.com/1277414.
2693 return false;
2694 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452695 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2696 if (!frame_entry)
2697 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142698 ReloadType reload_type = ReloadType::NORMAL;
2699 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452700 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142701 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452702 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432703 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332704 absl::nullopt /* initiator_frame_token */,
2705 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452706 if (!request)
2707 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052708 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452709 return true;
2710}
2711
clamy987a3752018-05-03 17:36:262712void NavigationControllerImpl::NavigateFromFrameProxy(
2713 RenderFrameHostImpl* render_frame_host,
2714 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022715 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452716 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072717 const absl::optional<url::Origin>& initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212718 const absl::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262719 bool is_renderer_initiated,
2720 SiteInstance* source_site_instance,
2721 const Referrer& referrer,
2722 ui::PageTransition page_transition,
2723 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252724 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262725 const std::string& method,
2726 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092727 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142728 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212729 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502730 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392731 const absl::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292732 blink::mojom::NavigationInitiatorActivationAndAdStatus
2733 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222734 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492735 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462736 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452737 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582738 bool is_container_initiated,
2739 absl::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582740 if (is_renderer_initiated)
2741 DCHECK(initiator_origin.has_value());
2742
clamy987a3752018-05-03 17:36:262743 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582744
Rakina Zata Amni2322f4f82022-01-24 13:24:242745 // Don't allow an entry replacement if there is no entry to replace.
2746 // http://crbug.com/457149
2747 if (GetEntryCount() == 0)
2748 should_replace_current_entry = false;
2749
clamy987a3752018-05-03 17:36:262750 // Create a NavigationEntry for the transfer, without making it the pending
2751 // entry. Subframe transfers should have a clone of the last committed entry
2752 // with a FrameNavigationEntry for the target frame. Main frame transfers
2753 // should have a new NavigationEntry.
2754 // TODO(creis): Make this unnecessary by creating (and validating) the params
2755 // directly, passing them to the destination RenderFrameHost. See
2756 // https://crbug.com/536906.
2757 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262758 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262759 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452760 DCHECK(GetLastCommittedEntry());
2761 entry = GetLastCommittedEntry()->Clone();
2762 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172763 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2764 // Renderer-initiated navigation that target a remote frame are currently
2765 // classified as browser-initiated when this one has already navigated.
2766 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372767 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2768 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2769 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2770 // same-document navigation), they will still be present in the
2771 // committed NavigationEntry that will be referenced to construct the new
2772 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262773 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082774 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582775 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072776 absl::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212777 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto22a27b142023-02-10 06:42:492778 blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482779 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori79d549d2021-02-18 12:59:542780 nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262781 } else {
2782 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172783 // If `node` is the outermost main frame, it rewrites a virtual url in order
2784 // to adjust the original input url if needed. For inner frames such as
2785 // fenced frames or subframes, they don't rewrite urls as the urls are not
2786 // input urls by users.
2787 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:322788 absl::optional<GURL> source_process_site_url = absl::nullopt;
2789 if (source_site_instance && source_site_instance->HasProcess()) {
2790 source_process_site_url =
2791 source_site_instance->GetProcess()->GetProcessLock().site_url();
2792 }
clamy987a3752018-05-03 17:36:262793 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212794 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322795 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212796 extra_headers, browser_context_, blob_url_loader_factory,
2797 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262798 entry->root_node()->frame_entry->set_source_site_instance(
2799 static_cast<SiteInstanceImpl*>(source_site_instance));
2800 entry->root_node()->frame_entry->set_method(method);
2801 }
clamy987a3752018-05-03 17:36:262802
Camille Lamy5193caa2018-10-12 11:59:422803 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452804 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262805 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422806 override_user_agent = true;
clamy987a3752018-05-03 17:36:262807 }
2808 // TODO(creis): Set user gesture and intent received timestamp on Android.
2809
2810 // We may not have successfully added the FrameNavigationEntry to |entry|
2811 // above (per https://crbug.com/608402), in which case we create it from
2812 // scratch. This works because we do not depend on |frame_entry| being inside
2813 // |entry| during NavigateToEntry. This will go away when we shortcut this
2814 // further in https://crbug.com/536906.
2815 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2816 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452817 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082818 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582819 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072820 absl::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212821 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto22a27b142023-02-10 06:42:492822 blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482823 nullptr /* subresource_web_bundle_navigation_info */,
Nate Chapin63db0d12022-01-20 22:03:302824 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572825 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262826 }
2827
Camille Lamy5193caa2018-10-12 11:59:422828 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022829 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452830 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292831 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212832 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422833 params.source_site_instance = source_site_instance;
2834 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2835 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032836 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422837 params.referrer = referrer;
2838 /* params.redirect_chain: skip */
2839 params.extra_headers = extra_headers;
2840 params.is_renderer_initiated = is_renderer_initiated;
2841 params.override_user_agent = UA_OVERRIDE_INHERIT;
2842 /* params.base_url_for_data_url: skip */
2843 /* params.virtual_url_for_data_url: skip */
2844 /* params.data_url_as_string: skip */
2845 params.post_data = post_body;
2846 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582847 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422848 /* params.frame_name: skip */
2849 // TODO(clamy): See if user gesture should be propagated to this function.
2850 params.has_user_gesture = false;
2851 params.should_clear_history_list = false;
2852 params.started_from_context_menu = false;
2853 /* params.navigation_ui_data: skip */
2854 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222855 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542856 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212857 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412858 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502859 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292860 params.initiator_activation_and_ad_status =
2861 initiator_activation_and_ad_status;
Camille Lamy5193caa2018-10-12 11:59:422862
2863 std::unique_ptr<NavigationRequest> request =
2864 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032865 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142866 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392867 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492868 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582869 is_unfenced_top_navigation, is_container_initiated,
2870 embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232871
2872 if (!request)
2873 return;
2874
Garrett Tanzerbb8db412022-09-27 21:59:462875 // Force the navigation to take place in a new browsing instance.
2876 // This is used by _unfencedTop in fenced frames to ensure that navigations
2877 // leaving the fenced context create a new browsing instance.
2878 if (force_new_browsing_instance) {
2879 request->coop_status().ForceBrowsingInstanceSwap();
2880 }
2881
Arthur Hemery948742762019-09-18 10:06:242882 // At this stage we are proceeding with this navigation. If this was renderer
2883 // initiated with user gesture, we need to make sure we clear up potential
2884 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2885 DiscardNonCommittedEntries();
2886
Lukasz Anforowicz9ee83c272020-12-01 20:14:052887 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262888}
2889
[email protected]d1198fd2012-08-13 22:50:192890void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252891 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212892 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192893 if (!session_storage_namespace)
2894 return;
2895
2896 // We can't overwrite an existing SessionStorage without violating spec.
2897 // Attempts to do so may give a tab access to another tab's session storage
2898 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152899 bool successful_insert =
2900 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252901 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052902 static_cast<SessionStorageNamespaceImpl*>(
2903 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302904 .second;
2905 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192906}
2907
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572908bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452909 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032910 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462911}
2912
Aran Gilman37d11632019-10-08 23:07:152913SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252914 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302915 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252916 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032917 DOMStorageContextWrapper* context_wrapper =
2918 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2919
2920 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252921 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032922 if (it != session_storage_namespace_map_.end()) {
2923 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152924 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2925 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472926
michaelnbacbcbd2016-02-09 00:32:032927 return it->second.get();
2928 }
2929
2930 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102931 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2932 SessionStorageNamespaceImpl::Create(context_wrapper);
2933 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2934 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252935 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102936 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302937
Daniel Murphy31bbb8b12018-02-07 21:44:102938 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302939}
2940
2941SessionStorageNamespace*
2942NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252943 return GetSessionStorageNamespace(
2944 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302945}
2946
2947const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572948NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302949 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552950}
[email protected]d202a7c2012-01-04 07:53:472951
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572952bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562953 return needs_reload_;
2954}
[email protected]a26023822011-12-29 00:23:552955
[email protected]46bb5e9c2013-10-03 22:16:472956void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412957 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2958}
2959
2960void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472961 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412962 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542963
2964 if (last_committed_entry_index_ != -1) {
2965 entries_[last_committed_entry_index_]->SetTransitionType(
2966 ui::PAGE_TRANSITION_RELOAD);
2967 }
[email protected]46bb5e9c2013-10-03 22:16:472968}
2969
[email protected]d202a7c2012-01-04 07:53:472970void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572971 DCHECK_LT(index, GetEntryCount());
2972 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312973 DiscardNonCommittedEntries();
2974
Nate Chapin9eb16be72022-09-23 22:54:312975 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:312976 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122977 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312978 last_committed_entry_index_--;
2979}
2980
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572981NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272982 // If there is no pending_entry_, there should be no pending_entry_index_.
2983 DCHECK(pending_entry_ || pending_entry_index_ == -1);
2984
2985 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:362986 // at that index. An exception is while a reload of a post commit error page
2987 // is ongoing; in that case pending entry will point to the entry replaced
2988 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:272989 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:362990 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
2991 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:272992
[email protected]022af742011-12-28 18:37:252993 return pending_entry_;
2994}
2995
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572996int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:272997 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:272998 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:552999 return pending_entry_index_;
3000}
3001
avi25764702015-06-23 15:43:373002void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573003 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363004 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313005 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003006 bool in_fenced_frame_tree,
3007 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313008 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3009 // set because:
3010 // 1) They don't influence the history of the outer page.
3011 // 2) They are always replace only navigation (there is always only one entry
3012 // in their history stack).
3013 // 3) Are not top level navigations and appear similar to iframes.
3014 // Navigations of the fenced frame might create a new NavigationEntry, which
3015 // will call this function. Non fenced frame navigations will never have
3016 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3017 // InsertOrReplaceEntry.
3018 DCHECK_EQ(in_fenced_frame_tree,
3019 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3020 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203021
avi5cad4912015-06-19 05:25:443022 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3023 // need to keep continuity with the pending entry, so copy the pending entry's
3024 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3025 // then the renderer navigated on its own, independent of the pending entry,
3026 // so don't copy anything.
3027 if (pending_entry_ && pending_entry_index_ == -1)
3028 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203029
Rakina Zata Amnia4e27222021-12-22 01:05:003030 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203031
creisee17e932015-07-17 17:56:223032 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453033 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103034 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573035 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363036 // If the new entry is a post-commit error page, we store the current last
3037 // committed entry to the side so that we can put it back when navigating
3038 // away from the error.
3039 if (was_post_commit_error) {
3040 DCHECK(!entry_replaced_by_post_commit_error_);
3041 entry_replaced_by_post_commit_error_ =
3042 std::move(entries_[last_committed_entry_index_]);
3043 }
dcheng36b6aec92015-12-26 06:16:363044 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223045 return;
3046 }
[email protected]765b35502008-08-21 00:51:203047
creis37979a62015-08-04 19:48:183048 // We shouldn't see replace == true when there's no committed entries.
3049 DCHECK(!replace);
3050
Michael Thiessen9b14d512019-09-23 21:19:473051 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203052
Shivani Sharmad8c8d652019-02-13 17:27:573053 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203054
dcheng36b6aec92015-12-26 06:16:363055 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203056 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293057}
3058
Shivani Sharmad8c8d652019-02-13 17:27:573059void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163060 if (entries_.size() < max_entry_count())
3061 return;
3062
3063 DCHECK_EQ(max_entry_count(), entries_.size());
3064 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573065 CHECK_EQ(pending_entry_index_, -1);
3066
3067 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423068 // Retrieve the oldest skippable entry.
3069 for (; index < GetEntryCount(); index++) {
3070 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3071 break;
Shivani Sharmad8c8d652019-02-13 17:27:573072 }
3073
3074 // If there is no skippable entry or if it is the last committed entry then
3075 // fall back to pruning the oldest entry. It is not safe to prune the last
3076 // committed entry.
3077 if (index == GetEntryCount() || index == last_committed_entry_index_)
3078 index = 0;
3079
3080 bool should_succeed = RemoveEntryAtIndex(index);
3081 DCHECK_EQ(true, should_succeed);
3082
3083 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253084}
3085
clamy3cb9bea92018-07-10 12:42:023086void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163087 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203088 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:133089 absl::optional<blink::scheduler::TaskAttributionId>
3090 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203091 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503092 TRACE_EVENT0("navigation",
3093 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273094 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023095 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363096 if (pending_entry_index_ != -1) {
3097 // The pending entry may not be in entries_ if a post-commit error page is
3098 // showing.
3099 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3100 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3101 }
Gyuyoung Kim107c2a02021-04-13 01:49:303102 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573103 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013104 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033105 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573106 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133107 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3108 // the same as the top level frame being navigated.
3109 if (root->current_frame_host() != initiator_rfh) {
3110 soft_navigation_heuristics_task_id = absl::nullopt;
3111 }
Arthur Sonzogni620cec62018-12-13 13:08:573112
[email protected]83c2e232011-10-07 21:36:463113 // If we were navigating to a slow-to-commit page, and the user performs
3114 // a session history navigation to the last committed page, RenderViewHost
3115 // will force the throbber to start, but WebKit will essentially ignore the
3116 // navigation, and won't send a message to stop the throbber. To prevent this
3117 // from happening, we drop the navigation here and stop the slow-to-commit
3118 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023119 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083120 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273121 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033122 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123123
[email protected]83c2e232011-10-07 21:36:463124 DiscardNonCommittedEntries();
3125 return;
3126 }
3127
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333128 absl::optional<blink::LocalFrameToken> initiator_frame_token;
3129 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3130 if (initiator_rfh) {
3131 initiator_frame_token = initiator_rfh->GetFrameToken();
3132 initiator_process_id = initiator_rfh->GetProcess()->GetID();
3133 DCHECK(initiator_frame_token);
3134 }
3135
creisce0ef3572017-01-26 17:53:083136 // Compare FrameNavigationEntries to see which frames in the tree need to be
3137 // navigated.
clamy3cb9bea92018-07-10 12:42:023138 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3139 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333140 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3141 initiator_process_id, soft_navigation_heuristics_task_id,
3142 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303143
3144 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573145 // We were unable to match any frames to navigate. This can happen if a
3146 // history navigation targets a subframe that no longer exists
3147 // (https://crbug.com/705550). In this case, we need to update the current
3148 // history entry to the pending one but keep the main document loaded. We
3149 // also need to ensure that observers are informed about the updated
3150 // current history entry (e.g., for greying out back/forward buttons), and
3151 // that renderer processes update their history offsets. The easiest way
3152 // to do all that is to schedule a "redundant" same-document navigation in
3153 // the main frame.
3154 //
3155 // Note that we don't want to remove this history entry, as it might still
3156 // be valid later, since a frame that it's targeting may be recreated.
3157 //
3158 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3159 // need to repeat history navigations until finding the one that works.
3160 // Consider changing this behavior to keep looking for the first valid
3161 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023162 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423163 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573164 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573165 ReloadType::NONE /* reload_type */,
3166 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433167 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333168 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023169 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573170 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023171 DiscardPendingEntry(false);
3172 return;
3173 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573174 same_document_loads.push_back(std::move(navigation_request));
3175
3176 // Sanity check that we never take this branch for any kinds of reloads,
3177 // as those should've queued a different-document load in the main frame.
3178 DCHECK(!is_forced_reload);
3179 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303180 }
3181
Nate Chapinbf682fa32022-09-26 22:41:203182 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163183 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203184 if (initiator_rfh && initiator_rfh->IsSandboxed(
3185 network::mojom::WebSandboxFlags::kTopNavigation)) {
3186 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3187 initiator_rfh, same_document_loads) &&
3188 DoesSandboxNavigationStayWithinSubtree(
3189 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503190 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163191 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203192 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3193 initiator_rfh,
3194 navigates_inside_tree
3195 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3196 : blink::mojom::WebFeature::
3197 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523198
3199 // If the navigation occurred outside the tree discard it because
3200 // the sandboxed frame didn't have permission to navigate outside
3201 // its tree. If it is possible that the navigation is both inside and
3202 // outside the frame tree and we discard it entirely because we don't
3203 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143204 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203205 // If a |navigation_api_key| was provided, this navigation originated from
3206 // the navigation API. Notify the renderer that the navigation was
3207 // cancelled so the navigation API can fire an error event and reject the
3208 // relevant promise.
3209 if (navigation_api_key) {
3210 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3211 *navigation_api_key,
3212 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3213 }
Dave Tapuska855c1e12019-08-23 20:45:523214 DiscardPendingEntry(false);
3215 return;
3216 }
Dave Tapuska8bfd84c2019-03-26 20:47:163217 }
3218
Nate Chapin6c43c022023-02-13 23:32:423219 // If it is possible that this traverse may involve a same-document navigation
3220 // in the initiator and there is a Navigation API key involved, then we may
3221 // need to notify the initiator if it fails. (The early returns above either
3222 // do not involve these cases or already notify the initiator.)
3223 // The event only needs to fire for the initiator, and only if the initiator
3224 // itself is performing a same-document navigation (because the event will not
3225 // fire if it navigates cross-document).
3226 if (navigation_api_key) {
3227 for (auto& item : same_document_loads) {
3228 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3229 item->set_pending_navigation_api_key(*navigation_api_key);
3230 break;
3231 }
3232 }
3233 }
3234
Carlos Caballero539a421c2020-07-06 10:25:573235 // BackForwardCache:
3236 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563237 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573238 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3239 DCHECK_EQ(reload_type, ReloadType::NONE);
3240 auto navigation_request = CreateNavigationRequestFromEntry(
3241 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3242 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333243 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3244 initiator_process_id);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053245 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573246
3247 return;
3248 }
3249
3250 // History navigation might try to reuse a specific BrowsingInstance, already
3251 // used by a page in the cache. To avoid having two different main frames that
3252 // live in the same BrowsingInstance, evict the all pages with this
3253 // BrowsingInstance from the cache.
3254 //
3255 // For example, take the following scenario:
3256 //
3257 // A1 = Some page on a.com
3258 // A2 = Some other page on a.com
3259 // B3 = An uncacheable page on b.com
3260 //
3261 // Then the following navigations occur:
3262 // A1->A2->B3->A1
3263 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3264 // take its place) and A1 will be created in the same BrowsingInstance (and
3265 // SiteInstance), as A2.
3266 //
3267 // If we didn't do anything, both A1 and A2 would remain alive in the same
3268 // BrowsingInstance/SiteInstance, which is unsupported by
3269 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3270 // A2 from the cache.
3271 if (pending_entry_->site_instance()) {
3272 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3273 pending_entry_->site_instance());
3274 }
3275
Rakina Zata Amnid605d462022-06-01 10:17:033276 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3277 pending_entry_ && pending_entry_->IsRestored());
3278 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3279 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3280 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3281 pending_entry_index_);
3282 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3283 last_committed_entry_index_);
3284 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3285 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3286 pending_entry_ && pending_entry_->IsInitialEntry());
3287 SCOPED_CRASH_KEY_BOOL(
3288 "nav_reentrancy", "pending_entry_initial2",
3289 pending_entry_ &&
3290 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3291 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3292 IsInitialNavigation());
3293 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3294 IsInitialBlankNavigation());
3295 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3296 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3297 (int)pending_reload_);
3298
clamy3cb9bea92018-07-10 12:42:023299 // This call does not support re-entrancy. See http://crbug.com/347742.
3300 CHECK(!in_navigate_to_pending_entry_);
3301 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303302
Rakina Zata Amnid605d462022-06-01 10:17:033303 // If the navigation-reentrancy is caused by calling
3304 // NavigateToExistingPendingEntry twice, this will note the previous call's
3305 // pending entry's ID.
3306 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3307 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3308
arthursonzogni66f711c2019-10-08 14:40:363309 // It is not possible to delete the pending NavigationEntry while navigating
3310 // to it. Grab a reference to delay potential deletion until the end of this
3311 // function.
3312 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3313
Nate Chapin154b14b2023-02-17 18:28:163314 // If there is a main-frame same-document history navigation, we may defer
3315 // the subframe history navigations in order to give JS in the main frame the
3316 // opportunity to cancel the entire traverse via the navigate event. In that
3317 // case, we need to stash the main frame request's navigation token on the
3318 // subframes, so they can look up the main frame request and defer themselves
3319 // until it completes.
3320 if (!same_document_loads.empty() &&
3321 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3322 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3323 // The token will only be returned in cases where deferring the navigation
3324 // is necessary.
3325 if (auto main_frame_same_document_token =
3326 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3327 for (auto& item : same_document_loads) {
3328 if (item.get() != main_frame_request) {
3329 item->set_main_frame_same_document_history_token(
3330 main_frame_same_document_token);
3331 }
3332 }
3333 for (auto& item : different_document_loads) {
3334 item->set_main_frame_same_document_history_token(
3335 main_frame_same_document_token);
3336 }
3337 }
3338 }
3339
creis4e2ecb72015-06-20 00:46:303340 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023341 for (auto& item : same_document_loads) {
3342 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053343 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303344 }
clamy3cb9bea92018-07-10 12:42:023345 for (auto& item : different_document_loads) {
3346 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053347 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303348 }
clamy3cb9bea92018-07-10 12:42:023349
3350 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303351}
3352
Alex Moshchuk3a4e77a2020-05-29 21:32:573353NavigationControllerImpl::HistoryNavigationAction
3354NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303355 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573356 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423357 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583358 // Only active and prerendered documents are allowed to navigate in their
3359 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423360 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013361 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583362 // - If the document is in pending deletion, the browser already committed
3363 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3364 // - If the document is in back-forward cache, it's not allowed to navigate
3365 // as it should remain frozen. Ignore the request and evict the document
3366 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423367 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583368 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423369 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113370 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3371 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423372 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113373 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423374 }
arthursonzogni03f76152019-02-12 10:35:203375
Alex Moshchuk3a4e77a2020-05-29 21:32:573376 // Reloads should result in a different-document load. Note that reloads may
3377 // also happen via the |needs_reload_| mechanism where the reload_type is
3378 // NONE, so detect this by comparing whether we're going to the same
3379 // entry that we're currently on. Similarly to above, only main frames
3380 // should reach this. Note that subframes support reloads, but that's done
3381 // via a different path that doesn't involve FindFramesToNavigate (see
3382 // RenderFrameHost::Reload()).
3383 if (reload_type != ReloadType::NONE ||
3384 pending_entry_index_ == last_committed_entry_index_) {
3385 DCHECK(frame->IsMainFrame());
3386 return HistoryNavigationAction::kDifferentDocument;
3387 }
3388
Alex Moshchuk47d1a4bd2020-06-01 22:15:343389 // If there is no new FrameNavigationEntry for the frame, ignore the
3390 // load. For example, this may happen when going back to an entry before a
3391 // frame was created. Suppose we commit a same-document navigation that also
3392 // results in adding a new subframe somewhere in the tree. If we go back,
3393 // the new subframe will be missing a FrameNavigationEntry in the previous
3394 // NavigationEntry, but we shouldn't delete or change what's loaded in
3395 // it.
3396 //
Alex Moshchuke65c39272020-06-03 17:55:373397 // Note that in this case, there is no need to keep looking for navigations
3398 // in subframes, which would be missing FrameNavigationEntries as well.
3399 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343400 // It's important to check this before checking |old_item| below, since both
3401 // might be null, and in that case we still shouldn't change what's loaded in
3402 // this frame. Note that scheduling any loads assumes that |new_item| is
3403 // non-null. See https://crbug.com/1088354.
3404 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3405 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373406 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343407
Charlie Reisa474fb62022-03-17 02:31:363408 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3409 // which history item it is currently on, since this may be different than the
3410 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3411 // (e.g., if a history navigation is targeting multiple frames and only some
3412 // have committed so far).
creis4e2ecb72015-06-20 00:46:303413 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363414 frame->current_frame_host()->last_committed_frame_entry();
3415 if (!old_item) {
3416 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3417 // fall back to the last committed NavigationEntry's record for this frame.
3418 // This may happen in cases like the initial state of the RenderFrameHost.
3419 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3420 // accurate FrameNavigationEntry and eliminate this case.
3421 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3422 }
3423 // If neither approach finds a FrameNavigationEntry, schedule a
3424 // different-document load.
3425 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573426 if (!old_item)
3427 return HistoryNavigationAction::kDifferentDocument;
3428
Alex Moshchuk3a4e77a2020-05-29 21:32:573429 // If the new item is not in the same SiteInstance, schedule a
3430 // different-document load. Newly restored items may not have a SiteInstance
3431 // yet, in which case it will be assigned on first commit.
3432 if (new_item->site_instance() &&
3433 new_item->site_instance() != old_item->site_instance())
3434 return HistoryNavigationAction::kDifferentDocument;
3435
3436 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313437 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3438 // that we do this even if the history navigation would not be modifying this
3439 // frame were it live.
3440 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573441 return HistoryNavigationAction::kDifferentDocument;
3442
3443 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313444 // Starting a navigation after a crash early-promotes the speculative
3445 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3446 // committed yet, so we can not possibly perform a same-document history
3447 // navigation. The frame would need to be reloaded with a cross-document
3448 // navigation.
3449 if (!frame->current_frame_host()->has_committed_any_navigation())
3450 return HistoryNavigationAction::kDifferentDocument;
3451
creis54131692016-08-12 18:32:253452 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493453 // sequence number but different item sequence number.
3454 if (new_item->document_sequence_number() ==
3455 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573456 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493457 }
avib48cb312016-05-05 21:35:003458
Alex Moshchuk3a4e77a2020-05-29 21:32:573459 // Otherwise, if both item and document sequence numbers differ, this
3460 // should be a different document load.
3461 return HistoryNavigationAction::kDifferentDocument;
3462 }
3463
3464 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373465 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573466 DCHECK_EQ(new_item->document_sequence_number(),
3467 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373468 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573469}
3470
3471void NavigationControllerImpl::FindFramesToNavigate(
3472 FrameTreeNode* frame,
3473 ReloadType reload_type,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333474 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
3475 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133476 absl::optional<blink::scheduler::TaskAttributionId>
3477 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573478 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3479 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3480 DCHECK(pending_entry_);
3481 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3482
3483 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3484
3485 if (action == HistoryNavigationAction::kSameDocument) {
3486 std::unique_ptr<NavigationRequest> navigation_request =
3487 CreateNavigationRequestFromEntry(
3488 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133489 /*is_same_document_history_load=*/true,
3490 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333491 initiator_frame_token, initiator_process_id,
3492 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573493 if (navigation_request) {
3494 // Only add the request if was properly created. It's possible for the
3495 // creation to fail in certain cases, e.g. when the URL is invalid.
3496 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303497 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573498 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473499 std::unique_ptr<NavigationRequest> navigation_request =
3500 CreateNavigationRequestFromEntry(
3501 frame, pending_entry_, new_item, reload_type,
3502 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433503 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333504 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473505 if (navigation_request) {
3506 // Only add the request if was properly created. It's possible for the
3507 // creation to fail in certain cases, e.g. when the URL is invalid.
3508 different_document_loads->push_back(std::move(navigation_request));
3509 }
3510 // For a different document, the subframes will be destroyed, so there's
3511 // no need to consider them.
3512 return;
Alex Moshchuke65c39272020-06-03 17:55:373513 } else if (action == HistoryNavigationAction::kStopLooking) {
3514 return;
creis4e2ecb72015-06-20 00:46:303515 }
3516
Yoav Weiss8c573952022-11-17 17:35:133517 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3518 // we currently only support soft navigation heuristics for the top level
3519 // frame.
creis4e2ecb72015-06-20 00:46:303520 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333521 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3522 initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133523 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
Nate Chapin45f620582021-09-30 17:45:433524 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303525 }
3526}
3527
Harkiran Bolariaba823e42021-05-21 18:30:363528base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243529 const LoadURLParams& params) {
3530 // Find the appropriate FrameTreeNode.
3531 FrameTreeNode* node = nullptr;
3532 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3533 !params.frame_name.empty()) {
3534 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033535 ? frame_tree_->FindByID(params.frame_tree_node_id)
3536 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503537 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243538 }
3539
3540 // If no FrameTreeNode was specified, navigate the main frame.
3541 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033542 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243543
Camille Lamy5193caa2018-10-12 11:59:423544 // Compute overrides to the LoadURLParams for |override_user_agent|,
3545 // |should_replace_current_entry| and |has_user_gesture| that will be used
3546 // both in the creation of the NavigationEntry and the NavigationRequest.
3547 // Ideally, the LoadURLParams themselves would be updated, but since they are
3548 // passed as a const reference, this is not possible.
3549 // TODO(clamy): When we only create a NavigationRequest, move this to
3550 // CreateNavigationRequestFromLoadURLParams.
3551 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3552 GetLastCommittedEntry());
3553
Rakina Zata Amnie2d31312022-11-18 03:38:453554 // An entry replacement must happen if the current browsing context should
3555 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333556 bool should_replace_current_entry =
3557 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453558 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423559
clamy21718cc22018-06-13 13:34:243560 // Javascript URLs should not create NavigationEntries. All other navigations
3561 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243562 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373563 std::unique_ptr<NavigationEntryImpl> entry =
3564 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3565 should_replace_current_entry,
3566 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243567 DiscardPendingEntry(false);
3568 SetPendingEntry(std::move(entry));
3569 }
3570
Tim Judkins59548192023-05-17 17:51:203571 // Renderer-debug URLs are sent to the current renderer process immediately
3572 // for processing and don't need to create a NavigationRequest. Note: this
3573 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243574 // renderer-debug URLs.
3575 // Note: we intentionally leave the pending entry in place for renderer debug
3576 // URLs, unlike the cases below where we clear it if the navigation doesn't
3577 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303578 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483579 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3580 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153581 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203582 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483583 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363584 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483585 }
3586
clamy21718cc22018-06-13 13:34:243587 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363588 return nullptr;
clamy21718cc22018-06-13 13:34:243589 }
3590
Antonio Sartori78a749f2020-11-30 12:03:393591 DCHECK(pending_entry_);
3592
clamy21718cc22018-06-13 13:34:243593 // Convert navigations to the current URL to a reload.
3594 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3595 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3596 // DevTools sometimes issues navigations to main frames that they do not
3597 // expect to see treated as reload, and it only works because they pass a
3598 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3599 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543600 ReloadType reload_type = params.reload_type;
3601 if (reload_type == ReloadType::NONE &&
3602 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043603 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243604 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243605 params.load_type ==
3606 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543607 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243608 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473609 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393610
3611 // If this is a reload of an existing FrameNavigationEntry and we had a
3612 // policy container for it, then we should copy it into the pending entry,
3613 // so that it is copied to the navigation request in
3614 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453615 FrameNavigationEntry* previous_frame_entry =
3616 GetLastCommittedEntry()->GetFrameEntry(node);
3617 if (previous_frame_entry &&
3618 previous_frame_entry->policy_container_policies()) {
3619 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3620 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393621 }
3622 }
3623
3624 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173625 // document, then we should copy the document polices from RenderFrameHost's
3626 // PolicyContainerHost. The NavigationRequest will create a new
3627 // PolicyContainerHost with the document policies from the |pending_entry_|,
3628 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3629 // the navigation. This way, we ensure that we keep enforcing the right
3630 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453631 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393632 if (node->current_frame_host() &&
3633 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193634 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163635 node->current_frame_host()
3636 ->policy_container_host()
3637 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233638 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393639 }
clamy21718cc22018-06-13 13:34:243640 }
3641
3642 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263643 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243644
Tsuyoshi Horo167ca6432022-03-09 05:16:393645 // This will be used to set the Navigation Timing API navigationStart
3646 // parameter for browser navigations in new tabs (intents, tabs opened through
3647 // "Open link in new tab"). If the navigation must wait on the current
3648 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3649 // will be updated when the BeforeUnload ack is received.
3650 const auto navigation_start_time = base::TimeTicks::Now();
3651
Camille Lamy5193caa2018-10-12 11:59:423652 std::unique_ptr<NavigationRequest> request =
3653 CreateNavigationRequestFromLoadParams(
3654 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143655 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393656 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3657 navigation_start_time);
clamy21718cc22018-06-13 13:34:243658
3659 // If the navigation couldn't start, return immediately and discard the
3660 // pending NavigationEntry.
3661 if (!request) {
3662 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363663 return nullptr;
clamy21718cc22018-06-13 13:34:243664 }
3665
Camille Lamy5193caa2018-10-12 11:59:423666#if DCHECK_IS_ON()
3667 // Safety check that NavigationRequest and NavigationEntry match.
3668 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3669#endif
3670
clamy21718cc22018-06-13 13:34:243671 // This call does not support re-entrancy. See http://crbug.com/347742.
3672 CHECK(!in_navigate_to_pending_entry_);
3673 in_navigate_to_pending_entry_ = true;
3674
arthursonzogni66f711c2019-10-08 14:40:363675 // It is not possible to delete the pending NavigationEntry while navigating
3676 // to it. Grab a reference to delay potential deletion until the end of this
3677 // function.
3678 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3679
Harkiran Bolariaba823e42021-05-21 18:30:363680 base::WeakPtr<NavigationHandle> created_navigation_handle(
3681 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053682 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243683
3684 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363685 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243686}
3687
clamyea99ea12018-05-28 13:54:233688void NavigationControllerImpl::HandleRendererDebugURL(
3689 FrameTreeNode* frame_tree_node,
3690 const GURL& url) {
3691 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243692 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3693 // the renderer process is not live, unless it is the initial navigation
3694 // of the tab.
clamyea99ea12018-05-28 13:54:233695 if (!IsInitialNavigation()) {
3696 DiscardNonCommittedEntries();
3697 return;
3698 }
Fergal Dalyecd3b0202020-06-25 01:57:373699 // The current frame is always a main frame. If IsInitialNavigation() is
3700 // true then there have been no navigations and any frames of this tab must
3701 // be in the same renderer process. If that has crashed then the only frame
3702 // that can be revived is the main frame.
3703 frame_tree_node->render_manager()
3704 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233705 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223706
3707 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3708 // notification, so set is loading to true here to properly surface it when
3709 // the renderer process is done handling the URL.
3710 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3711 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223712 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223713 }
clamyea99ea12018-05-28 13:54:233714 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3715}
3716
clamy21718cc22018-06-13 13:34:243717std::unique_ptr<NavigationEntryImpl>
3718NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3719 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423720 const LoadURLParams& params,
3721 bool override_user_agent,
3722 bool should_replace_current_entry,
3723 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393724 // Browser initiated navigations might not have a blob_url_loader_factory set
3725 // in params even if the navigation is to a blob URL. If that happens, lookup
3726 // the correct url loader factory to use here.
3727 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483728 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473729 // Resolve the blob URL in the storage partition associated with the target
3730 // frame. This is the storage partition the URL will be loaded in, and only
3731 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393732 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473733 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393734 }
3735
clamy21718cc22018-06-13 13:34:243736 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443737 // extra_headers in params are \n separated; navigation entries want \r\n.
3738 std::string extra_headers_crlf;
3739 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243740
3741 // For subframes, create a pending entry with a corresponding frame entry.
3742 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453743 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243744 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083745 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243746 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073747 params.url, absl::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213748 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3749 "GET", -1, blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:483750 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori78a749f2020-11-30 12:03:393751 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163752 // a conversion of a new navigation into a reload, we will set the right
3753 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193754 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243755 } else {
3756 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173757 // If `node` is the outermost main frame, it rewrites a virtual url in order
3758 // to adjust the original input url if needed. For inner frames such as
3759 // fenced frames or subframes, they don't rewrite urls as the urls are not
3760 // input urls by users.
3761 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323762 scoped_refptr<SiteInstance> source_site_instance =
3763 params.source_site_instance;
3764 absl::optional<GURL> source_process_site_url = absl::nullopt;
3765 if (source_site_instance && source_site_instance->HasProcess()) {
3766 source_process_site_url =
3767 source_site_instance->GetProcess()->GetProcessLock().site_url();
3768 }
clamy21718cc22018-06-13 13:34:243769 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063770 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323771 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213772 params.transition_type, params.is_renderer_initiated,
3773 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3774 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243775 entry->set_source_site_instance(
3776 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3777 entry->SetRedirectChain(params.redirect_chain);
3778 }
3779
3780 // Set the FTN ID (only used in non-site-per-process, for tests).
3781 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243782 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423783 entry->SetIsOverridingUserAgent(override_user_agent);
3784 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543785 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243786
clamy21718cc22018-06-13 13:34:243787 switch (params.load_type) {
3788 case LOAD_TYPE_DEFAULT:
3789 break;
3790 case LOAD_TYPE_HTTP_POST:
3791 entry->SetHasPostData(true);
3792 entry->SetPostData(params.post_data);
3793 break;
3794 case LOAD_TYPE_DATA:
3795 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3796 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283797#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243798 entry->SetDataURLAsString(params.data_url_as_string);
3799#endif
3800 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3801 break;
clamy21718cc22018-06-13 13:34:243802 }
3803
3804 // TODO(clamy): NavigationEntry is meant for information that will be kept
3805 // after the navigation ended and therefore is not appropriate for
3806 // started_from_context_menu. Move started_from_context_menu to
3807 // NavigationUIData.
3808 entry->set_started_from_context_menu(params.started_from_context_menu);
3809
3810 return entry;
3811}
3812
clamyea99ea12018-05-28 13:54:233813std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423814NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3815 FrameTreeNode* node,
3816 const LoadURLParams& params,
3817 bool override_user_agent,
3818 bool should_replace_current_entry,
3819 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143820 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423821 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573822 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393823 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223824 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493825 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453826 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583827 bool is_container_initiated,
3828 absl::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573829 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283830 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533831 // All renderer-initiated navigations must have an initiator_origin.
3832 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513833
Camille Lamy5193caa2018-10-12 11:59:423834 GURL url_to_load;
3835 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323836
Camille Lamy2baa8022018-10-19 16:43:173837 // For main frames, rewrite the URL if necessary and compute the virtual URL
3838 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263839 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423840 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173841 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423842 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423843
Camille Lamy2baa8022018-10-19 16:43:173844 // For DATA loads, override the virtual URL.
3845 if (params.load_type == LOAD_TYPE_DATA)
3846 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423847
Camille Lamy2baa8022018-10-19 16:43:173848 if (virtual_url.is_empty())
3849 virtual_url = url_to_load;
3850
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573851 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283852
Aran Gilman249eb122019-12-02 23:32:463853 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3854 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3855 // return different results, leading to a different URL in the
3856 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3857 // pending NavigationEntry, as we'll only make one call to
3858 // RewriteUrlForNavigation.
3859 VLOG_IF(1, (url_to_load != frame_entry->url()))
3860 << "NavigationRequest and FrameEntry have different URLs: "
3861 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283862
Camille Lamy2baa8022018-10-19 16:43:173863 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423864 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173865 // NavigationRequest.
3866 } else {
3867 url_to_load = params.url;
3868 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243869 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173870 }
Camille Lamy5193caa2018-10-12 11:59:423871
Ehsan Karamad44fc72112019-02-26 18:15:473872 if (node->render_manager()->is_attaching_inner_delegate()) {
3873 // Avoid starting any new navigations since this node is now preparing for
3874 // attaching an inner delegate.
3875 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203876 }
Camille Lamy5193caa2018-10-12 11:59:423877
Ian Vollick1c6dd3e2022-04-13 02:06:263878 if (!IsValidURLForNavigation(node->IsOutermostMainFrame(), virtual_url,
3879 url_to_load))
Camille Lamy5193caa2018-10-12 11:59:423880 return nullptr;
3881
danakjd83d706d2020-11-25 22:11:123882 // Look for a pending commit that is to another document in this
3883 // FrameTreeNode. If one exists, then the last committed URL will not be the
3884 // current URL by the time this navigation commits.
3885 bool has_pending_cross_document_commit =
3886 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213887 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123888
Minggang Wangb9f3fa92021-07-01 15:30:313889 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493890 /*old_url=*/node->current_url(),
3891 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3892 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133893 /*is_same_document_history_load=*/false,
3894 is_embedder_initiated_fenced_frame_navigation,
3895 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423896
3897 // Create the NavigationParams based on |params|.
3898
Hiroki Nakagawa4ed61282021-06-18 05:37:233899 bool is_view_source_mode = entry->IsViewSourceMode();
3900 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293901
Antonio Sartori6984c742021-08-26 08:03:413902 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:293903
Hiroki Nakagawa4ed61282021-06-18 05:37:233904 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293905 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253906 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293907
Minggang Wangb9f3fa92021-07-01 15:30:313908 blink::mojom::CommonNavigationParamsPtr common_params =
3909 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:213910 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513911 blink::mojom::Referrer::New(params.referrer.url,
3912 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213913 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513914 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393915 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513916 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143917 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413918 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273919 false /* has_text_fragment_token */,
3920 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3921 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513922 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:053923 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423924
Minggang Wangb9f3fa92021-07-01 15:30:313925 blink::mojom::CommitNavigationParamsPtr commit_params =
3926 blink::mojom::CommitNavigationParams::New(
Rakina Zata Amnic7367852022-11-07 17:10:403927 absl::nullopt,
Ari Chivukula43d2cf82023-01-24 03:16:073928 // The correct storage key and session storage key will be computed
3929 // before committing the navigation.
3930 blink::StorageKey(), blink::StorageKey(), override_user_agent,
3931 params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323932 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503933 std::vector<net::RedirectInfo>(), params.post_content_type,
3934 common_params->url, common_params->method,
3935 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313936 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133937 entry->GetSubframeUniqueNames(node),
3938 /*intended_as_new_entry=*/true,
3939 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143940 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3941 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:133942 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313943 params.should_clear_history_list,
3944 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223945 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:133946 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:513947 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283948#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:133949 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143950#endif
Yoav Weiss8c573952022-11-17 17:35:133951 /*is_browser_initiated=*/!params.is_renderer_initiated,
Yoav Weiss8c573952022-11-17 17:35:133952 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:073953 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133954 /*force_enabled_origin_trials=*/std::vector<std::string>(),
3955 /*origin_agent_cluster=*/false,
3956 /*origin_agent_cluster_left_as_default=*/true,
3957 /*enabled_client_hints=*/
3958 std::vector<network::mojom::WebClientHintsType>(),
3959 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
3960 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:013961 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:133962 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:583963 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:133964 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:133965 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:283966 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:133967 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:443968 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:423969 network::mojom::NavigationDeliveryType::kDefault,
Yoav Weiss8c573952022-11-17 17:35:133970 /*view_transition_state=*/absl::nullopt,
sbinglera07ae732022-12-02 20:49:053971 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
3972 /*modified_runtime_features=*/
Garrett Tanzer29de7112022-12-06 21:26:323973 base::flat_map<::blink::mojom::RuntimeFeatureState, bool>(),
Yuzu Saijo29f96ca92022-12-08 04:54:123974 /*fenced_frame_properties=*/absl::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:053975 /*not_restored_reasons=*/nullptr,
3976 /*load_with_storage_access=*/false);
Xiaohan Wang7f8052e02022-01-14 18:44:283977#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423978 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143979 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423980 }
3981#endif
3982
Lucas Furukawa Gadania9c45682019-07-31 22:05:143983 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:073984 commit_params->navigation_timing->system_entropy_at_navigation_start =
3985 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
3986 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:423987
Camille Lamy5193caa2018-10-12 11:59:423988 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3989 std::string extra_headers_crlf;
3990 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:093991
Alex Moshchuk9321e6a2022-12-07 21:58:313992 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143993 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:083994 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:093995 params.initiator_frame_token, params.initiator_process_id,
3996 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:213997 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:293998 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:453999 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584000 is_container_initiated, embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:094001 navigation_request->set_from_download_cross_origin_redirect(
4002 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554003 navigation_request->set_force_new_browsing_instance(
4004 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:094005 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424006}
4007
4008std::unique_ptr<NavigationRequest>
4009NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234010 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574011 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234012 FrameNavigationEntry* frame_entry,
4013 ReloadType reload_type,
4014 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434015 bool is_history_navigation_in_new_child_frame,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334016 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
4017 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:134018 absl::optional<blink::scheduler::TaskAttributionId>
4019 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344020 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234021 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434022 // We should never navigate to an existing initial NavigationEntry that is the
4023 // initial NavigationEntry for the initial empty document that hasn't been
4024 // overridden by the synchronous about:blank commit, to preserve previous
4025 // behavior where trying to reload when the main frame is on the initial empty
4026 // document won't result in a navigation.
4027 // See also https://crbug.com/1277414.
4028 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324029
clamyea99ea12018-05-28 13:54:234030 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:014031 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574032 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:234033 // We may have been redirected when navigating to the current URL.
4034 // Use the URL the user originally intended to visit as signaled by the
4035 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:014036 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574037 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:234038 dest_referrer = Referrer();
clamyea99ea12018-05-28 13:54:234039 }
4040
Ehsan Karamad44fc72112019-02-26 18:15:474041 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4042 // Avoid starting any new navigations since this node is now preparing for
4043 // attaching an inner delegate.
4044 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204045 }
4046
Ian Vollick1c6dd3e2022-04-13 02:06:264047 if (!IsValidURLForNavigation(frame_tree_node->IsOutermostMainFrame(),
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574048 entry->GetVirtualURL(), dest_url)) {
clamyea99ea12018-05-28 13:54:234049 return nullptr;
4050 }
4051
clamyea99ea12018-05-28 13:54:234052 // This will be used to set the Navigation Timing API navigationStart
4053 // parameter for browser navigations in new tabs (intents, tabs opened through
4054 // "Open link in new tab"). If the navigation must wait on the current
4055 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4056 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074057
clamyea99ea12018-05-28 13:54:234058 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074059 const auto navigation_start_system_entropy =
4060 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4061 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234062
danakjd83d706d2020-11-25 22:11:124063 // Look for a pending commit that is to another document in this
4064 // FrameTreeNode. If one exists, then the last committed URL will not be the
4065 // current URL by the time this navigation commits.
4066 bool has_pending_cross_document_commit =
4067 frame_tree_node->render_manager()
4068 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494069 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214070 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124071
Minggang Wangb9f3fa92021-07-01 15:30:314072 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124073 /*old_url=*/frame_tree_node->current_url(),
4074 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:494075 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494076 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134077 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494078 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424079
4080 // A form submission may happen here if the navigation is a
4081 // back/forward/reload navigation that does a form resubmission.
4082 scoped_refptr<network::ResourceRequestBody> request_body;
4083 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:504084 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
4085 // entry. This way, it could be directly retrieved here. Right now, it is only
4086 // partially recovered when request.method == "POST" and request.body exists.
4087 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424088 if (frame_entry->method() == "POST") {
4089 request_body = frame_entry->GetPostData(&post_content_type);
4090 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304091 post_content_type = std::string(
4092 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504093 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424094 }
4095
4096 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314097 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514098 entry->ConstructCommonNavigationParams(
4099 *frame_entry, request_body, dest_url,
4100 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384101 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534102 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514103 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554104 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424105
4106 // TODO(clamy): |intended_as_new_entry| below should always be false once
4107 // Reload no longer leads to this being called for a pending NavigationEntry
4108 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314109 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144110 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404111 *frame_entry, common_params->url, common_params->method,
4112 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144113 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534114 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484115 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134116 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074117 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144118 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074119 commit_params->navigation_timing->system_entropy_at_navigation_start =
4120 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4121 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Camille Lamy5193caa2018-10-12 11:59:424122
W. James MacLeanb7d6092682022-10-05 15:23:264123 if (common_params->url.IsAboutSrcdoc()) {
4124 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4125 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594126 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264127 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334128 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314129 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144130 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434131 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334132 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4133 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
4134 absl::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294135 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4136 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474137 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234138}
4139
[email protected]d202a7c2012-01-04 07:53:474140void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214141 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274142 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404143
Takashi Toyoshimaea534ef22021-07-21 03:27:594144 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404145 // location bar will have up-to-date information about the security style
4146 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134147 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404148
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374149 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574150 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:464151
[email protected]b0f724c2013-09-05 04:21:134152 // TODO(avi): Remove. http://crbug.com/170921
4153 NotificationDetails notification_details =
4154 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154155 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4156 Source<NavigationController>(this),
4157 notification_details);
initial.commit09911bf2008-07-26 23:55:294158}
4159
initial.commit09911bf2008-07-26 23:55:294160// static
[email protected]d202a7c2012-01-04 07:53:474161size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234162 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154163 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214164 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234165}
4166
[email protected]d202a7c2012-01-04 07:53:474167void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224168 if (is_active && needs_reload_)
4169 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294170}
4171
[email protected]d202a7c2012-01-04 07:53:474172void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034173 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4174 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294175 if (!needs_reload_)
4176 return;
4177
Bo Liucdfa4b12018-11-06 00:21:444178 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4179 needs_reload_type_);
4180
initial.commit09911bf2008-07-26 23:55:294181 // Calling Reload() results in ignoring state, and not loading.
4182 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4183 // cached state.
avicc872d7242015-08-19 21:26:344184 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134185 NavigateToExistingPendingEntry(
4186 ReloadType::NONE,
4187 /*initiator_rfh=*/nullptr,
4188 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4189 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454190 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434191 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274192 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344193 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134194 NavigateToExistingPendingEntry(
4195 ReloadType::NONE,
4196 /*initiator_rfh=*/nullptr,
4197 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4198 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344199 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434200 // We should never navigate to an existing initial NavigationEntry that is
4201 // the initial NavigationEntry for the initial empty document that hasn't
4202 // been overridden by the synchronous about:blank commit, to preserve
4203 // legacy behavior where trying to reload when the main frame is on the
4204 // initial empty document won't result in a navigation. See also
4205 // https://crbug.com/1277414. If there is something to reload, the
4206 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4207 // it here.
avicc872d7242015-08-19 21:26:344208 needs_reload_ = false;
4209 }
initial.commit09911bf2008-07-26 23:55:294210}
4211
Kevin McNeeccca6172021-10-19 17:11:144212base::WeakPtr<NavigationHandle>
4213NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364214 RenderFrameHost* render_frame_host,
4215 const GURL& url,
4216 const std::string& error_page_html,
4217 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134218 RenderFrameHostImpl* rfhi =
4219 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584220
4221 // Only active documents can load post-commit error pages:
4222 // - If the document is in pending deletion, the browser already committed to
4223 // destroying this RenderFrameHost so ignore loading the error page.
4224 // - If the document is in back-forward cache, it's not allowed to navigate as
4225 // it should remain frozen. Ignore the request and evict the document from
4226 // back-forward cache.
4227 // - If the document is prerendering, it can navigate but when loading error
4228 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114229 if (rfhi->IsInactiveAndDisallowActivation(
4230 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144231 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114232 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584233
Rakina Zata Amni919b7922020-12-11 09:03:134234 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414235
Minggang Wangb9f3fa92021-07-01 15:30:314236 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434237 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594238 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4239 // the frame actually committed (e.g. iframe with "src" set to a
4240 // slow-responding URL). We should rewrite the URL to about:blank in this
4241 // case, as the renderer will only think a page is an error page if it has a
4242 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134243 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314244 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434245 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334246 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414247
Mike Jacksone2aa7af2023-05-17 06:45:074248 commit_params->navigation_timing->system_entropy_at_navigation_start =
4249 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4250 node, blink::mojom::SystemEntropy::kNormal);
4251
arthursonzogni70ac7302020-05-28 08:49:054252 // Error pages have a fully permissive FramePolicy.
4253 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4254 // error pages.
4255 commit_params->frame_policy = blink::FramePolicy();
4256
John Delaney131ad362019-08-08 21:57:414257 std::unique_ptr<NavigationRequest> navigation_request =
4258 NavigationRequest::CreateBrowserInitiated(
4259 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094260 false /* was_opener_suppressed */, "" /* extra_headers */,
4261 nullptr /* frame_entry */, nullptr /* entry */,
4262 false /* is_form_submission */, nullptr /* navigation_ui_data */,
4263 absl::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364264 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414265 navigation_request->set_net_error(error);
Charlie Reis09952ee2022-12-08 16:35:074266 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414267 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144268
4269 // Calling BeginNavigation may destroy the NavigationRequest.
4270 base::WeakPtr<NavigationRequest> created_navigation_request(
4271 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414272 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144273 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414274}
4275
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574276void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214277 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094278 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154279 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144280 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294281}
4282
[email protected]d202a7c2012-01-04 07:53:474283void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364284 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474285 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4286 // represent a no-committed-entry state.
4287 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364288 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474289 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4290 // if `entries_` contains pre-existing entries from the NavigationController
4291 // before restore, which would not be removed and will be at the front of the
4292 // entries list, causing the index to be off by the amount of pre-existing
4293 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294294 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294295}
[email protected]765b35502008-08-21 00:51:204296
arthursonzogni69a6a1b2019-09-17 09:23:004297void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004298 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4299}
4300
4301void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4302 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474303 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104304 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4305 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294306 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474307 return;
Michael Thiessenc5676d22019-09-25 22:32:104308 }
avi45a72532015-04-07 21:01:454309 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314310
4311 if (!delegate_)
4312 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374313 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484314}
4315
avi7c6f35e2015-05-08 17:52:384316int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4317 int nav_entry_id) const {
4318 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4319 if (entries_[i]->GetUniqueID() == nav_entry_id)
4320 return i;
4321 }
4322 return -1;
4323}
4324
[email protected]d202a7c2012-01-04 07:53:474325void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574326 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254327 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574328 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574329 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4330 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254331 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374332 // Normally, cloning a NavigationEntryImpl results in sharing
4333 // FrameNavigationEntries between the original and the clone. However, when
4334 // cloning from a different NavigationControllerImpl, we want to fork the
4335 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374336 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574337 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254338 }
Rakina Zata Amnie2d31312022-11-18 03:38:454339 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274340 DCHECK(pending_entry_index_ == -1 ||
4341 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254342}
[email protected]c5b88d82012-10-06 17:03:334343
4344void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184345 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334346 get_timestamp_callback_ = get_timestamp_callback;
4347}
[email protected]8ff00d72012-10-23 19:12:214348
Shivani Sharmaffb32b82019-04-09 16:58:474349// History manipulation intervention:
4350void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474351 bool replace_entry,
4352 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404353 bool is_renderer_initiated,
4354 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454355 // Note that for a subframe, previous_document_was_activated is true if the
4356 // gesture happened in any subframe (propagated to main frame) or in the main
4357 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474358 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274359 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474360 return;
4361 }
4362 if (last_committed_entry_index_ == -1)
4363 return;
4364
Shivani Sharmac4cc8922019-04-18 03:11:174365 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474366
Alexander Timine3ec4192020-04-20 16:39:404367 // Log UKM with the URL we are navigating away from.
4368 ukm::builders::HistoryManipulationIntervention(
4369 previous_page_load_ukm_source_id)
4370 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474371}
4372
Shivani Sharmac4cc8922019-04-18 03:11:174373void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4374 int reference_index,
4375 bool skippable) {
4376 auto* reference_entry = GetEntryAtIndex(reference_index);
4377 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4378
4379 int64_t document_sequence_number =
4380 reference_entry->root_node()->frame_entry->document_sequence_number();
4381 for (int index = 0; index < GetEntryCount(); index++) {
4382 auto* entry = GetEntryAtIndex(index);
4383 if (entry->root_node()->frame_entry->document_sequence_number() ==
4384 document_sequence_number) {
4385 entry->set_should_skip_on_back_forward_ui(skippable);
4386 }
4387 }
4388}
4389
arthursonzogni66f711c2019-10-08 14:40:364390std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4391NavigationControllerImpl::ReferencePendingEntry() {
4392 DCHECK(pending_entry_);
4393 auto pending_entry_ref =
4394 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4395 pending_entry_refs_.insert(pending_entry_ref.get());
4396 return pending_entry_ref;
4397}
4398
4399void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4400 // Ignore refs that don't correspond to the current pending entry.
4401 auto it = pending_entry_refs_.find(ref);
4402 if (it == pending_entry_refs_.end())
4403 return;
4404 pending_entry_refs_.erase(it);
4405
4406 if (!pending_entry_refs_.empty())
4407 return;
4408
4409 // The pending entry may be deleted before the last PendingEntryRef.
4410 if (!pending_entry_)
4411 return;
4412
4413 // We usually clear the pending entry when the matching NavigationRequest
4414 // fails, so that an arbitrary URL isn't left visible above a committed page.
4415 //
4416 // However, we do preserve the pending entry in some cases, such as on the
4417 // initial navigation of an unmodified blank tab. We also allow the delegate
4418 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4419 // user edit the URL and try again. This may be useful in cases that the
4420 // committed page cannot be attacker-controlled. In these cases, we still
4421 // allow the view to clear the pending entry and typed URL if the user
4422 // requests (e.g., hitting Escape with focus in the address bar).
4423 //
4424 // Do not leave the pending entry visible if it has an invalid URL, since this
4425 // might be formatted in an unexpected or unsafe way.
4426 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364427 bool should_preserve_entry =
4428 (pending_entry_ == GetVisibleEntry()) &&
4429 pending_entry_->GetURL().is_valid() &&
4430 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4431 if (should_preserve_entry)
4432 return;
4433
4434 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374435 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364436}
4437
Titouan Rigoudy6ec70402021-02-02 15:42:194438std::unique_ptr<PolicyContainerPolicies>
4439NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394440 RenderFrameHostImpl* rfh,
4441 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174442 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394443 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454444 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394445 FrameNavigationEntry* previous_frame_entry =
4446 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4447
4448 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4449 // ensure we always have a FrameNavigationEntry here.
4450 if (!previous_frame_entry)
4451 return nullptr;
4452
Titouan Rigoudy6ec70402021-02-02 15:42:194453 const PolicyContainerPolicies* previous_policies =
4454 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394455
Titouan Rigoudy6ec70402021-02-02 15:42:194456 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394457 return nullptr;
4458
4459 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234460 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394461 }
4462
Titouan Rigoudy72f892d2022-05-02 18:21:234463 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394464}
4465
Hayato Ito2c8c08d02021-06-23 03:38:434466void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504467 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434468 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4469 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4470 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504471
4472 auto callback = base::BindRepeating(
4473 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4474 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4475 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4476 }
4477 },
Hayato Ito2c8c08d02021-06-23 03:38:434478 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034479 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504480}
4481
4482void NavigationControllerImpl::DidAccessInitialMainDocument() {
4483 // We may have left a failed browser-initiated navigation in the address bar
4484 // to let the user edit it and try again. Clear it now that content might
4485 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034486 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504487 DiscardPendingEntry(false);
4488
4489 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374490 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504491}
4492
4493void NavigationControllerImpl::UpdateStateForFrame(
4494 RenderFrameHostImpl* rfhi,
4495 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564496 OPTIONAL_TRACE_EVENT1("content",
4497 "NavigationControllerImpl::UpdateStateForFrame",
4498 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504499 // The state update affects the last NavigationEntry associated with the given
4500 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4501 // in the case of an UpdateState from a frame being swapped out). We track
4502 // which entry this is in the RenderFrameHost's nav_entry_id.
4503 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4504 if (!entry)
4505 return;
4506
4507 FrameNavigationEntry* frame_entry =
4508 entry->GetFrameEntry(rfhi->frame_tree_node());
4509 if (!frame_entry)
4510 return;
4511
4512 // The SiteInstance might not match if we do a cross-process navigation with
4513 // replacement (e.g., auto-subframe), in which case the swap out of the old
4514 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4515 // has already been replaced and destroyed.
4516 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4517 return;
4518
4519 if (page_state == frame_entry->page_state())
4520 return; // Nothing to update.
4521
4522 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4523
4524 // The document_sequence_number and item_sequence_number recorded in the
4525 // FrameNavigationEntry should not differ from the one coming with the update,
4526 // since it must come from the same document. Do not update it if a difference
4527 // is detected, as this indicates that |frame_entry| is not the correct one.
4528 blink::ExplodedPageState exploded_state;
4529 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4530 return;
4531
4532 if (exploded_state.top.document_sequence_number !=
4533 frame_entry->document_sequence_number() ||
4534 exploded_state.top.item_sequence_number !=
4535 frame_entry->item_sequence_number()) {
4536 return;
4537 }
4538
4539 frame_entry->SetPageState(page_state);
4540 NotifyEntryChanged(entry);
4541}
4542
Domenic Denicolacd30f5f82022-03-16 21:48:014543std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4544NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574545 Direction direction,
4546 int entry_index,
4547 const url::Origin& pending_origin,
4548 FrameTreeNode* node,
4549 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304550 int64_t pending_item_sequence_number,
4551 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014552 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454553 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174554 // Don't process the initial entry.
4555 DCHECK_EQ(GetEntryCount(), 1);
4556 return entries;
4557 }
Nate Chapind1fe3612021-04-16 20:45:574558 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304559 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574560 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4561 i += offset) {
4562 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414563 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574564 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014565 // An entry should only appear in the navigation API entries if it is for
4566 // the same origin as the document being committed. Check the committed
4567 // origin, or if that is not available (during restore), check against the
4568 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414569 url::Origin frame_entry_origin =
4570 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4571 frame_entry->url(),
4572 frame_entry->initiator_origin().value_or(url::Origin())));
4573 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574574 break;
4575 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4576 continue;
4577 blink::ExplodedPageState exploded_page_state;
4578 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4579 &exploded_page_state)) {
4580 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304581
4582 // If the document represented by this FNE hid its full url from appearing
4583 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014584 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304585 // document).
4586 std::u16string url;
4587 if (pending_document_sequence_number ==
4588 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574589 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304590 url = frame_state.url_string.value_or(std::u16string());
4591 }
4592
Domenic Denicolacd30f5f82022-03-16 21:48:014593 blink::mojom::NavigationApiHistoryEntryPtr entry =
4594 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574595 frame_state.navigation_api_key.value_or(std::u16string()),
4596 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094597 frame_state.item_sequence_number,
4598 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304599 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174600
Nate Chapin63db0d12022-01-20 22:03:304601 DCHECK(entry->url.empty() ||
4602 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574603 entries.push_back(std::move(entry));
4604 previous_item_sequence_number = frame_entry->item_sequence_number();
4605 }
4606 }
4607 // If |entries| was constructed by iterating backwards from
4608 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4609 // earliest-at-the-front. Reverse it.
4610 if (direction == Direction::kBack)
4611 std::reverse(entries.begin(), entries.end());
4612 return entries;
4613}
4614
Domenic Denicolacd30f5f82022-03-16 21:48:014615blink::mojom::NavigationApiHistoryEntryArraysPtr
4616NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554617 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574618 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404619 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444620 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404621 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574622
Nate Chapind1fe3612021-04-16 20:45:574623 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554624 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574625
Nate Chapine82339d02022-05-03 23:48:254626 // NOTE: |entry_index| is the index where this entry will commit if no
4627 // modifications are made between now and DidCommitNavigation. This is used to
4628 // walk |entries_| and determine which entries should be exposed by the
4629 // navigation API. It is important to calculate this correctly, because blink
4630 // will cancel a same-document history commit if it's not present in the
4631 // entries blink knows about.
4632 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574633 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304634 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254635 bool will_create_new_entry = false;
4636 if (GetPendingEntryIndex() != -1) {
4637 entry_index = GetPendingEntryIndex();
4638 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4639 pending_item_sequence_number = frame_entry->item_sequence_number();
4640 pending_document_sequence_number =
4641 frame_entry->document_sequence_number();
4642 }
4643 } else if (request &&
4644 !NavigationTypeUtils::IsReload(
4645 request->common_params().navigation_type) &&
4646 !NavigationTypeUtils::IsHistory(
4647 request->common_params().navigation_type) &&
4648 !request->common_params().should_replace_current_entry &&
4649 !request->common_params()
4650 .is_history_navigation_in_new_child_frame) {
4651 will_create_new_entry = true;
4652 entry_index = GetLastCommittedEntryIndex() + 1;
4653 // Don't set pending_item_sequence_number or
4654 // pending_document_sequence_number in this case - a new unique isn/dsn will
4655 // be calculated in the renderer later.
4656 } else if (GetLastCommittedEntryIndex() != -1) {
4657 entry_index = GetLastCommittedEntryIndex();
4658 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574659 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304660 pending_document_sequence_number =
4661 frame_entry->document_sequence_number();
4662 }
Nate Chapind1fe3612021-04-16 20:45:574663 }
4664
Domenic Denicolacd30f5f82022-03-16 21:48:014665 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254666 if (entry_index == -1) {
4667 // TODO(rakina): Exit early when there is no last committed entry.
4668 // Remove when InitialNavigationEntry ships.
4669 return entry_arrays;
4670 }
4671
Domenic Denicolacd30f5f82022-03-16 21:48:014672 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574673 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374674 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574675
4676 // Don't populate forward entries if they will be truncated by a new entry.
4677 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014678 entry_arrays->forward_entries =
4679 PopulateSingleNavigationApiHistoryEntryVector(
4680 Direction::kForward, entry_index, pending_origin, node,
4681 site_instance.get(), pending_item_sequence_number,
4682 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574683 }
Nate Chapin4e657a472022-02-06 03:38:374684 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574685}
4686
Nate Chapinfbfe5af2021-06-10 17:22:084687NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574688NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084689 FrameNavigationEntry* current_entry,
4690 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574691 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084692 if (!target_entry || !target_entry->committed_origin())
4693 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084694 if (!current_entry->committed_origin()->IsSameOriginWith(
4695 *target_entry->committed_origin())) {
4696 return HistoryNavigationAction::kStopLooking;
4697 }
4698
4699 // NOTE: We don't actually care between kSameDocument and
4700 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574701 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084702 return HistoryNavigationAction::kDifferentDocument;
4703 return HistoryNavigationAction::kKeepLooking;
4704}
4705
Domenic Denicolacc094fb2022-03-16 23:40:574706void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204707 RenderFrameHostImpl* initiator_rfh,
Yoav Weissa7449c3b2022-11-22 15:15:144708 absl::optional<blink::scheduler::TaskAttributionId>
4709 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574710 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204711 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084712 FrameNavigationEntry* current_entry =
4713 GetLastCommittedEntry()->GetFrameEntry(node);
4714 if (!current_entry)
4715 return;
4716
Yoav Weiss8c573952022-11-17 17:35:134717 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4718 // when `navigation.traverseTo()` is called.
4719
Nate Chapinfbfe5af2021-06-10 17:22:084720 // We want to find the nearest matching entry that is contiguously
4721 // same-instance and same-origin. Check back first, then forward.
4722 // TODO(japhet): Link spec here once it exists.
4723 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574724 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084725 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4726 if (result == HistoryNavigationAction::kStopLooking)
4727 break;
4728 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144729 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084730 return;
4731 }
4732 }
4733 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574734 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084735 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4736 if (result == HistoryNavigationAction::kStopLooking)
4737 break;
4738 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144739 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084740 return;
4741 }
4742 }
Nate Chapinbf682fa32022-09-26 22:41:204743
4744 // If we fall through to here, a matching NavigationEntry couldn't be found.
4745 // Notify the renderer that the navigation was cancelled.
4746 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4747 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084748}
4749
Domenic Denicolacc094fb2022-03-16 23:40:574750bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304751 network::mojom::ReferrerPolicy referrer_policy) {
4752 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4753 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4754}
4755
shivanigithubf405bf0d2021-11-05 17:58:334756bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4757 const FrameTreeNode* frame_tree_node) const {
4758 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4759 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544760 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Ali Hijazid87307d2022-11-07 20:15:034761 return frame_tree_->is_prerendering() ||
shivanigithubf405bf0d2021-11-05 17:58:334762 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544763}
4764
Julie Jeongeun Kim0e242242022-11-30 10:45:094765void NavigationControllerImpl::DidChangeReferrerPolicy(
4766 FrameTreeNode* node,
4767 network::mojom::ReferrerPolicy referrer_policy) {
4768 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4769 if (!entry)
4770 return;
4771
4772 // The FrameNavigationEntry may want to change whether to protect its url
4773 // in the navigation API when the referrer policy changes.
4774 entry->set_protect_url_in_navigation_api(
4775 ShouldProtectUrlInNavigationApi(referrer_policy));
4776}
4777
[email protected]8ff00d72012-10-23 19:12:214778} // namespace content