blob: c355534e91681362479ab0dd8de2ad0f941e590c [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() {
Jeremy Roman2d8dfe132021-07-06 20:51:261018 const std::string& mime_type =
Ali Hijazid87307d2022-11-07 20:15:031019 frame_tree_->root()->current_frame_host()->GetPage().contents_mime_type();
Kinuko Yasuda74702f92017-07-31 03:27:531020 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1021 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271022 NavigationEntry* visible_entry = GetVisibleEntry();
1023 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391024 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161025}
1026
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571027int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271028 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451029 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271030 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551031 return last_committed_entry_index_;
1032}
1033
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571034int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451035 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291036 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551037 return static_cast<int>(entries_.size());
1038}
1039
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571040NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371041 if (index < 0 || index >= GetEntryCount())
1042 return nullptr;
1043
avif16f85a72015-11-13 18:25:031044 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251045}
1046
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571047NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471048 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201049}
1050
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571051int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461052 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031053}
1054
Kevin McNee3b3a56192023-03-17 14:40:591055absl::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031056 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591057 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1058 return index;
1059 }
Shivani Sharma298d12852019-01-22 20:04:031060 }
Kevin McNee3b3a56192023-03-17 14:40:591061 return absl::nullopt;
1062}
1063
1064bool NavigationControllerImpl::CanGoBack() {
1065 return GetIndexForGoBack().has_value();
1066}
1067
1068absl::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
1069 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1070 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1071 return index;
1072 }
1073 }
1074 return absl::nullopt;
[email protected]765b35502008-08-21 00:51:201075}
1076
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571077bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591078 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201079}
1080
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571081bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031082 int index = GetIndexForOffset(offset);
1083 return index >= 0 && index < GetEntryCount();
1084}
1085
Xiaohan Wang7f8052e02022-01-14 18:44:281086#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151087bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151088 if (offset == 0)
1089 return true;
1090 int increment = offset > 0 ? 1 : -1;
1091 int non_skippable_entries = 0;
1092 for (int index = GetIndexForOffset(increment);
1093 index >= 0 && index < GetEntryCount(); index += increment) {
1094 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1095 non_skippable_entries++;
1096
1097 if (non_skippable_entries == std::abs(offset))
1098 return true;
1099 }
1100 return false;
1101}
1102#endif
1103
[email protected]d202a7c2012-01-04 07:53:471104void NavigationControllerImpl::GoBack() {
Kevin McNee3b3a56192023-03-17 14:40:591105 const absl::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061106
Kevin McNeeedc481c2023-04-27 22:30:581107 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211108
Kevin McNee3b3a56192023-03-17 14:40:591109 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201110}
1111
[email protected]d202a7c2012-01-04 07:53:471112void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161113 // Note that at least one entry (the last one) will be non-skippable since
1114 // entries are marked skippable only when they add another entry because of
1115 // redirect or pushState.
Kevin McNee3b3a56192023-03-17 14:40:591116 const absl::optional<int> target_index = GetIndexForGoForward();
1117
Kevin McNeeedc481c2023-04-27 22:30:581118 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591119
1120 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201121}
1122
[email protected]d202a7c2012-01-04 07:53:471123void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131124 GoToIndex(index, /*initiator_rfh=*/nullptr,
1125 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
1126 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161127}
1128
Nate Chapinbf682fa32022-09-26 22:41:201129void NavigationControllerImpl::GoToIndex(
1130 int index,
1131 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131132 absl::optional<blink::scheduler::TaskAttributionId>
1133 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201134 const std::string* navigation_api_key) {
Rakina Zata Amnid605d462022-06-01 10:17:031135 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
sunjian30574a62017-03-21 21:39:441136 TRACE_EVENT0("browser,navigation,benchmark",
1137 "NavigationControllerImpl::GoToIndex");
[email protected]765b35502008-08-21 00:51:201138 if (index < 0 || index >= static_cast<int>(entries_.size())) {
Rakina Zata Amni4595c36a2023-02-01 03:51:181139 // We've seen reports of this NOTREACHED being hit on Android WebView, where
1140 // we won't get the log message below. The following code ensures that
1141 // `index` and `entries_size` will show up on the minidump for that case.
1142 base::debug::Alias(&index);
1143 const size_t entries_size = entries_.size();
1144 base::debug::Alias(&entries_size);
1145 NOTREACHED() << "Index " << index
1146 << " is out of bounds, entries_.size() is " << entries_size;
[email protected]765b35502008-08-21 00:51:201147 return;
1148 }
1149
Rakina Zata Amnif297a802022-01-18 03:53:431150 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1151 // We should never navigate to an existing initial NavigationEntry that is
1152 // the initial NavigationEntry for the initial empty document that hasn't
1153 // been overridden by the synchronous about:blank commit, to preserve
1154 // legacy behavior where trying to reload when the main frame is on the
1155 // initial empty document won't result in a navigation. See also
1156 // https://crbug.com/1277414.
1157 return;
1158 }
1159
[email protected]cbab76d2008-10-13 22:42:471160 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201161
arthursonzogni5c4c202d2017-04-25 23:41:271162 DCHECK_EQ(nullptr, pending_entry_);
1163 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431164
arthursonzogni5c4c202d2017-04-25 23:41:271165 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201166 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271167 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1168 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201169 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131170 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201171 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201172}
1173
[email protected]d202a7c2012-01-04 07:53:471174void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121175 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031176 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201177 return;
1178
[email protected]9ba14052012-06-22 23:50:031179 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201180}
1181
Nate Chapinbf682fa32022-09-26 22:41:201182void NavigationControllerImpl::GoToOffsetFromRenderer(
1183 int offset,
Yoav Weiss8c573952022-11-17 17:35:131184 RenderFrameHostImpl* initiator_rfh,
1185 absl::optional<blink::scheduler::TaskAttributionId>
1186 soft_navigation_heuristics_task_id) {
Nate Chapin758e5e482023-05-02 00:22:551187 // If the renderer sent an out-of-bounds offset, cancel and notify the
1188 // renderer.
1189 if (!CanGoToOffset(offset)) {
1190 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
1191 /*navigation_api_key=*/std::string(),
1192 blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapin45f620582021-09-30 17:45:431193 return;
Nate Chapin758e5e482023-05-02 00:22:551194 }
Nate Chapin45f620582021-09-30 17:45:431195
Nate Chapinbf682fa32022-09-26 22:41:201196 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131197 soft_navigation_heuristics_task_id,
1198 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431199}
1200
Xiaohan Wang7f8052e02022-01-14 18:44:281201#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151202void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1203 // Note: This is actually reached in unit tests.
1204 if (!CanGoToOffsetWithSkipping(offset))
1205 return;
1206
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421207 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151208 GoToIndex(GetIndexForOffset(offset));
1209 return;
1210 }
1211 int increment = offset > 0 ? 1 : -1;
1212 // Find the offset without counting skippable entries.
1213 int target_index = GetIndexForOffset(increment);
1214 int non_skippable_entries = 0;
1215 for (int index = target_index; index >= 0 && index < GetEntryCount();
1216 index += increment) {
1217 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1218 non_skippable_entries++;
1219
1220 if (non_skippable_entries == std::abs(offset)) {
1221 target_index = index;
1222 break;
1223 }
1224 }
1225
1226 GoToIndex(target_index);
1227}
1228#endif
1229
[email protected]41374f12013-07-24 02:49:281230bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151231 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281232 return false;
[email protected]6a13a6c2011-12-20 21:47:121233
[email protected]43032342011-03-21 14:10:311234 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281235 return true;
[email protected]cbab76d2008-10-13 22:42:471236}
1237
Michael Thiessen9b14d512019-09-23 21:19:471238void NavigationControllerImpl::PruneForwardEntries() {
1239 DiscardNonCommittedEntries();
1240 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471241 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471242 if (num_removed <= 0)
1243 return;
Nate Chapin9eb16be72022-09-23 22:54:311244 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471245 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1246 NotifyPrunedEntries(this, remove_start_index /* start index */,
1247 num_removed /* count */);
1248}
1249
Aran Gilman37d11632019-10-08 23:07:151250void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1251 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321252 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311253 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511254 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1255 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321256 }
1257}
1258
Harkiran Bolariaba823e42021-05-21 18:30:361259base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1260 const GURL& url,
1261 const Referrer& referrer,
1262 ui::PageTransition transition,
1263 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471264 LoadURLParams params(url);
1265 params.referrer = referrer;
1266 params.transition_type = transition;
1267 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361268 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471269}
1270
Harkiran Bolariaba823e42021-05-21 18:30:361271base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1272 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061273 if (params.is_renderer_initiated)
1274 DCHECK(params.initiator_origin.has_value());
1275
naskob8744d22014-08-28 17:07:431276 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151277 "NavigationControllerImpl::LoadURLWithParams", "url",
1278 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291279 bool is_explicit_navigation =
1280 GetContentClient()->browser()->IsExplicitNavigation(
1281 params.transition_type);
1282 if (HandleDebugURL(params.url, params.transition_type,
1283 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431284 // If Telemetry is running, allow the URL load to proceed as if it's
1285 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491286 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431287 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361288 return nullptr;
[email protected]47752982014-07-29 08:01:431289 }
[email protected]8bf1048012012-02-08 01:22:181290
[email protected]cf002332012-08-14 19:17:471291 // Checks based on params.load_type.
1292 switch (params.load_type) {
1293 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431294 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471295 break;
1296 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261297 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471298 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361299 return nullptr;
[email protected]cf002332012-08-14 19:17:471300 }
1301 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461302 }
[email protected]e47ae9472011-10-13 19:48:341303
[email protected]e47ae9472011-10-13 19:48:341304 // The user initiated a load, we don't need to reload anymore.
1305 needs_reload_ = false;
1306
Harkiran Bolariaba823e42021-05-21 18:30:361307 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441308}
1309
Mohamed Abdelhalim833de902019-09-16 17:41:451310bool NavigationControllerImpl::PendingEntryMatchesRequest(
1311 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191312 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451313 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191314}
1315
[email protected]d202a7c2012-01-04 07:53:471316bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321317 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071318 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331319 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441320 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251321 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471322 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131323 NavigationRequest* navigation_request) {
1324 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331325
1326 // Note: validation checks and renderer kills due to invalid commit messages
1327 // must happen before getting here, in
1328 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1329 // effects of the navigation have already occurred.
1330
[email protected]cd2e15742013-03-08 04:08:311331 is_initial_navigation_ = false;
1332
Wang Hui96ab1012022-10-11 02:05:491333 // Any pending request to repost a form submission is no longer valid, since a
1334 // different NavigationEntry is committing.
1335 pending_reload_ = ReloadType::NONE;
1336
[email protected]0e8db942008-09-24 21:21:481337 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431338 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451339 if (entry_replaced_by_post_commit_error_) {
1340 // Same document navigation events with a post-commit error should already
1341 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1342 // reaching here.
1343 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331344
Rakina Zata Amnie2d31312022-11-18 03:38:451345 // Any commit while a post-commit error page is showing should put the
1346 // original entry back, replacing the error page's entry. This includes
1347 // reloads, where the original entry was used as the pending entry and
1348 // should now be at the correct index at commit time.
1349 entries_[last_committed_entry_index_] =
1350 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481351 }
Rakina Zata Amnie2d31312022-11-18 03:38:451352 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1353 details->previous_entry_index = GetLastCommittedEntryIndex();
1354 if (PendingEntryMatchesRequest(navigation_request) &&
1355 pending_entry_->GetIsOverridingUserAgent() !=
1356 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1357 overriding_user_agent_changed = true;
1358 }
1359#if BUILDFLAG(IS_ANDROID)
1360 // TODO(crbug.com/1266277): Clean up the logic of setting
1361 // |overriding_user_agent_changed| post-launch.
1362 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1363 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
1364 // Must honor user agent overrides in the |navigation_request|, such as
1365 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1366 // result, besides comparing |pending_entry_|'s user agent against
1367 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1368 // agent against LastCommittedEntry's.
1369 if (navigation_request->is_overriding_user_agent() !=
1370 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1371 overriding_user_agent_changed = true;
1372 }
1373 }
1374#endif // BUILDFLAG(IS_ANDROID)
[email protected]ecd9d8702008-08-28 22:10:171375
Dave Tapuskaa2ab4f252021-07-08 21:31:281376 bool is_main_frame_navigation = !rfh->GetParent();
1377
Alexander Timind2f2e4f22019-04-02 20:04:531378 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1379 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281380 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141381 // BackForwardCacheMetrics to be associated with the new navigation's
1382 // NavigationEntry, by either creating a new object or reusing the previous
1383 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281384 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Arthur Sonzognif6785ec2022-12-05 10:11:501385 if (navigation_request->frame_tree_node()->frame_tree().type() ==
Dave Tapuskaa2ab4f252021-07-08 21:31:281386 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141387 back_forward_cache_metrics = BackForwardCacheMetrics::
1388 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281389 GetLastCommittedEntry(), is_main_frame_navigation,
1390 params.document_sequence_number);
1391 }
Yuzu Saijo29f96ca92022-12-08 04:54:121392
Alexander Timind2f2e4f22019-04-02 20:04:531393 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281394 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451395 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1396 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531397 }
1398 }
1399
Rakina Zata Amnifd8370b2022-11-14 13:32:251400 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1401 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091402 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251403 details->did_replace_entry =
1404 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091405
fdegans9caf66a2015-07-30 21:10:421406 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111407 // except for restored entries. This should be true even if the current commit
1408 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291409 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481410 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081411 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111412
1413 // Only make changes based on the pending entry if the NavigationRequest
1414 // matches it. Otherwise, the pending entry may be for a different request
1415 // (e.g., if a slow history navigation is pending while an auto-subframe
1416 // commit occurs).
1417 if (PendingEntryMatchesRequest(navigation_request)) {
1418 // It is no longer necessary to consider the pending entry as restored.
1419 if (pending_entry_->IsRestored()) {
1420 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1421 was_restored = true;
1422 }
[email protected]e9ba4472008-09-14 15:42:431423
Charlie Reisf8cde712022-10-20 16:25:091424 // If the SiteInstance has changed from the matching pending entry, this
1425 // must be treated as a new navigation with replacement. Set the replacement
1426 // bit here and ClassifyNavigation will identify this case and return
1427 // NEW_ENTRY.
1428 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1429 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1430 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251431 // TODO(nasko,creis,rakina): Move this to happen before committing the
1432 // navigation. This is a bit complicated because we don't currently
1433 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091434 details->did_replace_entry = true;
1435 }
Nasko Oskovaee2f862018-06-15 00:05:521436 }
[email protected]bcd904482012-02-01 01:54:221437
[email protected]e9ba4472008-09-14 15:42:431438 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101439 NavigationType navigation_type =
1440 ClassifyNavigation(rfh, params, navigation_request);
1441 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451442
Rakina Zata Amnie2d31312022-11-18 03:38:451443 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451444 // Ensure that this navigation does not add a navigation entry, since
1445 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1446 // beyond the last committed one. Therefore, `should_replace_current_entry`
1447 // should be set, which replaces the current entry, or this should be a
1448 // reload, which does not create a new entry.
1449 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1450 // navigation that is restored will not be creating a new entry anyways, so
1451 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1452 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1453 // pointed out in the issue.
Rakina Zata Amnifd8370b2022-11-14 13:32:251454 DCHECK(navigation_request->common_params().should_replace_current_entry ||
shivanigithub189833f2022-04-27 18:08:451455 navigation_request->GetReloadType() != ReloadType::NONE ||
Miyoung Shin3299cbf2022-11-22 01:41:101456 navigation_type == NAVIGATION_TYPE_AUTO_SUBFRAME);
shivanigithub189833f2022-04-27 18:08:451457 }
1458
Rakina Zata Amnie2d31312022-11-18 03:38:451459 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551460 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241461 // This is a subframe navigation on the initial empty document, which used
1462 // to not have a NavigationEntry to attach to. Now it can attach to the
1463 // initial NavigationEntry, and we must ensure that its NavigationEntry
1464 // will keep the "initial NavigationEntry" status and won't append a new
1465 // NavigationEntry (it should always do replacement instead).
1466 // See also https://crbug.com/1277414.
1467 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551468 // Subframe navigation on initial NavigationEntry must not append a new
1469 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1470 // means every subframe navigation that happens while we're on the initial
1471 // NavigationEntry will always reuse the existing NavigationEntry and
1472 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101473 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1474 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551475 // This is a navigation that modifies the initial NavigationEntry, either
1476 // for a replacement or a reload. The initial NavigationEntry should
1477 // retain its "initial NavigationEntry" status in this case.
1478 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241479 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251480 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1481 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241482 // This is a synchronous about:blank navigation on the main frame, which
1483 // used to not create a NavigationEntry when we have no NavigationEntry on
1484 // FrameTree creation. We now have the initial NavigationEntry and are on
1485 // the initial NavigationEntry. To preserve old behavior, we should still
1486 // keep the "initial" status for the new NavigationEntry that we will
1487 // create for this navigation, so that subframe navigations under the
1488 // synchronously committed about:blank document will never append new
1489 // NavigationEntry, and instead will just reuse the initial
1490 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1491 // See also https://crbug.com/1277414.
1492 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551493 }
1494 }
1495 DCHECK(!details->should_stay_as_initial_entry ||
1496 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201497
eugenebutee08663a2017-04-27 17:43:121498 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441499 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121500
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071501 details->is_prerender_activation =
1502 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241503 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1504 ->GetOutermostMainFrame()
1505 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071506
Peter Boströmd7592132019-01-30 04:50:311507 // Make sure we do not discard the pending entry for a different ongoing
1508 // navigation when a same document commit comes in unexpectedly from the
1509 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1510 // other navigation types. See https://crbug.com/900036.
1511 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061512 bool keep_pending_entry =
1513 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101514 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061515 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311516
Miyoung Shin3299cbf2022-11-22 01:41:101517 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061518 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491519 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051520 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001521 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431522 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061523 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491524 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1525 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001526 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431527 break;
[email protected]8ff00d72012-10-23 19:12:211528 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471529 RendererDidNavigateNewSubframe(
1530 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001531 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431532 break;
[email protected]8ff00d72012-10-23 19:12:211533 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391534 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251535 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001536 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081537 // We don't send a notification about auto-subframe PageState during
1538 // UpdateStateForFrame, since it looks like nothing has changed. Send
1539 // it here at commit time instead.
1540 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431541 return false;
creis59d5a47cb2016-08-24 23:57:191542 }
[email protected]e9ba4472008-09-14 15:42:431543 break;
Aran Gilman37d11632019-10-08 23:07:151544 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431545 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151546 break;
[email protected]765b35502008-08-21 00:51:201547 }
1548
[email protected]688aa65c62012-09-28 04:32:221549 // At this point, we know that the navigation has just completed, so
1550 // record the time.
1551 //
1552 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261553 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331554 base::Time timestamp =
1555 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1556 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131557 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221558
Peter Boströmd7592132019-01-30 04:50:311559 // If we aren't keeping the pending entry, there shouldn't be one at this
1560 // point. Clear it again in case any error cases above forgot to do so.
1561 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1562 // been cleared instead of protecting against it.
1563 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551564 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141565
[email protected]e9ba4472008-09-14 15:42:431566 // All committed entries should have nonempty content state so WebKit doesn't
1567 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471568 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321569 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221570 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441571 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141572
Alexander Timind2f2e4f22019-04-02 20:04:531573 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1574 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281575 if (back_forward_cache_metrics &&
1576 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531577 active_entry->set_back_forward_cache_metrics(
1578 std::move(back_forward_cache_metrics));
1579 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281580
1581 // `back_forward_cache_metrics()` may return null as we do not record
1582 // back-forward cache metrics for navigations in non-primary frame trees.
1583 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141584 // TODO(https://crbug.com/1338089): Remove this.
1585 // These are both only available from details at this point, so we capture
1586 // them here.
1587 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101588 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141589 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1590 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281591 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1592 navigation_request,
1593 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1594 }
naskoc7533512016-05-06 17:01:121595
Charles Reisc0507202017-09-21 00:40:021596 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1597 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1598 // A mismatch can occur if the renderer lies or due to a unique name collision
1599 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121600 FrameNavigationEntry* frame_entry =
1601 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021602 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1603 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031604 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081605 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1606 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031607 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201608
1609 // Remember the bindings the renderer process has at this point, so that
1610 // we do not grant this entry additional bindings if we come back to it.
1611 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301612 }
[email protected]132e281a2012-07-31 18:32:441613
[email protected]97d8f0d2013-10-29 16:49:211614 // Once it is committed, we no longer need to track several pieces of state on
1615 // the entry.
naskoc7533512016-05-06 17:01:121616 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131617
[email protected]49bd30e62011-03-22 20:12:591618 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221619 // TODO(creis): This check won't pass for subframes until we create entries
1620 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001621 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421622 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591623
[email protected]e9ba4472008-09-14 15:42:431624 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001625 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001626 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311627 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531628
arthursonzogni7ddc6542021-04-09 09:16:501629 active_entry->SetIsOverridingUserAgent(
1630 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031631
[email protected]93f230e02011-06-01 14:40:001632 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291633
aelias100c9192017-01-13 00:01:431634 if (overriding_user_agent_changed)
1635 delegate_->UpdateOverridingUserAgent();
1636
creis03b48002015-11-04 00:54:561637 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1638 // one knows the latest NavigationEntry it is showing (whether it has
1639 // committed anything in this navigation or not). This allows things like
1640 // state and title updates from RenderFrames to apply to the latest relevant
1641 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381642 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031643 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381644 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431645
1646 if (navigation_request->IsPrerenderedPageActivation()) {
1647 BroadcastHistoryOffsetAndLength();
1648 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1649 // is activated. As a result, a "prerenderingchange" event listener sees the
1650 // history.length which is not updated yet. We should guarantee that
1651 // history's length and offset should be updated before a
1652 // "prerenderingchange" event listener runs. One possible approach is to use
1653 // the same IPC which "prerenderingchange" uses, and propagate history's
1654 // length and offset together with that.
1655 }
1656
[email protected]e9ba4472008-09-14 15:42:431657 return true;
initial.commit09911bf2008-07-26 23:55:291658}
1659
[email protected]8ff00d72012-10-23 19:12:211660NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321661 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101662 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241663 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591664 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511665 "ClassifyNavigation");
1666
avi7c6f35e2015-05-08 17:52:381667 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241668 // A new entry. We may or may not have a corresponding pending entry, and
1669 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001670 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491671 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061672 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381673 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241674 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511675 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381676 return NAVIGATION_TYPE_NEW_SUBFRAME;
1677 }
1678
Charlie Reisc0f17d2d2021-01-12 18:52:491679 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381680 DCHECK(!params.history_list_was_cleared);
1681
avi39c1edd32015-06-04 20:06:001682 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381683 // All manual subframes would be did_create_new_entry and handled above, so
1684 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081685 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1686 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381687 }
1688
Rakina Zata Amnif6950d552020-11-24 03:26:101689 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1690 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381691 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1692 // create a new page.
1693
Hayato Ito2ae49442021-07-02 02:59:251694 // This main frame navigation is not a history navigation (since
1695 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1696 // reload or a replacement navigation, which will modify the existing entry.
1697 //
Nasko Oskov332593c2018-08-16 17:21:341698 // TODO(nasko): With error page isolation, reloading an existing session
1699 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491700 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341701 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511702 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491703 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061704 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381705 }
1706
Charlie Reisf8cde712022-10-20 16:25:091707 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521708 // If the SiteInstance of the |pending_entry_| does not match the
1709 // SiteInstance that got committed, treat this as a new navigation with
1710 // replacement. This can happen if back/forward/reload encounters a server
1711 // redirect to a different site or an isolated error page gets successfully
1712 // reloaded into a different SiteInstance.
1713 if (pending_entry_->site_instance() &&
1714 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491715 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061716 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521717 }
creis77c9aa32015-09-25 19:59:421718
Nasko Oskovaee2f862018-06-15 00:05:521719 if (pending_entry_index_ == -1) {
1720 // In this case, we have a pending entry for a load of a new URL but Blink
1721 // didn't do a new navigation (params.did_create_new_entry). First check
1722 // to make sure Blink didn't treat a new cross-process navigation as
1723 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161724 // we must treat it as NEW rather than the converted reload case below,
1725 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451726 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161727 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061728 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521729 }
1730
1731 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161732 // We will create a pending entry, but NavigateWithoutEntry will convert
1733 // it to a reload since it's the same page and not create a new entry for
1734 // it. (The user doesn't want to have a new back/forward entry when they
1735 // do this.) Therefore we want to just ignore the pending entry and go
1736 // back to where we were (the "existing entry").
1737 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061738 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521739 }
avi7c6f35e2015-05-08 17:52:381740 }
1741
Rakina Zata Amni153d5702021-09-13 22:48:001742 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381743 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491744 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1745 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161746 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061747 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381748 }
1749
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121750 if (navigation_request->DidEncounterError() &&
1751 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101752 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381753 // If the renderer was going to a new pending entry that got cleared because
1754 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491755 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381756 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511757 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491758 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061759 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381760 }
1761
Charlie Reisc0f17d2d2021-01-12 18:52:491762 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101763 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511764 trace_return.traced_value()->SetInteger("existing_entry_index",
1765 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381766 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441767 // The renderer has committed a navigation to an entry that no longer
1768 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491769 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061770 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381771 }
1772
avi7c6f35e2015-05-08 17:52:381773 // Since we weeded out "new" navigations above, we know this is an existing
1774 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491775 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061776 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381777}
1778
Rakina Zata Amni3460d382021-10-29 00:43:371779void NavigationControllerImpl::UpdateNavigationEntryDetails(
1780 NavigationEntryImpl* entry,
1781 RenderFrameHostImpl* rfh,
1782 const mojom::DidCommitProvisionalLoadParams& params,
1783 NavigationRequest* request,
1784 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001785 bool is_new_entry,
1786 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371787 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171788 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371789 entry->AddOrUpdateFrameEntry(
1790 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571791 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371792 rfh->GetSiteInstance(), nullptr, params.url,
1793 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171794 Referrer(*params.referrer),
1795 request ? request->common_params().initiator_origin : params.origin,
W. James MacLean23e90a12022-12-21 04:38:211796 request ? request->common_params().initiator_base_url : absl::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171797 request ? request->GetRedirectChain() : redirects, params.page_state,
1798 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amniafd3c6582021-11-30 06:19:171799 (request ? request->GetSubresourceWebBundleNavigationInfo() : nullptr),
Rakina Zata Amni3460d382021-10-29 00:43:371800 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171801 rfh, request && request->IsSameDocument(),
1802 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371803
1804 if (rfh->GetParent()) {
1805 // Only modify the NavigationEntry for main frame navigations.
1806 return;
1807 }
1808 if (entry->update_virtual_url_with_url())
1809 UpdateVirtualURLToURL(entry, params.url);
1810 // Don't use the page type from the pending entry. Some interstitial page
1811 // may have set the type to interstitial. Once we commit, however, the page
1812 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171813 entry->set_page_type((request && request->DidEncounterError())
1814 ? PAGE_TYPE_ERROR
1815 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431816 if (commit_details && commit_details->should_stay_as_initial_entry) {
1817 // Retain the "initial NavigationEntry" status.
1818 if (request->IsSameDocument()) {
1819 // If this is for a same-document navigation, the NavigationEntry must be
1820 // reused and should already be marked as the initial NavigationEntry.
1821 DCHECK(entry->IsInitialEntry());
1822 } else {
1823 // If this is for a cross-document navigation, it can be caused by a
1824 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1825 // "for synchronous about:blank" in the latter case, and also when it is
1826 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1827 // is not for a synchronous about:blank commit.
1828 NavigationEntryImpl::InitialNavigationEntryState new_state =
1829 NavigationEntryImpl::InitialNavigationEntryState::
1830 kInitialNotForSynchronousAboutBlank;
1831 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1832 request->is_synchronous_renderer_commit()) {
1833 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1834 kInitialForSynchronousAboutBlank;
1835 }
1836 entry->set_initial_navigation_entry_state(new_state);
1837 }
1838 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1839 // Remove the "initial NavigationEntry" status.
1840 entry->set_initial_navigation_entry_state(
1841 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001842 }
Rakina Zata Amniddf10502022-01-15 02:56:551843
Rakina Zata Amni3460d382021-10-29 00:43:371844 if (is_new_entry) {
1845 // Some properties of the NavigationEntry are only set when the entry is
1846 // new (we aren't reusing it).
1847 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171848 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1849 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371850 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1851 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1852 } else {
1853 // We are reusing the NavigationEntry. The site instance will normally be
1854 // the same except for a few cases:
1855 // 1) session restore, when no site instance will be assigned or
1856 // 2) redirect, when the site instance is reset.
1857 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1858 entry->site_instance() == rfh->GetSiteInstance());
1859 }
1860}
1861
Rakina Zata Amniafd3c6582021-11-30 06:19:171862void NavigationControllerImpl::CreateInitialEntry() {
1863 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031864 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171865 auto params = mojom::DidCommitProvisionalLoadParams::New();
1866 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1867 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1868 // before we have initial NavigationEntries.
1869 params->url = GURL::EmptyGURL();
1870 params->http_status_code = 0;
1871 params->url_is_unreachable = false;
1872 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171873 params->post_id = -1;
1874 params->embedding_token = base::UnguessableToken::Create();
1875 params->navigation_token = base::UnguessableToken::Create();
1876 params->did_create_new_entry = true;
1877 params->origin = rfh->GetLastCommittedOrigin();
1878 params->should_update_history = true;
1879 params->item_sequence_number = 0;
1880 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151881 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171882 params->transition = is_in_fenced_frame_tree
1883 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1884 : ui::PAGE_TRANSITION_LINK;
1885 params->referrer = blink::mojom::Referrer::New();
1886
Rakina Zata Amniafd3c6582021-11-30 06:19:171887 auto new_entry = std::make_unique<NavigationEntryImpl>(
1888 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381889 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211890 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1891 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1892 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171893 UpdateNavigationEntryDetails(
1894 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001895 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1896 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171897
1898 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1899 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001900 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171901}
1902
Charlie Reisc0f17d2d2021-01-12 18:52:491903void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321904 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071905 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361906 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441907 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471908 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001909 NavigationRequest* request,
1910 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571911 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071912 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451913 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:521914 absl::optional<GURL> initiator_base_url;
1915 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
1916 initiator_base_url = request->common_params().initiator_base_url;
1917 }
Lukasz Anforowicz435bcb582019-07-12 20:50:061918
creisf49dfc92016-07-26 17:05:181919 // First check if this is an in-page navigation. If so, clone the current
1920 // entry instead of looking at the pending entry, because the pending entry
1921 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451922 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301923 FrameNavigationEntry* previous_frame_entry =
1924 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451925 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481926 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571927 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:081928 rfh->GetSiteInstance(), nullptr, params.url,
1929 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:211930 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:091931 request->GetRedirectChain(), params.page_state, params.method,
1932 params.post_id, nullptr /* blob_url_loader_factory */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:481933 request->GetSubresourceWebBundleNavigationInfo(),
Antonio Sartori78a749f2020-11-30 12:03:391934 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301935 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:571936 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:301937 // FrameNavigationEntry.
1938 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:571939 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:031940
creisf49dfc92016-07-26 17:05:181941 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:031942 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:521943 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1944 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571945 // TODO(jam): we had one report of this with a URL that was redirecting to
1946 // only tildes. Until we understand that better, don't copy the cert in
1947 // this case.
1948 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571949 }
creisf49dfc92016-07-26 17:05:181950
Patrick Monette50e8bd82019-06-13 22:40:451951 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1952 // that |frame_entry| should now have a reference count of exactly 2: one
1953 // due to the local variable |frame_entry|, and another due to |new_entry|
1954 // also retaining one. This should never fail, because it's the main frame.
1955 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181956 }
1957
Harkiran Bolaria59290d62021-03-17 01:53:011958 // If this is an activation navigation from a prerendered page, transfer the
1959 // new entry from an entry already created and stored in the
1960 // NavigationRequest. |new_entry| will not have been set prior to this as
1961 // |is_same_document| is mutually exclusive with
1962 // |IsPrerenderedPageActivation|.
1963 if (request->IsPrerenderedPageActivation()) {
1964 DCHECK(!is_same_document);
1965 DCHECK(!new_entry);
1966 new_entry = request->TakePrerenderNavigationEntry();
1967 DCHECK(new_entry);
1968 }
1969
Charlie Reisc0f17d2d2021-01-12 18:52:491970 // Only make a copy of the pending entry if it is appropriate for the new
1971 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451972 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041973 // 1. The SiteInstance hasn't been assigned to something else.
1974 // 2. The pending entry was intended as a new entry, rather than being a
1975 // history navigation that was interrupted by an unrelated,
1976 // renderer-initiated navigation.
1977 // TODO(csharrison): Investigate whether we can remove some of the coarser
1978 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451979 if (!new_entry && PendingEntryMatchesRequest(request) &&
1980 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:341981 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:431982 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:351983 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:431984
Camille Lamy62b826012019-02-26 09:15:471985 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451986 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:181987 }
1988
Charlie Reisc0f17d2d2021-01-12 18:52:491989 // For cross-document commits with no matching pending entry, create a new
1990 // entry.
creisf49dfc92016-07-26 17:05:181991 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061992 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:071993 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:211994 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:581995 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:451996 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:171997 nullptr, // blob_url_loader_factory
1998 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:241999
2000 // Find out whether the new entry needs to update its virtual URL on URL
2001 // change and set up the entry accordingly. This is needed to correctly
2002 // update the virtual URL when replaceState is called after a pushState.
2003 GURL url = params.url;
2004 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492005 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412006 // update the virtual URL based on the new URL. For example, this is needed
2007 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2008 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372009 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2010 &url, browser_context_, &needs_update);
2011 new_entry->set_update_virtual_url_with_url(needs_update);
2012
Camille Lamy62b826012019-02-26 09:15:472013 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452014 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432015 }
2016
Harkiran Bolaria59290d62021-03-17 01:53:012017 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
2018 // for prerendered contents, if any. This is because prerendering/activation
2019 // technically won't be creating a new document. Unlike BFCache, prerendering
2020 // creates a new NavigationEntry rather than using an existing one.
2021 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372022 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2023 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002024 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082025
Harkiran Bolaria59290d62021-03-17 01:53:012026 // history.pushState() is classified as a navigation to a new page, but sets
2027 // is_same_document to true. In this case, we already have the title and
2028 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452029 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012030 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2031 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2032 }
[email protected]3a868f212014-08-09 10:41:192033 }
[email protected]ff64b3e2014-05-31 04:07:332034
[email protected]60d6cca2013-04-30 08:47:132035 DCHECK(!params.history_list_was_cleared || !replace_entry);
2036 // The browser requested to clear the session history when it initiated the
2037 // navigation. Now we know that the renderer has updated its state accordingly
2038 // and it is safe to also clear the browser side history.
2039 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552040 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132041 entries_.clear();
2042 last_committed_entry_index_ = -1;
2043 }
2044
Nasko Oskovaee2f862018-06-15 00:05:522045 // If this is a new navigation with replacement and there is a
2046 // pending_entry_ which matches the navigation reported by the renderer
2047 // process, then it should be the one replaced, so update the
2048 // last_committed_entry_index_ to use it.
2049 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092050 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522051 last_committed_entry_index_ = pending_entry_index_;
2052 }
2053
Alexander Timine3ec4192020-04-20 16:39:402054 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412055 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402056 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052057
Yuzu Saijoa725585f2022-11-28 04:14:032058 // If this is a history navigation and the old entry has an existing
2059 // back/forward cache metrics object, keep using the old one so that the
2060 // reasons logged from the last time the page navigated gets preserved.
2061 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2062 request)) {
2063 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2064 // because some tests do not have a pending entry.
2065 NavigationEntryImpl* entry =
2066 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2067 if (entry && entry->back_forward_cache_metrics()) {
2068 scoped_refptr<BackForwardCacheMetrics> metrics =
2069 entry->TakeBackForwardCacheMetrics();
2070 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2071 }
2072 }
2073
Carlos IL42b416592019-10-07 23:10:362074 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312075 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152076 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432077}
2078
Charlie Reisc0f17d2d2021-01-12 18:52:492079void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322080 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072081 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362082 bool is_same_document,
jam48cea9082017-02-15 06:13:292083 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452084 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002085 bool keep_pending_entry,
2086 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562087 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2088 << "that a last committed entry exists.";
2089
[email protected]e9ba4472008-09-14 15:42:432090 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002091 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432092
Charlie Reis7e2cb6d2021-01-26 01:27:162093 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002094 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162095 // We're guaranteed to have a last committed entry if intended_as_new_entry
2096 // is true.
avicbdc4c12015-07-01 16:07:112097 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162098
2099 // If the NavigationRequest matches a new pending entry and is classified as
2100 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2101 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092102 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162103 // Note: The pending entry will usually have a real ReloadType here, but
2104 // it can still be ReloadType::NONE in cases that
2105 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2106
2107 // If we classified this correctly, the SiteInstance should not have
2108 // changed.
2109 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2110
2111 // For converted reloads, we assign the entry's unique ID to be that of
2112 // the new one. Since this is always the result of a user action, we want
2113 // to dismiss infobars, etc. like a regular user-initiated navigation.
2114 entry->set_unique_id(pending_entry_->GetUniqueID());
2115
2116 // The extra headers may have changed due to reloading with different
2117 // headers.
2118 entry->set_extra_headers(pending_entry_->extra_headers());
2119 }
2120 // Otherwise, this was intended as a new entry but the pending entry was
2121 // lost in the meantime and no new entry was created. We are stuck at the
2122 // last committed entry.
2123
2124 // Even if this is a converted reload from pressing enter in the omnibox,
2125 // the server could redirect, requiring an update to the SSL status. If this
2126 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452127 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162128 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472129 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452130 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162131 }
Rakina Zata Amnif6950d552020-11-24 03:26:102132 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112133 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102134 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162135
eugenebut604866f2017-05-10 21:35:362136 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452137 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362138 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2139 // this was a restored same document navigation entry, then it won't have
2140 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2141 // navigated it.
jam48cea9082017-02-15 06:13:292142 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522143 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2144 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292145 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2146 was_restored) {
2147 entry->GetSSL() = last_entry->GetSSL();
2148 }
2149 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452150 // In rapid back/forward navigations |request| sometimes won't have a cert
2151 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192152 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452153 if (request->GetSSLInfo().has_value() &&
2154 request->GetSSLInfo()->is_valid()) {
2155 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522156 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2157 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192158 entry->GetSSL() = SSLStatus();
2159 }
jam48cea9082017-02-15 06:13:292160 }
avicbdc4c12015-07-01 16:07:112161 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272162 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572163 // navigations that are EXISTING_ENTRY are same-document navigations that
2164 // result in replacement (e.g. history.replaceState(), location.replace(),
2165 // forced replacements for trivial session history contexts). For these
2166 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112167 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102168
Mikel Astizba9cf2fd2017-12-17 10:38:102169 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2170 // to avoid misleading interpretations (e.g. URLs paired with
2171 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2172 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2173 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2174
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572175 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102176
eugenebut604866f2017-05-10 21:35:362177 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452178 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362179 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472180 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452181 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112182 }
2183 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432184
Rakina Zata Amni3460d382021-10-29 00:43:372185 UpdateNavigationEntryDetails(entry, rfh, params, request,
2186 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002187 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302188
[email protected]5ccd4dc2012-10-24 02:28:142189 // The redirected to page should not inherit the favicon from the previous
2190 // page.
eugenebut604866f2017-05-10 21:35:362191 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482192 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142193
Charlie Reis951f43372023-05-05 00:30:072194 // Update the last committed index to reflect the committed entry. Do this
2195 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2196 // delegate sees the correct committed index when notified of navigation
2197 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2198 // https://crbug.com/1439948.)
2199 if (base::FeatureList::IsEnabled(
2200 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2201 last_committed_entry_index_ = GetIndexOfEntry(entry);
2202 }
2203
Peter Boströmd7592132019-01-30 04:50:312204 // We should also usually discard the pending entry if it corresponds to a
2205 // different navigation, since that one is now likely canceled. In rare
2206 // cases, we leave the pending entry for another navigation in place when we
2207 // know it is still ongoing, to avoid a flicker in the omnibox (see
2208 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432209 //
2210 // Note that we need to use the "internal" version since we don't want to
2211 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312212 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002213 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392214
Charlie Reis951f43372023-05-05 00:30:072215 if (!base::FeatureList::IsEnabled(
2216 kUpdateSessionHistoryIndexBeforeNavigationStateChanged)) {
2217 // Update the last committed index to reflect the committed entry.
2218 // (This is legacy behavior, in case the kill-switch needs to be used.)
2219 last_committed_entry_index_ = GetIndexOfEntry(entry);
2220 }
[email protected]e9ba4472008-09-14 15:42:432221}
2222
[email protected]d202a7c2012-01-04 07:53:472223void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322224 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072225 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362226 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472227 bool replace_entry,
2228 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002229 NavigationRequest* request,
2230 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262231 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2232 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552233 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2234 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112235
[email protected]e9ba4472008-09-14 15:42:432236 // Manual subframe navigations just get the current entry cloned so the user
2237 // can go back or forward to it. The actual subframe information will be
2238 // stored in the page state for each of those entries. This happens out of
2239 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092240 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2241 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382242
Mikel Astizba9cf2fd2017-12-17 10:38:102243 // The DCHECK below documents the fact that we don't know of any situation
2244 // where |replace_entry| is true for subframe navigations. This simplifies
2245 // reasoning about the replacement struct for subframes (see
2246 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2247 DCHECK(!replace_entry);
2248
Patrick Monette50e8bd82019-06-13 22:40:452249 // This FrameNavigationEntry might not end up being used in the
2250 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072251 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452252 request->common_params().initiator_origin;
W. James MacLean8be423a2023-03-31 21:35:522253 absl::optional<GURL> initiator_base_url;
2254 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2255 initiator_base_url = request->common_params().initiator_base_url;
2256 }
Nate Chapin63db0d12022-01-20 22:03:302257 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2258 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2259 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572260 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302261 if (is_same_document) {
2262 FrameNavigationEntry* previous_frame_entry =
2263 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572264 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302265 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572266 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302267 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572268 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302269 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572270 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302271 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572272 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302273 policy_container_policies->referrer_policy);
2274 }
2275
Patrick Monette50e8bd82019-06-13 22:40:452276 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482277 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572278 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082279 rfh->GetSiteInstance(), nullptr, params.url,
2280 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212281 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2282 request->GetRedirectChain(), params.page_state, params.method,
2283 params.post_id, nullptr /* blob_url_loader_factory */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482284 request->GetSubresourceWebBundleNavigationInfo(),
Domenic Denicolacc094fb2022-03-16 23:40:572285 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032286
creisce0ef3572017-01-26 17:53:082287 std::unique_ptr<NavigationEntryImpl> new_entry =
2288 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452289 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032290 frame_tree_->root());
creise062d542015-08-25 02:01:552291
Alexander Timine3ec4192020-04-20 16:39:402292 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412293 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402294 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472295
creisce0ef3572017-01-26 17:53:082296 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452297 // to replace, which can happen due to a unique name change. See
2298 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2299 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382300
Dave Tapuska87696ae2021-11-18 18:48:312301 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152302 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432303}
2304
[email protected]d202a7c2012-01-04 07:53:472305bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322306 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072307 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392308 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252309 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002310 NavigationRequest* request,
2311 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292312 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2313 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2314
[email protected]e9ba4472008-09-14 15:42:432315 // We're guaranteed to have a previously committed entry, and we now need to
2316 // handle navigation inside of a subframe in it without creating a new entry.
2317 DCHECK(GetLastCommittedEntry());
2318
creis913c63ce2016-07-16 19:52:522319 // For newly created subframes, we don't need to send a commit notification.
2320 // This is only necessary for history navigations in subframes.
2321 bool send_commit_notification = false;
2322
Rakina Zata Amnif6950d552020-11-24 03:26:102323 // If |nav_entry_id| is non-zero and matches an existing entry, this
2324 // is a history navigation. Update the last committed index accordingly. If
2325 // we don't recognize the |nav_entry_id|, it might be a recently
2326 // pruned entry. We'll handle it below.
2327 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2328 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472329 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062330 // Make sure that a subframe commit isn't changing the main frame's
2331 // origin. Otherwise the renderer process may be confused, leading to a
2332 // URL spoof. We can't check the path since that may change
2333 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572334 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2335 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242336 // We should use checks similar to RenderFrameHostImpl's
2337 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2338 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572339 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2340 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2341 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2342 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522343 current_top_url.DeprecatedGetOriginAsURL() !=
2344 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442345 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512346 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062347 }
creis3cdc3b02015-05-29 23:00:472348
creis913c63ce2016-07-16 19:52:522349 // We only need to discard the pending entry in this history navigation
2350 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062351 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002352 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522353
2354 // History navigations should send a commit notification.
2355 send_commit_notification = true;
avi98405c22015-05-21 20:47:062356 }
[email protected]e9ba4472008-09-14 15:42:432357 }
[email protected]f233e4232013-02-23 00:55:142358
creisce0ef3572017-01-26 17:53:082359 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2360 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372361 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2362 // exists), or we may want to clobber it and create a new one. We update in
2363 // cases where the corresponding FrameNavigationEntry is conceptually similar
2364 // to the document described by the commit params: same-document
2365 // navigations, history traversal to an existing entry, and reloads (including
2366 // a "soft reload" where we navigate to the same url without flagging it as a
2367 // reload). But in the case of a different document that is not logically
2368 // related to the committed FrameNavigationEntry's document (cross-document,
2369 // not same url, not a reload, not a history traversal), we replace rather
2370 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252371 //
Nate Chapin9f169072021-06-09 19:32:372372 // In the case where we update, the FrameNavigationEntry will potentially be
2373 // shared across multiple NavigationEntries, and any updates will be reflected
2374 // in all of those NavigationEntries. In the replace case, any existing
2375 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252376 //
2377 // When navigating away from the initial empty document, we also update rather
2378 // than replace. Either update or replace will overwrite the initial empty
2379 // document state for |last_committed|, but if the FrameNavigationEntry for
2380 // the initial empty document is shared across multiple NavigationEntries (due
2381 // to a navigation in another frame), we want to make sure we overwrite the
2382 // initial empty document state everywhere this FrameNavigationEntry is used,
2383 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452384 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372385 FrameNavigationEntry* last_committed_frame_entry =
2386 last_committed->GetFrameEntry(rfh->frame_tree_node());
2387 NavigationEntryImpl::UpdatePolicy update_policy =
2388 NavigationEntryImpl::UpdatePolicy::kUpdate;
2389 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312390 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372391 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252392 last_committed_frame_entry->url() != params.url &&
2393 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372394 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2395 }
2396
Rakina Zata Amni3460d382021-10-29 00:43:372397 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002398 update_policy, false /* is_new_entry */,
2399 commit_details);
creis625a0c7d2015-03-24 23:17:122400
creis913c63ce2016-07-16 19:52:522401 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432402}
2403
[email protected]d202a7c2012-01-04 07:53:472404int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232405 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032406 for (size_t i = 0; i < entries_.size(); ++i) {
2407 if (entries_[i].get() == entry)
2408 return i;
2409 }
2410 return -1;
[email protected]765b35502008-08-21 00:51:202411}
2412
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572413void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242414 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572415 NavigationControllerImpl* source =
2416 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572417 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382418 DCHECK_EQ(1, GetEntryCount());
2419 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472420 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172421 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572422
Francois Dorayeaace782017-06-21 16:37:242423 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442424 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572425 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572426
Fergal Dalya1d569972021-03-16 03:24:532427 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302428 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532429 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2430 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302431 }
[email protected]4e6419c2010-01-15 04:50:342432
Lukasz Anforowicz0de0f452020-12-02 19:57:152433 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572434}
2435
Aran Gilman37d11632019-10-08 23:07:152436void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2437 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162438 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012439 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162440
[email protected]d202a7c2012-01-04 07:53:472441 NavigationControllerImpl* source =
2442 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252443
avi2b177592014-12-10 02:08:022444 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012445 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252446
[email protected]474f8512013-05-31 22:31:162447 // We now have one entry, possibly with a new pending entry. Ensure that
2448 // adding the entries from source won't put us over the limit.
2449 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572450 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572451 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252452
Carlos IL4dea8902020-05-26 15:14:292453 // Insert the entries from source. Ignore any pending entry, since it has not
2454 // committed in source.
[email protected]474f8512013-05-31 22:31:162455 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172456 DCHECK_NE(max_source_index, -1);
2457 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572458
2459 // Ignore the source's current entry if merging with replacement.
2460 // TODO(davidben): This should preserve entries forward of the current
2461 // too. http://crbug.com/317872
2462 if (replace_entry && max_source_index > 0)
2463 max_source_index--;
2464
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572465 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252466
2467 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552468 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142469
Hayato Ito2c8c08d02021-06-23 03:38:432470 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252471}
2472
[email protected]79368982013-11-13 01:11:012473bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162474 // If there is no last committed entry, we cannot prune. Even if there is a
2475 // pending entry, it may not commit, leaving this WebContents blank, despite
2476 // possibly giving it new entries via CopyStateFromAndPrune.
2477 if (last_committed_entry_index_ == -1)
2478 return false;
[email protected]9350602e2013-02-26 23:27:442479
[email protected]474f8512013-05-31 22:31:162480 // We cannot prune if there is a pending entry at an existing entry index.
2481 // It may not commit, so we have to keep the last committed entry, and thus
2482 // there is no sensible place to keep the pending entry. It is ok to have
2483 // a new pending entry, which can optionally commit as a new navigation.
2484 if (pending_entry_index_ != -1)
2485 return false;
2486
[email protected]474f8512013-05-31 22:31:162487 return true;
2488}
2489
[email protected]79368982013-11-13 01:11:012490void NavigationControllerImpl::PruneAllButLastCommitted() {
2491 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162492
avi2b177592014-12-10 02:08:022493 DCHECK_EQ(0, last_committed_entry_index_);
2494 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442495
Hayato Ito2c8c08d02021-06-23 03:38:432496 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442497}
2498
[email protected]79368982013-11-13 01:11:012499void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162500 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012501 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262502
Nate Chapin9eb16be72022-09-23 22:54:312503 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2504
[email protected]474f8512013-05-31 22:31:162505 // Erase all entries but the last committed entry. There may still be a
2506 // new pending entry after this.
2507 entries_.erase(entries_.begin(),
2508 entries_.begin() + last_committed_entry_index_);
2509 entries_.erase(entries_.begin() + 1, entries_.end());
2510 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262511}
2512
Christian Dullweber1af31e62018-02-22 11:49:482513void NavigationControllerImpl::DeleteNavigationEntries(
2514 const DeletionPredicate& deletionPredicate) {
2515 // It is up to callers to check the invariants before calling this.
2516 CHECK(CanPruneAllButLastCommitted());
2517 std::vector<int> delete_indices;
2518 for (size_t i = 0; i < entries_.size(); i++) {
2519 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572520 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482521 delete_indices.push_back(i);
2522 }
2523 }
2524 if (delete_indices.empty())
2525 return;
2526
2527 if (delete_indices.size() == GetEntryCount() - 1U) {
2528 PruneAllButLastCommitted();
2529 } else {
2530 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382531 for (const auto& index : base::Reversed(delete_indices)) {
2532 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482533 }
Hayato Ito2c8c08d02021-06-23 03:38:432534 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482535 }
2536 delegate()->NotifyNavigationEntriesDeleted();
2537}
2538
Shivani Sharma883f5f32019-02-12 18:20:012539bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2540 auto* entry = GetEntryAtIndex(index);
2541 return entry && entry->should_skip_on_back_forward_ui();
2542}
2543
Carlos Caballero35ce710c2019-09-19 10:59:452544BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2545 return back_forward_cache_;
2546}
2547
William Liu055a3542023-04-02 17:21:192548NavigationEntryScreenshotCache*
2549NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
2550 CHECK_EQ(frame_tree_->type(), FrameTree::Type::kPrimary);
2551 if (!nav_entry_screenshot_cache_ && AreBackForwardTransitionsEnabled()) {
2552 nav_entry_screenshot_cache_ =
2553 std::make_unique<NavigationEntryScreenshotCache>(
2554 BrowserContextImpl::From(browser_context_)
2555 ->GetNavigationEntryScreenshotManager()
2556 ->GetSafeRef(),
2557 this);
2558 }
2559 return nav_entry_screenshot_cache_.get();
2560}
2561
clamy987a3752018-05-03 17:36:262562void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2563 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2564 // progress, since this will cause a use-after-free. (We only allow this
2565 // when the tab is being destroyed for shutdown, since it won't return to
2566 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032567 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262568
2569 if (was_failure && pending_entry_) {
2570 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2571 } else {
2572 failed_pending_entry_id_ = 0;
2573 }
2574
2575 if (pending_entry_) {
2576 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332577 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262578 pending_entry_index_ = -1;
2579 pending_entry_ = nullptr;
2580 }
arthursonzogni66f711c2019-10-08 14:40:362581
2582 // Ensure any refs to the current pending entry are ignored if they get
2583 // deleted, by clearing the set of known refs. All future pending entries will
2584 // only be affected by new refs.
2585 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262586}
2587
2588void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2589 if (pending_entry_)
2590 pending_entry_->set_ssl_error(error);
2591}
2592
Xiaohan Wang7f8052e02022-01-14 18:44:282593#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422594// static
2595bool NavigationControllerImpl::ValidateDataURLAsString(
2596 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2597 if (!data_url_as_string)
2598 return false;
2599
2600 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2601 return false;
2602
2603 // The number of characters that is enough for validating a data: URI.
2604 // From the GURL's POV, the only important part here is scheme, it doesn't
2605 // check the actual content. Thus we can take only the prefix of the url, to
2606 // avoid unneeded copying of a potentially long string.
2607 const size_t kDataUriPrefixMaxLen = 64;
2608 GURL data_url(
2609 std::string(data_url_as_string->front_as<char>(),
2610 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2611 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2612 return false;
2613
2614 return true;
2615}
2616#endif
2617
Shivani Sharma194877032019-03-07 17:52:472618void NavigationControllerImpl::NotifyUserActivation() {
2619 // When a user activation occurs, ensure that all adjacent entries for the
2620 // same document clear their skippable bit, so that the history manipulation
2621 // intervention does not apply to them.
shivanigithub99368382021-06-16 18:33:372622 if (base::FeatureList::IsEnabled(
2623 features::kDebugHistoryInterventionNoUserActivation)) {
2624 return;
2625 }
2626
Shivani Sharmac4cc8922019-04-18 03:11:172627 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472628}
2629
clamy987a3752018-05-03 17:36:262630bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2631 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332632 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2633 blink::LocalFrameToken initiator_frame_token,
2634 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262635 NavigationEntryImpl* entry =
2636 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2637 if (!entry)
2638 return false;
2639
2640 FrameNavigationEntry* frame_entry =
2641 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2642 if (!frame_entry)
2643 return false;
2644
Camille Lamy5193caa2018-10-12 11:59:422645 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572646 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232647 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332648 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2649 initiator_process_id);
clamyea99ea12018-05-28 13:54:232650
2651 if (!request)
2652 return false;
2653
arthursonzognif046d4a2019-12-12 19:08:102654 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412655
Rakina Zata Amni1c83b082023-02-08 01:09:002656 SCOPED_CRASH_KEY_STRING256(
2657 "Bug1400009", "req_url",
2658 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2659 SCOPED_CRASH_KEY_NUMBER(
2660 "Bug1400009", "nav_entry_si",
2661 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2662 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2663 frame_entry->site_instance()
2664 ? ((int)frame_entry->site_instance()->GetId())
2665 : -1);
2666 bool has_sig =
2667 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2668 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2669 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2670 has_sig ? (!!frame_tree_->GetRenderViewHost(
2671 frame_entry->site_instance()->group()))
2672 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052673 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2674 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232675
2676 return true;
clamy987a3752018-05-03 17:36:262677}
2678
Tsuyoshi Horo52fd08e2020-07-07 07:03:452679bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2680 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2681 if (!entry)
2682 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432683
2684 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2685 // We should never navigate to an existing initial NavigationEntry that is
2686 // the initial NavigationEntry for the initial empty document that hasn't
2687 // been overridden by the synchronous about:blank commit, to preserve
2688 // legacy behavior where trying to reload when the main frame is on the
2689 // initial empty document won't result in a navigation. See also
2690 // https://crbug.com/1277414.
2691 return false;
2692 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452693 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2694 if (!frame_entry)
2695 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142696 ReloadType reload_type = ReloadType::NORMAL;
2697 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452698 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142699 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452700 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432701 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332702 absl::nullopt /* initiator_frame_token */,
2703 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452704 if (!request)
2705 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052706 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452707 return true;
2708}
2709
clamy987a3752018-05-03 17:36:262710void NavigationControllerImpl::NavigateFromFrameProxy(
2711 RenderFrameHostImpl* render_frame_host,
2712 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022713 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452714 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072715 const absl::optional<url::Origin>& initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212716 const absl::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262717 bool is_renderer_initiated,
2718 SiteInstance* source_site_instance,
2719 const Referrer& referrer,
2720 ui::PageTransition page_transition,
2721 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252722 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262723 const std::string& method,
2724 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092725 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142726 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212727 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502728 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392729 const absl::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292730 blink::mojom::NavigationInitiatorActivationAndAdStatus
2731 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222732 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492733 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462734 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452735 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582736 bool is_container_initiated,
2737 absl::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582738 if (is_renderer_initiated)
2739 DCHECK(initiator_origin.has_value());
2740
clamy987a3752018-05-03 17:36:262741 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582742
Rakina Zata Amni2322f4f82022-01-24 13:24:242743 // Don't allow an entry replacement if there is no entry to replace.
2744 // http://crbug.com/457149
2745 if (GetEntryCount() == 0)
2746 should_replace_current_entry = false;
2747
clamy987a3752018-05-03 17:36:262748 // Create a NavigationEntry for the transfer, without making it the pending
2749 // entry. Subframe transfers should have a clone of the last committed entry
2750 // with a FrameNavigationEntry for the target frame. Main frame transfers
2751 // should have a new NavigationEntry.
2752 // TODO(creis): Make this unnecessary by creating (and validating) the params
2753 // directly, passing them to the destination RenderFrameHost. See
2754 // https://crbug.com/536906.
2755 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262756 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262757 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452758 DCHECK(GetLastCommittedEntry());
2759 entry = GetLastCommittedEntry()->Clone();
2760 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172761 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2762 // Renderer-initiated navigation that target a remote frame are currently
2763 // classified as browser-initiated when this one has already navigated.
2764 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372765 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2766 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2767 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2768 // same-document navigation), they will still be present in the
2769 // committed NavigationEntry that will be referenced to construct the new
2770 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262771 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082772 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582773 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072774 absl::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212775 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto22a27b142023-02-10 06:42:492776 blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482777 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori79d549d2021-02-18 12:59:542778 nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262779 } else {
2780 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172781 // If `node` is the outermost main frame, it rewrites a virtual url in order
2782 // to adjust the original input url if needed. For inner frames such as
2783 // fenced frames or subframes, they don't rewrite urls as the urls are not
2784 // input urls by users.
2785 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:322786 absl::optional<GURL> source_process_site_url = absl::nullopt;
2787 if (source_site_instance && source_site_instance->HasProcess()) {
2788 source_process_site_url =
2789 source_site_instance->GetProcess()->GetProcessLock().site_url();
2790 }
clamy987a3752018-05-03 17:36:262791 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212792 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322793 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212794 extra_headers, browser_context_, blob_url_loader_factory,
2795 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262796 entry->root_node()->frame_entry->set_source_site_instance(
2797 static_cast<SiteInstanceImpl*>(source_site_instance));
2798 entry->root_node()->frame_entry->set_method(method);
2799 }
clamy987a3752018-05-03 17:36:262800
Camille Lamy5193caa2018-10-12 11:59:422801 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452802 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262803 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422804 override_user_agent = true;
clamy987a3752018-05-03 17:36:262805 }
2806 // TODO(creis): Set user gesture and intent received timestamp on Android.
2807
2808 // We may not have successfully added the FrameNavigationEntry to |entry|
2809 // above (per https://crbug.com/608402), in which case we create it from
2810 // scratch. This works because we do not depend on |frame_entry| being inside
2811 // |entry| during NavigateToEntry. This will go away when we shortcut this
2812 // further in https://crbug.com/536906.
2813 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2814 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452815 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082816 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582817 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072818 absl::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212819 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto22a27b142023-02-10 06:42:492820 blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482821 nullptr /* subresource_web_bundle_navigation_info */,
Nate Chapin63db0d12022-01-20 22:03:302822 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572823 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262824 }
2825
Camille Lamy5193caa2018-10-12 11:59:422826 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022827 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452828 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292829 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212830 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422831 params.source_site_instance = source_site_instance;
2832 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2833 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032834 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422835 params.referrer = referrer;
2836 /* params.redirect_chain: skip */
2837 params.extra_headers = extra_headers;
2838 params.is_renderer_initiated = is_renderer_initiated;
2839 params.override_user_agent = UA_OVERRIDE_INHERIT;
2840 /* params.base_url_for_data_url: skip */
2841 /* params.virtual_url_for_data_url: skip */
2842 /* params.data_url_as_string: skip */
2843 params.post_data = post_body;
2844 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582845 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422846 /* params.frame_name: skip */
2847 // TODO(clamy): See if user gesture should be propagated to this function.
2848 params.has_user_gesture = false;
2849 params.should_clear_history_list = false;
2850 params.started_from_context_menu = false;
2851 /* params.navigation_ui_data: skip */
2852 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222853 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542854 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212855 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412856 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502857 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292858 params.initiator_activation_and_ad_status =
2859 initiator_activation_and_ad_status;
Camille Lamy5193caa2018-10-12 11:59:422860
2861 std::unique_ptr<NavigationRequest> request =
2862 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032863 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142864 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392865 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492866 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582867 is_unfenced_top_navigation, is_container_initiated,
2868 embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232869
2870 if (!request)
2871 return;
2872
Garrett Tanzerbb8db412022-09-27 21:59:462873 // Force the navigation to take place in a new browsing instance.
2874 // This is used by _unfencedTop in fenced frames to ensure that navigations
2875 // leaving the fenced context create a new browsing instance.
2876 if (force_new_browsing_instance) {
2877 request->coop_status().ForceBrowsingInstanceSwap();
2878 }
2879
Arthur Hemery948742762019-09-18 10:06:242880 // At this stage we are proceeding with this navigation. If this was renderer
2881 // initiated with user gesture, we need to make sure we clear up potential
2882 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2883 DiscardNonCommittedEntries();
2884
Lukasz Anforowicz9ee83c272020-12-01 20:14:052885 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262886}
2887
[email protected]d1198fd2012-08-13 22:50:192888void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252889 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212890 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192891 if (!session_storage_namespace)
2892 return;
2893
2894 // We can't overwrite an existing SessionStorage without violating spec.
2895 // Attempts to do so may give a tab access to another tab's session storage
2896 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152897 bool successful_insert =
2898 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252899 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052900 static_cast<SessionStorageNamespaceImpl*>(
2901 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302902 .second;
2903 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192904}
2905
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572906bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452907 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032908 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462909}
2910
Aran Gilman37d11632019-10-08 23:07:152911SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252912 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302913 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252914 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032915 DOMStorageContextWrapper* context_wrapper =
2916 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2917
2918 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252919 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032920 if (it != session_storage_namespace_map_.end()) {
2921 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152922 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2923 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472924
michaelnbacbcbd2016-02-09 00:32:032925 return it->second.get();
2926 }
2927
2928 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102929 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2930 SessionStorageNamespaceImpl::Create(context_wrapper);
2931 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2932 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252933 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102934 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302935
Daniel Murphy31bbb8b12018-02-07 21:44:102936 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302937}
2938
2939SessionStorageNamespace*
2940NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252941 return GetSessionStorageNamespace(
2942 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302943}
2944
2945const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572946NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302947 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552948}
[email protected]d202a7c2012-01-04 07:53:472949
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572950bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562951 return needs_reload_;
2952}
[email protected]a26023822011-12-29 00:23:552953
[email protected]46bb5e9c2013-10-03 22:16:472954void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412955 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2956}
2957
2958void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472959 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412960 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542961
2962 if (last_committed_entry_index_ != -1) {
2963 entries_[last_committed_entry_index_]->SetTransitionType(
2964 ui::PAGE_TRANSITION_RELOAD);
2965 }
[email protected]46bb5e9c2013-10-03 22:16:472966}
2967
[email protected]d202a7c2012-01-04 07:53:472968void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572969 DCHECK_LT(index, GetEntryCount());
2970 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312971 DiscardNonCommittedEntries();
2972
Nate Chapin9eb16be72022-09-23 22:54:312973 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:312974 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122975 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312976 last_committed_entry_index_--;
2977}
2978
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572979NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272980 // If there is no pending_entry_, there should be no pending_entry_index_.
2981 DCHECK(pending_entry_ || pending_entry_index_ == -1);
2982
2983 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:362984 // at that index. An exception is while a reload of a post commit error page
2985 // is ongoing; in that case pending entry will point to the entry replaced
2986 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:272987 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:362988 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
2989 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:272990
[email protected]022af742011-12-28 18:37:252991 return pending_entry_;
2992}
2993
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572994int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:272995 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:272996 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:552997 return pending_entry_index_;
2998}
2999
avi25764702015-06-23 15:43:373000void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573001 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363002 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313003 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003004 bool in_fenced_frame_tree,
3005 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313006 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3007 // set because:
3008 // 1) They don't influence the history of the outer page.
3009 // 2) They are always replace only navigation (there is always only one entry
3010 // in their history stack).
3011 // 3) Are not top level navigations and appear similar to iframes.
3012 // Navigations of the fenced frame might create a new NavigationEntry, which
3013 // will call this function. Non fenced frame navigations will never have
3014 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3015 // InsertOrReplaceEntry.
3016 DCHECK_EQ(in_fenced_frame_tree,
3017 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3018 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203019
avi5cad4912015-06-19 05:25:443020 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3021 // need to keep continuity with the pending entry, so copy the pending entry's
3022 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3023 // then the renderer navigated on its own, independent of the pending entry,
3024 // so don't copy anything.
3025 if (pending_entry_ && pending_entry_index_ == -1)
3026 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203027
Rakina Zata Amnia4e27222021-12-22 01:05:003028 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203029
creisee17e932015-07-17 17:56:223030 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453031 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103032 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573033 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363034 // If the new entry is a post-commit error page, we store the current last
3035 // committed entry to the side so that we can put it back when navigating
3036 // away from the error.
3037 if (was_post_commit_error) {
3038 DCHECK(!entry_replaced_by_post_commit_error_);
3039 entry_replaced_by_post_commit_error_ =
3040 std::move(entries_[last_committed_entry_index_]);
3041 }
dcheng36b6aec92015-12-26 06:16:363042 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223043 return;
3044 }
[email protected]765b35502008-08-21 00:51:203045
creis37979a62015-08-04 19:48:183046 // We shouldn't see replace == true when there's no committed entries.
3047 DCHECK(!replace);
3048
Michael Thiessen9b14d512019-09-23 21:19:473049 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203050
Shivani Sharmad8c8d652019-02-13 17:27:573051 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203052
dcheng36b6aec92015-12-26 06:16:363053 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203054 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293055}
3056
Shivani Sharmad8c8d652019-02-13 17:27:573057void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163058 if (entries_.size() < max_entry_count())
3059 return;
3060
3061 DCHECK_EQ(max_entry_count(), entries_.size());
3062 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573063 CHECK_EQ(pending_entry_index_, -1);
3064
3065 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423066 // Retrieve the oldest skippable entry.
3067 for (; index < GetEntryCount(); index++) {
3068 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3069 break;
Shivani Sharmad8c8d652019-02-13 17:27:573070 }
3071
3072 // If there is no skippable entry or if it is the last committed entry then
3073 // fall back to pruning the oldest entry. It is not safe to prune the last
3074 // committed entry.
3075 if (index == GetEntryCount() || index == last_committed_entry_index_)
3076 index = 0;
3077
3078 bool should_succeed = RemoveEntryAtIndex(index);
3079 DCHECK_EQ(true, should_succeed);
3080
3081 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253082}
3083
clamy3cb9bea92018-07-10 12:42:023084void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163085 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203086 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:133087 absl::optional<blink::scheduler::TaskAttributionId>
3088 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203089 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503090 TRACE_EVENT0("navigation",
3091 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273092 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023093 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363094 if (pending_entry_index_ != -1) {
3095 // The pending entry may not be in entries_ if a post-commit error page is
3096 // showing.
3097 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3098 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3099 }
Gyuyoung Kim107c2a02021-04-13 01:49:303100 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573101 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013102 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033103 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573104 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133105 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3106 // the same as the top level frame being navigated.
3107 if (root->current_frame_host() != initiator_rfh) {
3108 soft_navigation_heuristics_task_id = absl::nullopt;
3109 }
Arthur Sonzogni620cec62018-12-13 13:08:573110
[email protected]83c2e232011-10-07 21:36:463111 // If we were navigating to a slow-to-commit page, and the user performs
3112 // a session history navigation to the last committed page, RenderViewHost
3113 // will force the throbber to start, but WebKit will essentially ignore the
3114 // navigation, and won't send a message to stop the throbber. To prevent this
3115 // from happening, we drop the navigation here and stop the slow-to-commit
3116 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023117 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083118 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273119 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033120 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123121
[email protected]83c2e232011-10-07 21:36:463122 DiscardNonCommittedEntries();
3123 return;
3124 }
3125
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333126 absl::optional<blink::LocalFrameToken> initiator_frame_token;
3127 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3128 if (initiator_rfh) {
3129 initiator_frame_token = initiator_rfh->GetFrameToken();
3130 initiator_process_id = initiator_rfh->GetProcess()->GetID();
3131 DCHECK(initiator_frame_token);
3132 }
3133
creisce0ef3572017-01-26 17:53:083134 // Compare FrameNavigationEntries to see which frames in the tree need to be
3135 // navigated.
clamy3cb9bea92018-07-10 12:42:023136 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3137 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333138 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3139 initiator_process_id, soft_navigation_heuristics_task_id,
3140 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303141
3142 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573143 // We were unable to match any frames to navigate. This can happen if a
3144 // history navigation targets a subframe that no longer exists
3145 // (https://crbug.com/705550). In this case, we need to update the current
3146 // history entry to the pending one but keep the main document loaded. We
3147 // also need to ensure that observers are informed about the updated
3148 // current history entry (e.g., for greying out back/forward buttons), and
3149 // that renderer processes update their history offsets. The easiest way
3150 // to do all that is to schedule a "redundant" same-document navigation in
3151 // the main frame.
3152 //
3153 // Note that we don't want to remove this history entry, as it might still
3154 // be valid later, since a frame that it's targeting may be recreated.
3155 //
3156 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3157 // need to repeat history navigations until finding the one that works.
3158 // Consider changing this behavior to keep looking for the first valid
3159 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023160 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423161 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573162 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573163 ReloadType::NONE /* reload_type */,
3164 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433165 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333166 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023167 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573168 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023169 DiscardPendingEntry(false);
3170 return;
3171 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573172 same_document_loads.push_back(std::move(navigation_request));
3173
3174 // Sanity check that we never take this branch for any kinds of reloads,
3175 // as those should've queued a different-document load in the main frame.
3176 DCHECK(!is_forced_reload);
3177 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303178 }
3179
Nate Chapinbf682fa32022-09-26 22:41:203180 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163181 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203182 if (initiator_rfh && initiator_rfh->IsSandboxed(
3183 network::mojom::WebSandboxFlags::kTopNavigation)) {
3184 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3185 initiator_rfh, same_document_loads) &&
3186 DoesSandboxNavigationStayWithinSubtree(
3187 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503188 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163189 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203190 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3191 initiator_rfh,
3192 navigates_inside_tree
3193 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3194 : blink::mojom::WebFeature::
3195 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523196
3197 // If the navigation occurred outside the tree discard it because
3198 // the sandboxed frame didn't have permission to navigate outside
3199 // its tree. If it is possible that the navigation is both inside and
3200 // outside the frame tree and we discard it entirely because we don't
3201 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143202 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203203 // If a |navigation_api_key| was provided, this navigation originated from
3204 // the navigation API. Notify the renderer that the navigation was
3205 // cancelled so the navigation API can fire an error event and reject the
3206 // relevant promise.
3207 if (navigation_api_key) {
3208 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3209 *navigation_api_key,
3210 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3211 }
Dave Tapuska855c1e12019-08-23 20:45:523212 DiscardPendingEntry(false);
3213 return;
3214 }
Dave Tapuska8bfd84c2019-03-26 20:47:163215 }
3216
Nate Chapin6c43c022023-02-13 23:32:423217 // If it is possible that this traverse may involve a same-document navigation
3218 // in the initiator and there is a Navigation API key involved, then we may
3219 // need to notify the initiator if it fails. (The early returns above either
3220 // do not involve these cases or already notify the initiator.)
3221 // The event only needs to fire for the initiator, and only if the initiator
3222 // itself is performing a same-document navigation (because the event will not
3223 // fire if it navigates cross-document).
3224 if (navigation_api_key) {
3225 for (auto& item : same_document_loads) {
3226 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3227 item->set_pending_navigation_api_key(*navigation_api_key);
3228 break;
3229 }
3230 }
3231 }
3232
Carlos Caballero539a421c2020-07-06 10:25:573233 // BackForwardCache:
3234 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563235 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573236 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3237 DCHECK_EQ(reload_type, ReloadType::NONE);
3238 auto navigation_request = CreateNavigationRequestFromEntry(
3239 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3240 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333241 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3242 initiator_process_id);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053243 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573244
3245 return;
3246 }
3247
3248 // History navigation might try to reuse a specific BrowsingInstance, already
3249 // used by a page in the cache. To avoid having two different main frames that
3250 // live in the same BrowsingInstance, evict the all pages with this
3251 // BrowsingInstance from the cache.
3252 //
3253 // For example, take the following scenario:
3254 //
3255 // A1 = Some page on a.com
3256 // A2 = Some other page on a.com
3257 // B3 = An uncacheable page on b.com
3258 //
3259 // Then the following navigations occur:
3260 // A1->A2->B3->A1
3261 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3262 // take its place) and A1 will be created in the same BrowsingInstance (and
3263 // SiteInstance), as A2.
3264 //
3265 // If we didn't do anything, both A1 and A2 would remain alive in the same
3266 // BrowsingInstance/SiteInstance, which is unsupported by
3267 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3268 // A2 from the cache.
3269 if (pending_entry_->site_instance()) {
3270 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3271 pending_entry_->site_instance());
3272 }
3273
Rakina Zata Amnid605d462022-06-01 10:17:033274 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3275 pending_entry_ && pending_entry_->IsRestored());
3276 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3277 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3278 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3279 pending_entry_index_);
3280 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3281 last_committed_entry_index_);
3282 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3283 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3284 pending_entry_ && pending_entry_->IsInitialEntry());
3285 SCOPED_CRASH_KEY_BOOL(
3286 "nav_reentrancy", "pending_entry_initial2",
3287 pending_entry_ &&
3288 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3289 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3290 IsInitialNavigation());
3291 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3292 IsInitialBlankNavigation());
3293 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3294 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3295 (int)pending_reload_);
3296
clamy3cb9bea92018-07-10 12:42:023297 // This call does not support re-entrancy. See http://crbug.com/347742.
3298 CHECK(!in_navigate_to_pending_entry_);
3299 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303300
Rakina Zata Amnid605d462022-06-01 10:17:033301 // If the navigation-reentrancy is caused by calling
3302 // NavigateToExistingPendingEntry twice, this will note the previous call's
3303 // pending entry's ID.
3304 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3305 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3306
arthursonzogni66f711c2019-10-08 14:40:363307 // It is not possible to delete the pending NavigationEntry while navigating
3308 // to it. Grab a reference to delay potential deletion until the end of this
3309 // function.
3310 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3311
Nate Chapin154b14b2023-02-17 18:28:163312 // If there is a main-frame same-document history navigation, we may defer
3313 // the subframe history navigations in order to give JS in the main frame the
3314 // opportunity to cancel the entire traverse via the navigate event. In that
3315 // case, we need to stash the main frame request's navigation token on the
3316 // subframes, so they can look up the main frame request and defer themselves
3317 // until it completes.
3318 if (!same_document_loads.empty() &&
3319 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3320 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3321 // The token will only be returned in cases where deferring the navigation
3322 // is necessary.
3323 if (auto main_frame_same_document_token =
3324 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3325 for (auto& item : same_document_loads) {
3326 if (item.get() != main_frame_request) {
3327 item->set_main_frame_same_document_history_token(
3328 main_frame_same_document_token);
3329 }
3330 }
3331 for (auto& item : different_document_loads) {
3332 item->set_main_frame_same_document_history_token(
3333 main_frame_same_document_token);
3334 }
3335 }
3336 }
3337
creis4e2ecb72015-06-20 00:46:303338 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023339 for (auto& item : same_document_loads) {
3340 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053341 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303342 }
clamy3cb9bea92018-07-10 12:42:023343 for (auto& item : different_document_loads) {
3344 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053345 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303346 }
clamy3cb9bea92018-07-10 12:42:023347
3348 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303349}
3350
Alex Moshchuk3a4e77a2020-05-29 21:32:573351NavigationControllerImpl::HistoryNavigationAction
3352NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303353 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573354 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423355 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583356 // Only active and prerendered documents are allowed to navigate in their
3357 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423358 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013359 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583360 // - If the document is in pending deletion, the browser already committed
3361 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3362 // - If the document is in back-forward cache, it's not allowed to navigate
3363 // as it should remain frozen. Ignore the request and evict the document
3364 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423365 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583366 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423367 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113368 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3369 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423370 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113371 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423372 }
arthursonzogni03f76152019-02-12 10:35:203373
Alex Moshchuk3a4e77a2020-05-29 21:32:573374 // Reloads should result in a different-document load. Note that reloads may
3375 // also happen via the |needs_reload_| mechanism where the reload_type is
3376 // NONE, so detect this by comparing whether we're going to the same
3377 // entry that we're currently on. Similarly to above, only main frames
3378 // should reach this. Note that subframes support reloads, but that's done
3379 // via a different path that doesn't involve FindFramesToNavigate (see
3380 // RenderFrameHost::Reload()).
3381 if (reload_type != ReloadType::NONE ||
3382 pending_entry_index_ == last_committed_entry_index_) {
3383 DCHECK(frame->IsMainFrame());
3384 return HistoryNavigationAction::kDifferentDocument;
3385 }
3386
Alex Moshchuk47d1a4bd2020-06-01 22:15:343387 // If there is no new FrameNavigationEntry for the frame, ignore the
3388 // load. For example, this may happen when going back to an entry before a
3389 // frame was created. Suppose we commit a same-document navigation that also
3390 // results in adding a new subframe somewhere in the tree. If we go back,
3391 // the new subframe will be missing a FrameNavigationEntry in the previous
3392 // NavigationEntry, but we shouldn't delete or change what's loaded in
3393 // it.
3394 //
Alex Moshchuke65c39272020-06-03 17:55:373395 // Note that in this case, there is no need to keep looking for navigations
3396 // in subframes, which would be missing FrameNavigationEntries as well.
3397 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343398 // It's important to check this before checking |old_item| below, since both
3399 // might be null, and in that case we still shouldn't change what's loaded in
3400 // this frame. Note that scheduling any loads assumes that |new_item| is
3401 // non-null. See https://crbug.com/1088354.
3402 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3403 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373404 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343405
Charlie Reisa474fb62022-03-17 02:31:363406 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3407 // which history item it is currently on, since this may be different than the
3408 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3409 // (e.g., if a history navigation is targeting multiple frames and only some
3410 // have committed so far).
creis4e2ecb72015-06-20 00:46:303411 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363412 frame->current_frame_host()->last_committed_frame_entry();
3413 if (!old_item) {
3414 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3415 // fall back to the last committed NavigationEntry's record for this frame.
3416 // This may happen in cases like the initial state of the RenderFrameHost.
3417 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3418 // accurate FrameNavigationEntry and eliminate this case.
3419 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3420 }
3421 // If neither approach finds a FrameNavigationEntry, schedule a
3422 // different-document load.
3423 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573424 if (!old_item)
3425 return HistoryNavigationAction::kDifferentDocument;
3426
Alex Moshchuk3a4e77a2020-05-29 21:32:573427 // If the new item is not in the same SiteInstance, schedule a
3428 // different-document load. Newly restored items may not have a SiteInstance
3429 // yet, in which case it will be assigned on first commit.
3430 if (new_item->site_instance() &&
3431 new_item->site_instance() != old_item->site_instance())
3432 return HistoryNavigationAction::kDifferentDocument;
3433
3434 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313435 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3436 // that we do this even if the history navigation would not be modifying this
3437 // frame were it live.
3438 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573439 return HistoryNavigationAction::kDifferentDocument;
3440
3441 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313442 // Starting a navigation after a crash early-promotes the speculative
3443 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3444 // committed yet, so we can not possibly perform a same-document history
3445 // navigation. The frame would need to be reloaded with a cross-document
3446 // navigation.
3447 if (!frame->current_frame_host()->has_committed_any_navigation())
3448 return HistoryNavigationAction::kDifferentDocument;
3449
creis54131692016-08-12 18:32:253450 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493451 // sequence number but different item sequence number.
3452 if (new_item->document_sequence_number() ==
3453 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573454 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493455 }
avib48cb312016-05-05 21:35:003456
Alex Moshchuk3a4e77a2020-05-29 21:32:573457 // Otherwise, if both item and document sequence numbers differ, this
3458 // should be a different document load.
3459 return HistoryNavigationAction::kDifferentDocument;
3460 }
3461
3462 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373463 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573464 DCHECK_EQ(new_item->document_sequence_number(),
3465 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373466 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573467}
3468
3469void NavigationControllerImpl::FindFramesToNavigate(
3470 FrameTreeNode* frame,
3471 ReloadType reload_type,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333472 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
3473 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133474 absl::optional<blink::scheduler::TaskAttributionId>
3475 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573476 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3477 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3478 DCHECK(pending_entry_);
3479 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3480
3481 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3482
3483 if (action == HistoryNavigationAction::kSameDocument) {
3484 std::unique_ptr<NavigationRequest> navigation_request =
3485 CreateNavigationRequestFromEntry(
3486 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133487 /*is_same_document_history_load=*/true,
3488 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333489 initiator_frame_token, initiator_process_id,
3490 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573491 if (navigation_request) {
3492 // Only add the request if was properly created. It's possible for the
3493 // creation to fail in certain cases, e.g. when the URL is invalid.
3494 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303495 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573496 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473497 std::unique_ptr<NavigationRequest> navigation_request =
3498 CreateNavigationRequestFromEntry(
3499 frame, pending_entry_, new_item, reload_type,
3500 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433501 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333502 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473503 if (navigation_request) {
3504 // Only add the request if was properly created. It's possible for the
3505 // creation to fail in certain cases, e.g. when the URL is invalid.
3506 different_document_loads->push_back(std::move(navigation_request));
3507 }
3508 // For a different document, the subframes will be destroyed, so there's
3509 // no need to consider them.
3510 return;
Alex Moshchuke65c39272020-06-03 17:55:373511 } else if (action == HistoryNavigationAction::kStopLooking) {
3512 return;
creis4e2ecb72015-06-20 00:46:303513 }
3514
Yoav Weiss8c573952022-11-17 17:35:133515 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3516 // we currently only support soft navigation heuristics for the top level
3517 // frame.
creis4e2ecb72015-06-20 00:46:303518 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333519 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3520 initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:133521 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
Nate Chapin45f620582021-09-30 17:45:433522 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303523 }
3524}
3525
Harkiran Bolariaba823e42021-05-21 18:30:363526base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243527 const LoadURLParams& params) {
3528 // Find the appropriate FrameTreeNode.
3529 FrameTreeNode* node = nullptr;
3530 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3531 !params.frame_name.empty()) {
3532 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033533 ? frame_tree_->FindByID(params.frame_tree_node_id)
3534 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503535 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243536 }
3537
3538 // If no FrameTreeNode was specified, navigate the main frame.
3539 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033540 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243541
Camille Lamy5193caa2018-10-12 11:59:423542 // Compute overrides to the LoadURLParams for |override_user_agent|,
3543 // |should_replace_current_entry| and |has_user_gesture| that will be used
3544 // both in the creation of the NavigationEntry and the NavigationRequest.
3545 // Ideally, the LoadURLParams themselves would be updated, but since they are
3546 // passed as a const reference, this is not possible.
3547 // TODO(clamy): When we only create a NavigationRequest, move this to
3548 // CreateNavigationRequestFromLoadURLParams.
3549 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3550 GetLastCommittedEntry());
3551
Rakina Zata Amnie2d31312022-11-18 03:38:453552 // An entry replacement must happen if the current browsing context should
3553 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333554 bool should_replace_current_entry =
3555 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453556 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423557
clamy21718cc22018-06-13 13:34:243558 // Javascript URLs should not create NavigationEntries. All other navigations
3559 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243560 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373561 std::unique_ptr<NavigationEntryImpl> entry =
3562 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3563 should_replace_current_entry,
3564 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243565 DiscardPendingEntry(false);
3566 SetPendingEntry(std::move(entry));
3567 }
3568
Tim Judkins59548192023-05-17 17:51:203569 // Renderer-debug URLs are sent to the current renderer process immediately
3570 // for processing and don't need to create a NavigationRequest. Note: this
3571 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243572 // renderer-debug URLs.
3573 // Note: we intentionally leave the pending entry in place for renderer debug
3574 // URLs, unlike the cases below where we clear it if the navigation doesn't
3575 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303576 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483577 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3578 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153579 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203580 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483581 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363582 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483583 }
3584
clamy21718cc22018-06-13 13:34:243585 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363586 return nullptr;
clamy21718cc22018-06-13 13:34:243587 }
3588
Antonio Sartori78a749f2020-11-30 12:03:393589 DCHECK(pending_entry_);
3590
clamy21718cc22018-06-13 13:34:243591 // Convert navigations to the current URL to a reload.
3592 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3593 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3594 // DevTools sometimes issues navigations to main frames that they do not
3595 // expect to see treated as reload, and it only works because they pass a
3596 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3597 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543598 ReloadType reload_type = params.reload_type;
3599 if (reload_type == ReloadType::NONE &&
3600 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043601 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243602 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243603 params.load_type ==
3604 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543605 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243606 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473607 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393608
3609 // If this is a reload of an existing FrameNavigationEntry and we had a
3610 // policy container for it, then we should copy it into the pending entry,
3611 // so that it is copied to the navigation request in
3612 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453613 FrameNavigationEntry* previous_frame_entry =
3614 GetLastCommittedEntry()->GetFrameEntry(node);
3615 if (previous_frame_entry &&
3616 previous_frame_entry->policy_container_policies()) {
3617 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3618 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393619 }
3620 }
3621
3622 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173623 // document, then we should copy the document polices from RenderFrameHost's
3624 // PolicyContainerHost. The NavigationRequest will create a new
3625 // PolicyContainerHost with the document policies from the |pending_entry_|,
3626 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3627 // the navigation. This way, we ensure that we keep enforcing the right
3628 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453629 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393630 if (node->current_frame_host() &&
3631 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193632 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163633 node->current_frame_host()
3634 ->policy_container_host()
3635 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233636 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393637 }
clamy21718cc22018-06-13 13:34:243638 }
3639
3640 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263641 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243642
Tsuyoshi Horo167ca6432022-03-09 05:16:393643 // This will be used to set the Navigation Timing API navigationStart
3644 // parameter for browser navigations in new tabs (intents, tabs opened through
3645 // "Open link in new tab"). If the navigation must wait on the current
3646 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3647 // will be updated when the BeforeUnload ack is received.
3648 const auto navigation_start_time = base::TimeTicks::Now();
3649
Camille Lamy5193caa2018-10-12 11:59:423650 std::unique_ptr<NavigationRequest> request =
3651 CreateNavigationRequestFromLoadParams(
3652 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143653 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393654 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3655 navigation_start_time);
clamy21718cc22018-06-13 13:34:243656
3657 // If the navigation couldn't start, return immediately and discard the
3658 // pending NavigationEntry.
3659 if (!request) {
3660 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363661 return nullptr;
clamy21718cc22018-06-13 13:34:243662 }
3663
Camille Lamy5193caa2018-10-12 11:59:423664#if DCHECK_IS_ON()
3665 // Safety check that NavigationRequest and NavigationEntry match.
3666 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3667#endif
3668
clamy21718cc22018-06-13 13:34:243669 // This call does not support re-entrancy. See http://crbug.com/347742.
3670 CHECK(!in_navigate_to_pending_entry_);
3671 in_navigate_to_pending_entry_ = true;
3672
arthursonzogni66f711c2019-10-08 14:40:363673 // It is not possible to delete the pending NavigationEntry while navigating
3674 // to it. Grab a reference to delay potential deletion until the end of this
3675 // function.
3676 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3677
Harkiran Bolariaba823e42021-05-21 18:30:363678 base::WeakPtr<NavigationHandle> created_navigation_handle(
3679 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053680 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243681
3682 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363683 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243684}
3685
clamyea99ea12018-05-28 13:54:233686void NavigationControllerImpl::HandleRendererDebugURL(
3687 FrameTreeNode* frame_tree_node,
3688 const GURL& url) {
3689 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243690 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3691 // the renderer process is not live, unless it is the initial navigation
3692 // of the tab.
clamyea99ea12018-05-28 13:54:233693 if (!IsInitialNavigation()) {
3694 DiscardNonCommittedEntries();
3695 return;
3696 }
Fergal Dalyecd3b0202020-06-25 01:57:373697 // The current frame is always a main frame. If IsInitialNavigation() is
3698 // true then there have been no navigations and any frames of this tab must
3699 // be in the same renderer process. If that has crashed then the only frame
3700 // that can be revived is the main frame.
3701 frame_tree_node->render_manager()
3702 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233703 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223704
3705 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3706 // notification, so set is loading to true here to properly surface it when
3707 // the renderer process is done handling the URL.
3708 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3709 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223710 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223711 }
clamyea99ea12018-05-28 13:54:233712 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3713}
3714
clamy21718cc22018-06-13 13:34:243715std::unique_ptr<NavigationEntryImpl>
3716NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3717 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423718 const LoadURLParams& params,
3719 bool override_user_agent,
3720 bool should_replace_current_entry,
3721 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393722 // Browser initiated navigations might not have a blob_url_loader_factory set
3723 // in params even if the navigation is to a blob URL. If that happens, lookup
3724 // the correct url loader factory to use here.
3725 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483726 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473727 // Resolve the blob URL in the storage partition associated with the target
3728 // frame. This is the storage partition the URL will be loaded in, and only
3729 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393730 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473731 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393732 }
3733
clamy21718cc22018-06-13 13:34:243734 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443735 // extra_headers in params are \n separated; navigation entries want \r\n.
3736 std::string extra_headers_crlf;
3737 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243738
3739 // For subframes, create a pending entry with a corresponding frame entry.
3740 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453741 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243742 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083743 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243744 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073745 params.url, absl::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213746 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3747 "GET", -1, blob_url_loader_factory,
Kunihiko Sakamoto346a74e2021-03-10 08:57:483748 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori78a749f2020-11-30 12:03:393749 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163750 // a conversion of a new navigation into a reload, we will set the right
3751 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193752 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243753 } else {
3754 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173755 // If `node` is the outermost main frame, it rewrites a virtual url in order
3756 // to adjust the original input url if needed. For inner frames such as
3757 // fenced frames or subframes, they don't rewrite urls as the urls are not
3758 // input urls by users.
3759 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323760 scoped_refptr<SiteInstance> source_site_instance =
3761 params.source_site_instance;
3762 absl::optional<GURL> source_process_site_url = absl::nullopt;
3763 if (source_site_instance && source_site_instance->HasProcess()) {
3764 source_process_site_url =
3765 source_site_instance->GetProcess()->GetProcessLock().site_url();
3766 }
clamy21718cc22018-06-13 13:34:243767 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063768 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323769 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213770 params.transition_type, params.is_renderer_initiated,
3771 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3772 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243773 entry->set_source_site_instance(
3774 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3775 entry->SetRedirectChain(params.redirect_chain);
3776 }
3777
3778 // Set the FTN ID (only used in non-site-per-process, for tests).
3779 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243780 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423781 entry->SetIsOverridingUserAgent(override_user_agent);
3782 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543783 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243784
clamy21718cc22018-06-13 13:34:243785 switch (params.load_type) {
3786 case LOAD_TYPE_DEFAULT:
3787 break;
3788 case LOAD_TYPE_HTTP_POST:
3789 entry->SetHasPostData(true);
3790 entry->SetPostData(params.post_data);
3791 break;
3792 case LOAD_TYPE_DATA:
3793 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3794 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283795#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243796 entry->SetDataURLAsString(params.data_url_as_string);
3797#endif
3798 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3799 break;
clamy21718cc22018-06-13 13:34:243800 }
3801
3802 // TODO(clamy): NavigationEntry is meant for information that will be kept
3803 // after the navigation ended and therefore is not appropriate for
3804 // started_from_context_menu. Move started_from_context_menu to
3805 // NavigationUIData.
3806 entry->set_started_from_context_menu(params.started_from_context_menu);
3807
3808 return entry;
3809}
3810
clamyea99ea12018-05-28 13:54:233811std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423812NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3813 FrameTreeNode* node,
3814 const LoadURLParams& params,
3815 bool override_user_agent,
3816 bool should_replace_current_entry,
3817 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143818 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423819 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573820 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393821 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223822 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493823 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453824 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583825 bool is_container_initiated,
3826 absl::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573827 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283828 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533829 // All renderer-initiated navigations must have an initiator_origin.
3830 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513831
Camille Lamy5193caa2018-10-12 11:59:423832 GURL url_to_load;
3833 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323834
Camille Lamy2baa8022018-10-19 16:43:173835 // For main frames, rewrite the URL if necessary and compute the virtual URL
3836 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263837 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423838 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173839 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423840 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423841
Camille Lamy2baa8022018-10-19 16:43:173842 // For DATA loads, override the virtual URL.
3843 if (params.load_type == LOAD_TYPE_DATA)
3844 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423845
Camille Lamy2baa8022018-10-19 16:43:173846 if (virtual_url.is_empty())
3847 virtual_url = url_to_load;
3848
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573849 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283850
Aran Gilman249eb122019-12-02 23:32:463851 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3852 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3853 // return different results, leading to a different URL in the
3854 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3855 // pending NavigationEntry, as we'll only make one call to
3856 // RewriteUrlForNavigation.
3857 VLOG_IF(1, (url_to_load != frame_entry->url()))
3858 << "NavigationRequest and FrameEntry have different URLs: "
3859 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283860
Camille Lamy2baa8022018-10-19 16:43:173861 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423862 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173863 // NavigationRequest.
3864 } else {
3865 url_to_load = params.url;
3866 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243867 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173868 }
Camille Lamy5193caa2018-10-12 11:59:423869
Ehsan Karamad44fc72112019-02-26 18:15:473870 if (node->render_manager()->is_attaching_inner_delegate()) {
3871 // Avoid starting any new navigations since this node is now preparing for
3872 // attaching an inner delegate.
3873 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203874 }
Camille Lamy5193caa2018-10-12 11:59:423875
Ian Vollick1c6dd3e2022-04-13 02:06:263876 if (!IsValidURLForNavigation(node->IsOutermostMainFrame(), virtual_url,
3877 url_to_load))
Camille Lamy5193caa2018-10-12 11:59:423878 return nullptr;
3879
danakjd83d706d2020-11-25 22:11:123880 // Look for a pending commit that is to another document in this
3881 // FrameTreeNode. If one exists, then the last committed URL will not be the
3882 // current URL by the time this navigation commits.
3883 bool has_pending_cross_document_commit =
3884 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213885 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123886
Minggang Wangb9f3fa92021-07-01 15:30:313887 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493888 /*old_url=*/node->current_url(),
3889 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3890 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133891 /*is_same_document_history_load=*/false,
3892 is_embedder_initiated_fenced_frame_navigation,
3893 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423894
3895 // Create the NavigationParams based on |params|.
3896
Hiroki Nakagawa4ed61282021-06-18 05:37:233897 bool is_view_source_mode = entry->IsViewSourceMode();
3898 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293899
Antonio Sartori6984c742021-08-26 08:03:413900 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:293901
Hiroki Nakagawa4ed61282021-06-18 05:37:233902 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293903 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253904 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293905
Minggang Wangb9f3fa92021-07-01 15:30:313906 blink::mojom::CommonNavigationParamsPtr common_params =
3907 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:213908 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513909 blink::mojom::Referrer::New(params.referrer.url,
3910 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213911 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513912 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393913 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513914 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143915 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413916 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273917 false /* has_text_fragment_token */,
3918 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3919 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513920 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:053921 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423922
Minggang Wangb9f3fa92021-07-01 15:30:313923 blink::mojom::CommitNavigationParamsPtr commit_params =
3924 blink::mojom::CommitNavigationParams::New(
Rakina Zata Amnic7367852022-11-07 17:10:403925 absl::nullopt,
Ari Chivukula43d2cf82023-01-24 03:16:073926 // The correct storage key and session storage key will be computed
3927 // before committing the navigation.
3928 blink::StorageKey(), blink::StorageKey(), override_user_agent,
3929 params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323930 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503931 std::vector<net::RedirectInfo>(), params.post_content_type,
3932 common_params->url, common_params->method,
3933 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313934 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133935 entry->GetSubframeUniqueNames(node),
3936 /*intended_as_new_entry=*/true,
3937 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143938 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3939 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:133940 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313941 params.should_clear_history_list,
3942 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223943 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:133944 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:513945 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283946#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:133947 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143948#endif
Yoav Weiss8c573952022-11-17 17:35:133949 /*is_browser_initiated=*/!params.is_renderer_initiated,
Yoav Weiss8c573952022-11-17 17:35:133950 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:073951 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133952 /*force_enabled_origin_trials=*/std::vector<std::string>(),
3953 /*origin_agent_cluster=*/false,
3954 /*origin_agent_cluster_left_as_default=*/true,
3955 /*enabled_client_hints=*/
3956 std::vector<network::mojom::WebClientHintsType>(),
3957 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
3958 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:013959 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:133960 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:583961 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:133962 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:133963 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:283964 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:133965 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:443966 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:423967 network::mojom::NavigationDeliveryType::kDefault,
Yoav Weiss8c573952022-11-17 17:35:133968 /*view_transition_state=*/absl::nullopt,
sbinglera07ae732022-12-02 20:49:053969 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
3970 /*modified_runtime_features=*/
Garrett Tanzer29de7112022-12-06 21:26:323971 base::flat_map<::blink::mojom::RuntimeFeatureState, bool>(),
Yuzu Saijo29f96ca92022-12-08 04:54:123972 /*fenced_frame_properties=*/absl::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:053973 /*not_restored_reasons=*/nullptr,
3974 /*load_with_storage_access=*/false);
Xiaohan Wang7f8052e02022-01-14 18:44:283975#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423976 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143977 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423978 }
3979#endif
3980
Lucas Furukawa Gadania9c45682019-07-31 22:05:143981 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:073982 commit_params->navigation_timing->system_entropy_at_navigation_start =
3983 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
3984 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:423985
Camille Lamy5193caa2018-10-12 11:59:423986 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3987 std::string extra_headers_crlf;
3988 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:093989
Alex Moshchuk9321e6a2022-12-07 21:58:313990 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143991 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:083992 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:093993 params.initiator_frame_token, params.initiator_process_id,
3994 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:213995 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:293996 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:453997 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583998 is_container_initiated, embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:093999 navigation_request->set_from_download_cross_origin_redirect(
4000 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554001 navigation_request->set_force_new_browsing_instance(
4002 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:094003 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424004}
4005
4006std::unique_ptr<NavigationRequest>
4007NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234008 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574009 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234010 FrameNavigationEntry* frame_entry,
4011 ReloadType reload_type,
4012 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434013 bool is_history_navigation_in_new_child_frame,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334014 const absl::optional<blink::LocalFrameToken>& initiator_frame_token,
4015 int initiator_process_id,
Yoav Weiss8c573952022-11-17 17:35:134016 absl::optional<blink::scheduler::TaskAttributionId>
4017 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344018 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234019 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434020 // We should never navigate to an existing initial NavigationEntry that is the
4021 // initial NavigationEntry for the initial empty document that hasn't been
4022 // overridden by the synchronous about:blank commit, to preserve previous
4023 // behavior where trying to reload when the main frame is on the initial empty
4024 // document won't result in a navigation.
4025 // See also https://crbug.com/1277414.
4026 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324027
clamyea99ea12018-05-28 13:54:234028 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:014029 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574030 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:234031 // We may have been redirected when navigating to the current URL.
4032 // Use the URL the user originally intended to visit as signaled by the
4033 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:014034 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574035 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:234036 dest_referrer = Referrer();
clamyea99ea12018-05-28 13:54:234037 }
4038
Ehsan Karamad44fc72112019-02-26 18:15:474039 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4040 // Avoid starting any new navigations since this node is now preparing for
4041 // attaching an inner delegate.
4042 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204043 }
4044
Ian Vollick1c6dd3e2022-04-13 02:06:264045 if (!IsValidURLForNavigation(frame_tree_node->IsOutermostMainFrame(),
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574046 entry->GetVirtualURL(), dest_url)) {
clamyea99ea12018-05-28 13:54:234047 return nullptr;
4048 }
4049
clamyea99ea12018-05-28 13:54:234050 // This will be used to set the Navigation Timing API navigationStart
4051 // parameter for browser navigations in new tabs (intents, tabs opened through
4052 // "Open link in new tab"). If the navigation must wait on the current
4053 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4054 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074055
clamyea99ea12018-05-28 13:54:234056 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074057 const auto navigation_start_system_entropy =
4058 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4059 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234060
danakjd83d706d2020-11-25 22:11:124061 // Look for a pending commit that is to another document in this
4062 // FrameTreeNode. If one exists, then the last committed URL will not be the
4063 // current URL by the time this navigation commits.
4064 bool has_pending_cross_document_commit =
4065 frame_tree_node->render_manager()
4066 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494067 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214068 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124069
Minggang Wangb9f3fa92021-07-01 15:30:314070 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124071 /*old_url=*/frame_tree_node->current_url(),
4072 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:494073 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494074 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134075 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494076 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424077
4078 // A form submission may happen here if the navigation is a
4079 // back/forward/reload navigation that does a form resubmission.
4080 scoped_refptr<network::ResourceRequestBody> request_body;
4081 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:504082 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
4083 // entry. This way, it could be directly retrieved here. Right now, it is only
4084 // partially recovered when request.method == "POST" and request.body exists.
4085 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424086 if (frame_entry->method() == "POST") {
4087 request_body = frame_entry->GetPostData(&post_content_type);
4088 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304089 post_content_type = std::string(
4090 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504091 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424092 }
4093
4094 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314095 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514096 entry->ConstructCommonNavigationParams(
4097 *frame_entry, request_body, dest_url,
4098 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384099 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534100 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514101 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554102 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424103
4104 // TODO(clamy): |intended_as_new_entry| below should always be false once
4105 // Reload no longer leads to this being called for a pending NavigationEntry
4106 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314107 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144108 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404109 *frame_entry, common_params->url, common_params->method,
4110 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144111 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534112 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484113 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134114 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074115 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144116 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074117 commit_params->navigation_timing->system_entropy_at_navigation_start =
4118 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4119 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Camille Lamy5193caa2018-10-12 11:59:424120
W. James MacLeanb7d6092682022-10-05 15:23:264121 if (common_params->url.IsAboutSrcdoc()) {
4122 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4123 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594124 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264125 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334126 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314127 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144128 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434129 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334130 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4131 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
4132 absl::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294133 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4134 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474135 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234136}
4137
[email protected]d202a7c2012-01-04 07:53:474138void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214139 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274140 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404141
Takashi Toyoshimaea534ef22021-07-21 03:27:594142 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404143 // location bar will have up-to-date information about the security style
4144 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134145 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404146
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374147 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574148 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:464149
[email protected]b0f724c2013-09-05 04:21:134150 // TODO(avi): Remove. http://crbug.com/170921
4151 NotificationDetails notification_details =
4152 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154153 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4154 Source<NavigationController>(this),
4155 notification_details);
initial.commit09911bf2008-07-26 23:55:294156}
4157
initial.commit09911bf2008-07-26 23:55:294158// static
[email protected]d202a7c2012-01-04 07:53:474159size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234160 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154161 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214162 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234163}
4164
[email protected]d202a7c2012-01-04 07:53:474165void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224166 if (is_active && needs_reload_)
4167 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294168}
4169
[email protected]d202a7c2012-01-04 07:53:474170void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034171 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4172 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294173 if (!needs_reload_)
4174 return;
4175
Bo Liucdfa4b12018-11-06 00:21:444176 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4177 needs_reload_type_);
4178
initial.commit09911bf2008-07-26 23:55:294179 // Calling Reload() results in ignoring state, and not loading.
4180 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4181 // cached state.
avicc872d7242015-08-19 21:26:344182 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134183 NavigateToExistingPendingEntry(
4184 ReloadType::NONE,
4185 /*initiator_rfh=*/nullptr,
4186 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4187 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454188 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434189 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274190 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344191 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134192 NavigateToExistingPendingEntry(
4193 ReloadType::NONE,
4194 /*initiator_rfh=*/nullptr,
4195 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4196 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344197 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434198 // We should never navigate to an existing initial NavigationEntry that is
4199 // the initial NavigationEntry for the initial empty document that hasn't
4200 // been overridden by the synchronous about:blank commit, to preserve
4201 // legacy behavior where trying to reload when the main frame is on the
4202 // initial empty document won't result in a navigation. See also
4203 // https://crbug.com/1277414. If there is something to reload, the
4204 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4205 // it here.
avicc872d7242015-08-19 21:26:344206 needs_reload_ = false;
4207 }
initial.commit09911bf2008-07-26 23:55:294208}
4209
Kevin McNeeccca6172021-10-19 17:11:144210base::WeakPtr<NavigationHandle>
4211NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364212 RenderFrameHost* render_frame_host,
4213 const GURL& url,
4214 const std::string& error_page_html,
4215 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134216 RenderFrameHostImpl* rfhi =
4217 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584218
4219 // Only active documents can load post-commit error pages:
4220 // - If the document is in pending deletion, the browser already committed to
4221 // destroying this RenderFrameHost so ignore loading the error page.
4222 // - If the document is in back-forward cache, it's not allowed to navigate as
4223 // it should remain frozen. Ignore the request and evict the document from
4224 // back-forward cache.
4225 // - If the document is prerendering, it can navigate but when loading error
4226 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114227 if (rfhi->IsInactiveAndDisallowActivation(
4228 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144229 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114230 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584231
Rakina Zata Amni919b7922020-12-11 09:03:134232 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414233
Minggang Wangb9f3fa92021-07-01 15:30:314234 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434235 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594236 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4237 // the frame actually committed (e.g. iframe with "src" set to a
4238 // slow-responding URL). We should rewrite the URL to about:blank in this
4239 // case, as the renderer will only think a page is an error page if it has a
4240 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134241 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314242 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434243 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334244 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414245
Mike Jacksone2aa7af2023-05-17 06:45:074246 commit_params->navigation_timing->system_entropy_at_navigation_start =
4247 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4248 node, blink::mojom::SystemEntropy::kNormal);
4249
arthursonzogni70ac7302020-05-28 08:49:054250 // Error pages have a fully permissive FramePolicy.
4251 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4252 // error pages.
4253 commit_params->frame_policy = blink::FramePolicy();
4254
John Delaney131ad362019-08-08 21:57:414255 std::unique_ptr<NavigationRequest> navigation_request =
4256 NavigationRequest::CreateBrowserInitiated(
4257 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094258 false /* was_opener_suppressed */, "" /* extra_headers */,
4259 nullptr /* frame_entry */, nullptr /* entry */,
4260 false /* is_form_submission */, nullptr /* navigation_ui_data */,
4261 absl::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364262 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414263 navigation_request->set_net_error(error);
Charlie Reis09952ee2022-12-08 16:35:074264 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414265 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144266
4267 // Calling BeginNavigation may destroy the NavigationRequest.
4268 base::WeakPtr<NavigationRequest> created_navigation_request(
4269 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414270 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144271 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414272}
4273
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574274void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214275 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094276 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154277 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144278 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294279}
4280
[email protected]d202a7c2012-01-04 07:53:474281void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364282 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474283 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4284 // represent a no-committed-entry state.
4285 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364286 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474287 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4288 // if `entries_` contains pre-existing entries from the NavigationController
4289 // before restore, which would not be removed and will be at the front of the
4290 // entries list, causing the index to be off by the amount of pre-existing
4291 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294292 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294293}
[email protected]765b35502008-08-21 00:51:204294
arthursonzogni69a6a1b2019-09-17 09:23:004295void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004296 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4297}
4298
4299void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4300 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474301 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104302 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4303 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294304 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474305 return;
Michael Thiessenc5676d22019-09-25 22:32:104306 }
avi45a72532015-04-07 21:01:454307 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314308
4309 if (!delegate_)
4310 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374311 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484312}
4313
avi7c6f35e2015-05-08 17:52:384314int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4315 int nav_entry_id) const {
4316 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4317 if (entries_[i]->GetUniqueID() == nav_entry_id)
4318 return i;
4319 }
4320 return -1;
4321}
4322
[email protected]d202a7c2012-01-04 07:53:474323void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574324 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254325 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574326 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574327 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4328 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254329 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374330 // Normally, cloning a NavigationEntryImpl results in sharing
4331 // FrameNavigationEntries between the original and the clone. However, when
4332 // cloning from a different NavigationControllerImpl, we want to fork the
4333 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374334 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574335 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254336 }
Rakina Zata Amnie2d31312022-11-18 03:38:454337 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274338 DCHECK(pending_entry_index_ == -1 ||
4339 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254340}
[email protected]c5b88d82012-10-06 17:03:334341
4342void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184343 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334344 get_timestamp_callback_ = get_timestamp_callback;
4345}
[email protected]8ff00d72012-10-23 19:12:214346
Shivani Sharmaffb32b82019-04-09 16:58:474347// History manipulation intervention:
4348void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474349 bool replace_entry,
4350 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404351 bool is_renderer_initiated,
4352 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454353 // Note that for a subframe, previous_document_was_activated is true if the
4354 // gesture happened in any subframe (propagated to main frame) or in the main
4355 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474356 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274357 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474358 return;
4359 }
4360 if (last_committed_entry_index_ == -1)
4361 return;
4362
Shivani Sharmac4cc8922019-04-18 03:11:174363 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474364
Alexander Timine3ec4192020-04-20 16:39:404365 // Log UKM with the URL we are navigating away from.
4366 ukm::builders::HistoryManipulationIntervention(
4367 previous_page_load_ukm_source_id)
4368 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474369}
4370
Shivani Sharmac4cc8922019-04-18 03:11:174371void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4372 int reference_index,
4373 bool skippable) {
4374 auto* reference_entry = GetEntryAtIndex(reference_index);
4375 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4376
4377 int64_t document_sequence_number =
4378 reference_entry->root_node()->frame_entry->document_sequence_number();
4379 for (int index = 0; index < GetEntryCount(); index++) {
4380 auto* entry = GetEntryAtIndex(index);
4381 if (entry->root_node()->frame_entry->document_sequence_number() ==
4382 document_sequence_number) {
4383 entry->set_should_skip_on_back_forward_ui(skippable);
4384 }
4385 }
4386}
4387
arthursonzogni66f711c2019-10-08 14:40:364388std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4389NavigationControllerImpl::ReferencePendingEntry() {
4390 DCHECK(pending_entry_);
4391 auto pending_entry_ref =
4392 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4393 pending_entry_refs_.insert(pending_entry_ref.get());
4394 return pending_entry_ref;
4395}
4396
4397void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4398 // Ignore refs that don't correspond to the current pending entry.
4399 auto it = pending_entry_refs_.find(ref);
4400 if (it == pending_entry_refs_.end())
4401 return;
4402 pending_entry_refs_.erase(it);
4403
4404 if (!pending_entry_refs_.empty())
4405 return;
4406
4407 // The pending entry may be deleted before the last PendingEntryRef.
4408 if (!pending_entry_)
4409 return;
4410
4411 // We usually clear the pending entry when the matching NavigationRequest
4412 // fails, so that an arbitrary URL isn't left visible above a committed page.
4413 //
4414 // However, we do preserve the pending entry in some cases, such as on the
4415 // initial navigation of an unmodified blank tab. We also allow the delegate
4416 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4417 // user edit the URL and try again. This may be useful in cases that the
4418 // committed page cannot be attacker-controlled. In these cases, we still
4419 // allow the view to clear the pending entry and typed URL if the user
4420 // requests (e.g., hitting Escape with focus in the address bar).
4421 //
4422 // Do not leave the pending entry visible if it has an invalid URL, since this
4423 // might be formatted in an unexpected or unsafe way.
4424 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364425 bool should_preserve_entry =
4426 (pending_entry_ == GetVisibleEntry()) &&
4427 pending_entry_->GetURL().is_valid() &&
4428 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4429 if (should_preserve_entry)
4430 return;
4431
4432 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374433 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364434}
4435
Titouan Rigoudy6ec70402021-02-02 15:42:194436std::unique_ptr<PolicyContainerPolicies>
4437NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394438 RenderFrameHostImpl* rfh,
4439 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174440 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394441 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454442 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394443 FrameNavigationEntry* previous_frame_entry =
4444 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4445
4446 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4447 // ensure we always have a FrameNavigationEntry here.
4448 if (!previous_frame_entry)
4449 return nullptr;
4450
Titouan Rigoudy6ec70402021-02-02 15:42:194451 const PolicyContainerPolicies* previous_policies =
4452 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394453
Titouan Rigoudy6ec70402021-02-02 15:42:194454 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394455 return nullptr;
4456
4457 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234458 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394459 }
4460
Titouan Rigoudy72f892d2022-05-02 18:21:234461 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394462}
4463
Hayato Ito2c8c08d02021-06-23 03:38:434464void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504465 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434466 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4467 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4468 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504469
4470 auto callback = base::BindRepeating(
4471 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4472 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4473 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4474 }
4475 },
Hayato Ito2c8c08d02021-06-23 03:38:434476 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034477 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504478}
4479
4480void NavigationControllerImpl::DidAccessInitialMainDocument() {
4481 // We may have left a failed browser-initiated navigation in the address bar
4482 // to let the user edit it and try again. Clear it now that content might
4483 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034484 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504485 DiscardPendingEntry(false);
4486
4487 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374488 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504489}
4490
4491void NavigationControllerImpl::UpdateStateForFrame(
4492 RenderFrameHostImpl* rfhi,
4493 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564494 OPTIONAL_TRACE_EVENT1("content",
4495 "NavigationControllerImpl::UpdateStateForFrame",
4496 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504497 // The state update affects the last NavigationEntry associated with the given
4498 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4499 // in the case of an UpdateState from a frame being swapped out). We track
4500 // which entry this is in the RenderFrameHost's nav_entry_id.
4501 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4502 if (!entry)
4503 return;
4504
4505 FrameNavigationEntry* frame_entry =
4506 entry->GetFrameEntry(rfhi->frame_tree_node());
4507 if (!frame_entry)
4508 return;
4509
4510 // The SiteInstance might not match if we do a cross-process navigation with
4511 // replacement (e.g., auto-subframe), in which case the swap out of the old
4512 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4513 // has already been replaced and destroyed.
4514 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4515 return;
4516
4517 if (page_state == frame_entry->page_state())
4518 return; // Nothing to update.
4519
4520 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4521
4522 // The document_sequence_number and item_sequence_number recorded in the
4523 // FrameNavigationEntry should not differ from the one coming with the update,
4524 // since it must come from the same document. Do not update it if a difference
4525 // is detected, as this indicates that |frame_entry| is not the correct one.
4526 blink::ExplodedPageState exploded_state;
4527 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4528 return;
4529
4530 if (exploded_state.top.document_sequence_number !=
4531 frame_entry->document_sequence_number() ||
4532 exploded_state.top.item_sequence_number !=
4533 frame_entry->item_sequence_number()) {
4534 return;
4535 }
4536
4537 frame_entry->SetPageState(page_state);
4538 NotifyEntryChanged(entry);
4539}
4540
Domenic Denicolacd30f5f82022-03-16 21:48:014541std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4542NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574543 Direction direction,
4544 int entry_index,
4545 const url::Origin& pending_origin,
4546 FrameTreeNode* node,
4547 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304548 int64_t pending_item_sequence_number,
4549 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014550 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454551 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174552 // Don't process the initial entry.
4553 DCHECK_EQ(GetEntryCount(), 1);
4554 return entries;
4555 }
Nate Chapind1fe3612021-04-16 20:45:574556 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304557 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574558 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4559 i += offset) {
4560 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414561 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574562 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014563 // An entry should only appear in the navigation API entries if it is for
4564 // the same origin as the document being committed. Check the committed
4565 // origin, or if that is not available (during restore), check against the
4566 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414567 url::Origin frame_entry_origin =
4568 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4569 frame_entry->url(),
4570 frame_entry->initiator_origin().value_or(url::Origin())));
4571 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574572 break;
4573 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4574 continue;
4575 blink::ExplodedPageState exploded_page_state;
4576 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4577 &exploded_page_state)) {
4578 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304579
4580 // If the document represented by this FNE hid its full url from appearing
4581 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014582 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304583 // document).
4584 std::u16string url;
4585 if (pending_document_sequence_number ==
4586 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574587 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304588 url = frame_state.url_string.value_or(std::u16string());
4589 }
4590
Domenic Denicolacd30f5f82022-03-16 21:48:014591 blink::mojom::NavigationApiHistoryEntryPtr entry =
4592 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574593 frame_state.navigation_api_key.value_or(std::u16string()),
4594 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094595 frame_state.item_sequence_number,
4596 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304597 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174598
Nate Chapin63db0d12022-01-20 22:03:304599 DCHECK(entry->url.empty() ||
4600 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574601 entries.push_back(std::move(entry));
4602 previous_item_sequence_number = frame_entry->item_sequence_number();
4603 }
4604 }
4605 // If |entries| was constructed by iterating backwards from
4606 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4607 // earliest-at-the-front. Reverse it.
4608 if (direction == Direction::kBack)
4609 std::reverse(entries.begin(), entries.end());
4610 return entries;
4611}
4612
Domenic Denicolacd30f5f82022-03-16 21:48:014613blink::mojom::NavigationApiHistoryEntryArraysPtr
4614NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554615 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574616 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404617 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444618 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404619 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574620
Nate Chapind1fe3612021-04-16 20:45:574621 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554622 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574623
Nate Chapine82339d02022-05-03 23:48:254624 // NOTE: |entry_index| is the index where this entry will commit if no
4625 // modifications are made between now and DidCommitNavigation. This is used to
4626 // walk |entries_| and determine which entries should be exposed by the
4627 // navigation API. It is important to calculate this correctly, because blink
4628 // will cancel a same-document history commit if it's not present in the
4629 // entries blink knows about.
4630 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574631 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304632 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254633 bool will_create_new_entry = false;
4634 if (GetPendingEntryIndex() != -1) {
4635 entry_index = GetPendingEntryIndex();
4636 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4637 pending_item_sequence_number = frame_entry->item_sequence_number();
4638 pending_document_sequence_number =
4639 frame_entry->document_sequence_number();
4640 }
4641 } else if (request &&
4642 !NavigationTypeUtils::IsReload(
4643 request->common_params().navigation_type) &&
4644 !NavigationTypeUtils::IsHistory(
4645 request->common_params().navigation_type) &&
4646 !request->common_params().should_replace_current_entry &&
4647 !request->common_params()
4648 .is_history_navigation_in_new_child_frame) {
4649 will_create_new_entry = true;
4650 entry_index = GetLastCommittedEntryIndex() + 1;
4651 // Don't set pending_item_sequence_number or
4652 // pending_document_sequence_number in this case - a new unique isn/dsn will
4653 // be calculated in the renderer later.
4654 } else if (GetLastCommittedEntryIndex() != -1) {
4655 entry_index = GetLastCommittedEntryIndex();
4656 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574657 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304658 pending_document_sequence_number =
4659 frame_entry->document_sequence_number();
4660 }
Nate Chapind1fe3612021-04-16 20:45:574661 }
4662
Domenic Denicolacd30f5f82022-03-16 21:48:014663 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254664 if (entry_index == -1) {
4665 // TODO(rakina): Exit early when there is no last committed entry.
4666 // Remove when InitialNavigationEntry ships.
4667 return entry_arrays;
4668 }
4669
Domenic Denicolacd30f5f82022-03-16 21:48:014670 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574671 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374672 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574673
4674 // Don't populate forward entries if they will be truncated by a new entry.
4675 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014676 entry_arrays->forward_entries =
4677 PopulateSingleNavigationApiHistoryEntryVector(
4678 Direction::kForward, entry_index, pending_origin, node,
4679 site_instance.get(), pending_item_sequence_number,
4680 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574681 }
Nate Chapin4e657a472022-02-06 03:38:374682 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574683}
4684
Nate Chapinfbfe5af2021-06-10 17:22:084685NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574686NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084687 FrameNavigationEntry* current_entry,
4688 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574689 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084690 if (!target_entry || !target_entry->committed_origin())
4691 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084692 if (!current_entry->committed_origin()->IsSameOriginWith(
4693 *target_entry->committed_origin())) {
4694 return HistoryNavigationAction::kStopLooking;
4695 }
4696
4697 // NOTE: We don't actually care between kSameDocument and
4698 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574699 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084700 return HistoryNavigationAction::kDifferentDocument;
4701 return HistoryNavigationAction::kKeepLooking;
4702}
4703
Domenic Denicolacc094fb2022-03-16 23:40:574704void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204705 RenderFrameHostImpl* initiator_rfh,
Yoav Weissa7449c3b2022-11-22 15:15:144706 absl::optional<blink::scheduler::TaskAttributionId>
4707 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574708 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204709 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084710 FrameNavigationEntry* current_entry =
4711 GetLastCommittedEntry()->GetFrameEntry(node);
4712 if (!current_entry)
4713 return;
4714
Yoav Weiss8c573952022-11-17 17:35:134715 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4716 // when `navigation.traverseTo()` is called.
4717
Nate Chapinfbfe5af2021-06-10 17:22:084718 // We want to find the nearest matching entry that is contiguously
4719 // same-instance and same-origin. Check back first, then forward.
4720 // TODO(japhet): Link spec here once it exists.
4721 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574722 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084723 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4724 if (result == HistoryNavigationAction::kStopLooking)
4725 break;
4726 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144727 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084728 return;
4729 }
4730 }
4731 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574732 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084733 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4734 if (result == HistoryNavigationAction::kStopLooking)
4735 break;
4736 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144737 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084738 return;
4739 }
4740 }
Nate Chapinbf682fa32022-09-26 22:41:204741
4742 // If we fall through to here, a matching NavigationEntry couldn't be found.
4743 // Notify the renderer that the navigation was cancelled.
4744 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4745 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084746}
4747
Domenic Denicolacc094fb2022-03-16 23:40:574748bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304749 network::mojom::ReferrerPolicy referrer_policy) {
4750 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4751 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4752}
4753
shivanigithubf405bf0d2021-11-05 17:58:334754bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4755 const FrameTreeNode* frame_tree_node) const {
4756 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4757 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544758 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Ali Hijazid87307d2022-11-07 20:15:034759 return frame_tree_->is_prerendering() ||
shivanigithubf405bf0d2021-11-05 17:58:334760 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544761}
4762
Julie Jeongeun Kim0e242242022-11-30 10:45:094763void NavigationControllerImpl::DidChangeReferrerPolicy(
4764 FrameTreeNode* node,
4765 network::mojom::ReferrerPolicy referrer_policy) {
4766 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4767 if (!entry)
4768 return;
4769
4770 // The FrameNavigationEntry may want to change whether to protect its url
4771 // in the navigation API when the referrer policy changes.
4772 entry->set_protect_url_in_navigation_api(
4773 ShouldProtectUrlInNavigationApi(referrer_policy));
4774}
4775
[email protected]8ff00d72012-10-23 19:12:214776} // namespace content