blob: c996cacd0955907568a4504b9f0b53cee42742c7 [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]c5b88d82012-10-06 17:03:3341#include "base/bind.h"
[email protected]eabfe1912014-05-12 10:07:2842#include "base/command_line.h"
Ayu Ishii2f825852022-03-08 19:47:3843#include "base/containers/adapters.h"
Rakina Zata Amni627360d2022-02-24 00:53:4044#include "base/debug/dump_without_crashing.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"
[email protected]825b1662012-03-12 19:07:3161#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4162#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0463#include "content/browser/dom_storage/session_storage_namespace_impl.h"
danakjc492bf82020-09-09 20:02:4464#include "content/browser/renderer_host/debug_urls.h"
65#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0066#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3367#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4468#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5769#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4470#include "content/browser/renderer_host/navigation_request.h"
71#include "content/browser/renderer_host/navigator.h"
72#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0073#include "content/browser/renderer_host/render_view_host_impl.h"
Sharon Yangd70a5392021-10-26 23:06:3274#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3375#include "content/browser/site_instance_impl.h"
Kunihiko Sakamoto346a74e2021-03-10 08:57:4876#include "content/browser/web_package/subresource_web_bundle_navigation_info.h"
Tsuyoshi Horo37493af2019-11-21 23:43:1477#include "content/browser/web_package/web_bundle_navigation_info.h"
Camille Lamy5193caa2018-10-12 11:59:4278#include "content/common/content_constants_internal.h"
Nate Chapind1fe3612021-04-16 20:45:5779#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5180#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1181#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1982#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1183#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4684#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0085#include "content/public/browser/navigation_details.h"
[email protected]7f6f44c2011-12-14 13:23:3886#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1687#include "content/public/browser/notification_types.h"
Lei Zhang96031532019-10-10 19:05:4788#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5889#include "content/public/browser/render_widget_host.h"
90#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1091#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3492#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1993#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3894#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1095#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:4796#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:4397#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:5998#include "media/base/mime_util.h"
Arthur Sonzogni620cec62018-12-13 13:08:5799#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18100#include "services/metrics/public/cpp/ukm_builders.h"
101#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17102#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37103#include "services/network/public/mojom/fetch_api.mojom.h"
[email protected]9677a3c2012-12-22 04:18:58104#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39105#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30106#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21107#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06108#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43109#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50110#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31111#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51112#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
[email protected]cca6f392014-05-28 21:32:26113#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29114
[email protected]8ff00d72012-10-23 19:12:21115namespace content {
[email protected]e9ba4472008-09-14 15:42:43116namespace {
117
118// Invoked when entries have been pruned, or removed. For example, if the
119// current entries are [google, digg, yahoo], with the current entry google,
120// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47121void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50122 int index,
[email protected]c12bf1a12008-09-17 16:28:49123 int count) {
[email protected]8ff00d72012-10-23 19:12:21124 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50125 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49126 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14127 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43128}
129
[email protected]e9ba4472008-09-14 15:42:43130// Configure all the NavigationEntries in entries for restore. This resets
131// the transition type to reload and makes sure the content state isn't empty.
132void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57133 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48134 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47135 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43136 // Use a transition type of reload so that we don't incorrectly increase
137 // the typed count.
Lei Zhang96031532019-10-10 19:05:47138 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
139 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43140 }
141}
142
[email protected]bf70edce2012-06-20 22:32:22143// Determines whether or not we should be carrying over a user agent override
144// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57145bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22146 return last_entry && last_entry->GetIsOverridingUserAgent();
147}
148
Camille Lamy5193caa2018-10-12 11:59:42149// Determines whether to override user agent for a navigation.
150bool ShouldOverrideUserAgent(
151 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57152 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42153 switch (override_user_agent) {
154 case NavigationController::UA_OVERRIDE_INHERIT:
155 return ShouldKeepOverride(last_committed_entry);
156 case NavigationController::UA_OVERRIDE_TRUE:
157 return true;
158 case NavigationController::UA_OVERRIDE_FALSE:
159 return false;
Camille Lamy5193caa2018-10-12 11:59:42160 }
161 NOTREACHED();
162 return false;
163}
164
Rakina Zata Amni312822d72021-06-04 16:13:37165// Returns true if this navigation should be treated as a reload. For e.g.
clamy0a656e42018-02-06 18:18:28166// navigating to the last committed url via the address bar or clicking on a
Rakina Zata Amni312822d72021-06-04 16:13:37167// link which results in a navigation to the last committed URL (but wasn't
168// converted to do a replacement navigation in the renderer), etc.
Fergal Daly766177d2020-07-07 07:54:04169// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
170// |base_url_for_data_url|, |transition_type| correspond to the new navigation
171// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
172// navigation that committed.
173bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
174 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57175 const GURL& virtual_url,
176 const GURL& base_url_for_data_url,
177 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57178 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37179 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57180 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37181 // Navigations intended to do a replacement shouldn't be converted to do a
182 // reload.
183 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28184 return false;
clamy0a656e42018-02-06 18:18:28185 // Only convert to reload if at least one navigation committed.
Rakina Zata Amni2322f4f82022-01-24 13:24:24186 if (!last_committed_entry || last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55187 return false;
188
arthursonzogni7a8243682017-12-14 16:41:42189 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28190 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42191 return false;
192
ananta3bdd8ae2016-12-22 17:11:55193 // We treat (PAGE_TRANSITION_RELOAD | PAGE_TRANSITION_FROM_ADDRESS_BAR),
194 // PAGE_TRANSITION_TYPED or PAGE_TRANSITION_LINK transitions as navigations
195 // which should be treated as reloads.
clamy0a656e42018-02-06 18:18:28196 bool transition_type_can_be_converted = false;
197 if (ui::PageTransitionCoreTypeIs(transition_type,
198 ui::PAGE_TRANSITION_RELOAD) &&
199 (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)) {
200 transition_type_can_be_converted = true;
ananta3bdd8ae2016-12-22 17:11:55201 }
clamy0a656e42018-02-06 18:18:28202 if (ui::PageTransitionCoreTypeIs(transition_type,
ananta3bdd8ae2016-12-22 17:11:55203 ui::PAGE_TRANSITION_TYPED)) {
clamy0a656e42018-02-06 18:18:28204 transition_type_can_be_converted = true;
205 }
206 if (ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_LINK))
207 transition_type_can_be_converted = true;
208 if (!transition_type_can_be_converted)
209 return false;
210
211 // This check is required for cases like view-source:, etc. Here the URL of
212 // the navigation entry would contain the url of the page, while the virtual
213 // URL contains the full URL including the view-source prefix.
214 if (virtual_url != last_committed_entry->GetVirtualURL())
215 return false;
216
Fergal Daly766177d2020-07-07 07:54:04217 // Check that the URLs match.
218 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
219 // If there's no frame entry then by definition the URLs don't match.
220 if (!frame_entry)
221 return false;
222
223 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28224 return false;
225
226 // This check is required for Android WebView loadDataWithBaseURL. Apps
227 // can pass in anything in the base URL and we need to ensure that these
228 // match before classifying it as a reload.
229 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
230 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
231 return false;
ananta3bdd8ae2016-12-22 17:11:55232 }
233
clamy0a656e42018-02-06 18:18:28234 // Skip entries with SSL errors.
235 if (last_committed_entry->ssl_error())
236 return false;
237
238 // Don't convert to a reload when the last navigation was a POST or the new
239 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04240 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28241 return false;
242
243 return true;
ananta3bdd8ae2016-12-22 17:11:55244}
245
Nasko Oskov03912102019-01-11 00:21:32246bool DoesURLMatchOriginForNavigation(
Wang Hui14cac7a2022-01-28 06:07:47247 const GURL& destination_url,
Anton Bikineevf62d1bf2021-05-15 17:56:07248 const absl::optional<url::Origin>& origin,
Wang Hui14cac7a2022-01-28 06:07:47249 SubresourceWebBundleNavigationInfo* subresource_web_bundle_navigation_info,
250 NavigationEntry* entry,
251 bool is_main_frame) {
Nasko Oskov03912102019-01-11 00:21:32252 // If there is no origin supplied there is nothing to match. This can happen
253 // for navigations to a pending entry and therefore it should be allowed.
254 if (!origin)
255 return true;
256
Wang Hui14cac7a2022-01-28 06:07:47257 // For a history navigation to a document loaded with loadDataWithBaseURL,
258 // compare the origin to the entry's base URL instead of the data: URL used to
259 // commit.
260 const GURL& base_url_for_data_url = entry->GetBaseURLForDataURL();
261 bool check_origin_against_base_url =
262 is_main_frame && !base_url_for_data_url.is_empty();
263
264 const GURL& url_for_origin =
265 check_origin_against_base_url ? base_url_for_data_url : destination_url;
Kunihiko Sakamotof32652502022-04-05 03:05:59266 // Uuid-in-package: subframe from WebBundle has an opaque origin derived from
267 // the Bundle's origin.
268 if (url_for_origin.SchemeIs(url::kUuidInPackageScheme) &&
Kunihiko Sakamoto260ee0a2021-10-15 01:44:08269 subresource_web_bundle_navigation_info) {
Kunihiko Sakamoto346a74e2021-03-10 08:57:48270 return origin->CanBeDerivedFrom(
271 subresource_web_bundle_navigation_info->bundle_url());
272 }
273
Wang Hui14cac7a2022-01-28 06:07:47274 return origin->CanBeDerivedFrom(url_for_origin);
Nasko Oskov03912102019-01-11 00:21:32275}
276
Anton Bikineevf62d1bf2021-05-15 17:56:07277absl::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12278 const mojom::DidCommitProvisionalLoadParams& params,
279 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32280 // Error pages commit in an opaque origin, yet have the real URL that resulted
281 // in an error as the |params.url|. Since successful reload of an error page
282 // should commit in the correct origin, setting the opaque origin on the
283 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17284 if (request && request->DidEncounterError())
Anton Bikineevf62d1bf2021-05-15 17:56:07285 return absl::nullopt;
Nasko Oskov03912102019-01-11 00:21:32286
Anton Bikineevf62d1bf2021-05-15 17:56:07287 return absl::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32288}
289
Camille Lamy5193caa2018-10-12 11:59:42290bool IsValidURLForNavigation(bool is_main_frame,
291 const GURL& virtual_url,
292 const GURL& dest_url) {
293 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
294 if (is_main_frame && !virtual_url.is_valid() && !virtual_url.is_empty()) {
295 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
296 << virtual_url.possibly_invalid_spec();
297 return false;
298 }
299
300 // Don't attempt to navigate to non-empty invalid URLs.
301 if (!dest_url.is_valid() && !dest_url.is_empty()) {
302 LOG(WARNING) << "Refusing to load invalid URL: "
303 << dest_url.possibly_invalid_spec();
304 return false;
305 }
306
307 // The renderer will reject IPC messages with URLs longer than
308 // this limit, so don't attempt to navigate with a longer URL.
309 if (dest_url.spec().size() > url::kMaxURLChars) {
310 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
311 << " characters.";
312 return false;
313 }
314
Aaron Colwell33109c592020-04-21 21:31:19315 // Reject renderer debug URLs because they should have been handled before
316 // we get to this point. This check handles renderer debug URLs
317 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
318 // provides defense-in-depth if a renderer debug URL manages to get here via
319 // some other path. We want to reject the navigation here so it doesn't
320 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30321 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19322 LOG(WARNING) << "Refusing to load renderer debug URL: "
323 << dest_url.possibly_invalid_spec();
324 return false;
325 }
326
Camille Lamy5193caa2018-10-12 11:59:42327 return true;
328}
329
Mikel Astizba9cf2fd2017-12-17 10:38:10330// See replaced_navigation_entry_data.h for details: this information is meant
331// to ensure |*output_entry| keeps track of its original URL (landing page in
332// case of server redirects) as it gets replaced (e.g. history.replaceState()),
333// without overwriting it later, for main frames.
334void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57335 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10336 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17337 if (output_entry->GetReplacedEntryData().has_value() ||
338 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10339 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17340 }
Mikel Astizba9cf2fd2017-12-17 10:38:10341
342 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57343 data.first_committed_url = replaced_entry->GetURL();
344 data.first_timestamp = replaced_entry->GetTimestamp();
345 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29346 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10347}
348
Minggang Wangb9f3fa92021-07-01 15:30:31349blink::mojom::NavigationType GetNavigationType(
350 const GURL& old_url,
351 const GURL& new_url,
352 ReloadType reload_type,
353 NavigationEntryImpl* entry,
354 const FrameNavigationEntry& frame_entry,
355 bool has_pending_cross_document_commit,
356 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49357 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13358 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49359 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23360 // Reload navigations
361 switch (reload_type) {
362 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31363 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23364 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31365 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23366 case ReloadType::ORIGINAL_REQUEST_URL:
Minggang Wangb9f3fa92021-07-01 15:30:31367 return blink::mojom::NavigationType::RELOAD_ORIGINAL_REQUEST_URL;
clamyea99ea12018-05-28 13:54:23368 case ReloadType::NONE:
369 break; // Fall through to rest of function.
370 }
371
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08372 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31373 return entry->GetHasPostData()
374 ? blink::mojom::NavigationType::RESTORE_WITH_POST
375 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23376 }
377
danakjb952ef12021-01-14 19:58:49378 const bool can_be_same_document =
379 // A pending cross-document commit means this navigation will not occur in
380 // the current document, as that document would end up being replaced in
381 // the meantime.
382 !has_pending_cross_document_commit &&
383 // If the current document is an error page, we should always treat it as
384 // a different-document navigation so that we'll attempt to load the
385 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49386 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13387 // If the navigation is an embedder-initiated navigation of a fenced
388 // frame root (i.e. enters a fenced frame tree from outside),
389 // same-document navigations should be disabled because we don't want to
390 // allow information to be joined across multiple embedder-initiated
391 // fenced frame navigations (which may contain separate cross-site data).
392 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49393 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
394 // same-document navigations should be disabled because we want to force
395 // the creation of a new browsing context group.
396 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12397
clamyea99ea12018-05-28 13:54:23398 // History navigations.
399 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12400 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31401 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
402 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23403 }
404 DCHECK(!is_same_document_history_load);
405
406 // A same-document fragment-navigation happens when the only part of the url
407 // that is modified is after the '#' character.
408 //
409 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12410 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23411 //
412 // Note: this check is only valid for navigations that are not history
413 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
414 // history navigation from 'A#foo' to 'A#bar' is not a same-document
415 // navigation, but a different-document one. This is why history navigation
416 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47417 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
418 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12419
420 // The one case where we do the wrong thing here and incorrectly choose
421 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
422 // the renderer is a frameset. All frameset navigations should be
423 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
424 // navigation would do the right thing, as it would send it to the browser and
425 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
426 // into this method). But since we can't tell that case here for browser-
427 // initiated navigations, we have to get the renderer involved. In that case
428 // the navigation would be restarted due to the renderer spending a reply of
429 // mojom::CommitResult::RestartCrossDocument.
430
431 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31432 ? blink::mojom::NavigationType::SAME_DOCUMENT
433 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23434}
435
Camille Lamy5193caa2018-10-12 11:59:42436// Adjusts the original input URL if needed, to get the URL to actually load and
437// the virtual URL, which may differ.
438void RewriteUrlForNavigation(const GURL& original_url,
439 BrowserContext* browser_context,
440 GURL* url_to_load,
441 GURL* virtual_url,
442 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42443 // Allow the browser URL handler to rewrite the URL. This will, for example,
444 // remove "view-source:" from the beginning of the URL to get the URL that
445 // will actually be loaded. This real URL won't be shown to the user, just
446 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31447 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42448 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
449 url_to_load, browser_context, reverse_on_redirect);
450}
451
452#if DCHECK_IS_ON()
453// Helper sanity check function used in debug mode.
454void ValidateRequestMatchesEntry(NavigationRequest* request,
455 NavigationEntryImpl* entry) {
456 if (request->frame_tree_node()->IsMainFrame()) {
457 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
458 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31459 ui::PageTransitionFromInt(request->common_params().transition),
460 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42461 }
Nasko Oskovc36327d2019-01-03 23:23:04462 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42463 entry->should_clear_history_list());
464 DCHECK_EQ(request->common_params().has_user_gesture,
465 entry->has_user_gesture());
466 DCHECK_EQ(request->common_params().base_url_for_data_url,
467 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04468 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42469 entry->GetCanLoadLocalResources());
470 DCHECK_EQ(request->common_params().started_from_context_menu,
471 entry->has_started_from_context_menu());
472
473 FrameNavigationEntry* frame_entry =
474 entry->GetFrameEntry(request->frame_tree_node());
475 if (!frame_entry) {
476 NOTREACHED();
477 return;
478 }
479
Camille Lamy5193caa2018-10-12 11:59:42480 DCHECK_EQ(request->common_params().method, frame_entry->method());
481
Nasko Oskovc36327d2019-01-03 23:23:04482 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42483 if (redirect_size == frame_entry->redirect_chain().size()) {
484 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04485 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42486 frame_entry->redirect_chain()[i]);
487 }
488 } else {
489 NOTREACHED();
490 }
491}
492#endif // DCHECK_IS_ON()
493
Dave Tapuska8bfd84c2019-03-26 20:47:16494// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20495// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16496bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20497 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16498 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20499 DCHECK(sandboxed_initiator_rfh);
500 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
501 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16502 for (auto& item : navigations) {
503 bool within_subtree = false;
504 // Check whether this NavigationRequest affects a frame within the
505 // sandboxed frame's subtree by walking up the tree looking for the
506 // sandboxed frame.
507 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03508 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20509 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16510 within_subtree = true;
511 break;
512 }
513 }
514 if (!within_subtree)
515 return false;
516 }
517 return true;
518}
519
[email protected]e9ba4472008-09-14 15:42:43520} // namespace
521
arthursonzogni66f711c2019-10-08 14:40:36522// NavigationControllerImpl::PendingEntryRef------------------------------------
523
524NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
525 base::WeakPtr<NavigationControllerImpl> controller)
526 : controller_(controller) {}
527
528NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
529 if (!controller_) // Can be null with interstitials.
530 return;
531
532 controller_->PendingEntryRefDeleted(this);
533}
534
[email protected]d202a7c2012-01-04 07:53:47535// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29536
[email protected]23a918b2014-07-15 09:51:36537const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23538
[email protected]765b35502008-08-21 00:51:20539// static
[email protected]d202a7c2012-01-04 07:53:47540size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23541 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20542
[email protected]e6fec472013-05-14 05:29:02543// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20544// when testing.
545static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29546
[email protected]71fde352011-12-29 03:29:56547// static
dcheng9bfa5162016-04-09 01:00:57548std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
549 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10550 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07551 absl::optional<url::Origin> initiator_origin,
Lukasz Anforowicz641234d52019-11-07 21:07:10552 ui::PageTransition transition,
553 bool is_renderer_initiated,
554 const std::string& extra_headers,
555 BrowserContext* browser_context,
556 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
557 return NavigationControllerImpl::CreateNavigationEntry(
558 url, referrer, std::move(initiator_origin),
559 nullptr /* source_site_instance */, transition, is_renderer_initiated,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17560 extra_headers, browser_context, std::move(blob_url_loader_factory),
561 true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10562}
563
564// static
565std::unique_ptr<NavigationEntryImpl>
566NavigationControllerImpl::CreateNavigationEntry(
567 const GURL& url,
568 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07569 absl::optional<url::Origin> initiator_origin,
Lukasz Anforowicz641234d52019-11-07 21:07:10570 SiteInstance* source_site_instance,
dcheng9bfa5162016-04-09 01:00:57571 ui::PageTransition transition,
572 bool is_renderer_initiated,
573 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09574 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17575 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
576 bool rewrite_virtual_urls) {
577 GURL url_to_load = url;
578 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56579 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17580 if (rewrite_virtual_urls) {
581 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
582 &reverse_on_redirect);
583 }
Lukasz Anforowicz641234d52019-11-07 21:07:10584 // Let the NTP override the navigation params and pretend that this is a
585 // browser-initiated, bookmark-like navigation.
586 GetContentClient()->browser()->OverrideNavigationParams(
Scott Violetcf6ea7e2021-06-09 21:09:21587 source_site_instance, &transition, &is_renderer_initiated, &referrer,
588 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10589
Patrick Monettef507e982019-06-19 20:18:06590 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28591 nullptr, // The site instance for tabs is sent on navigation
592 // (WebContents::GetSiteInstance).
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:58593 url_to_load, referrer, initiator_origin, std::u16string(), transition,
Rakina Zata Amniafd3c6582021-11-30 06:19:17594 is_renderer_initiated, blob_url_loader_factory,
595 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42596 entry->SetVirtualURL(virtual_url);
597 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56598 entry->set_update_virtual_url_with_url(reverse_on_redirect);
599 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06600 return entry;
[email protected]71fde352011-12-29 03:29:56601}
602
[email protected]cdcb1dee2012-01-04 00:46:20603// static
604void NavigationController::DisablePromptOnRepost() {
605 g_check_for_repost = false;
606}
607
[email protected]c5b88d82012-10-06 17:03:33608base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
609 base::Time t) {
610 // If |t| is between the water marks, we're in a run of duplicates
611 // or just getting out of it, so increase the high-water mark to get
612 // a time that probably hasn't been used before and return it.
613 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35614 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33615 return high_water_mark_;
616 }
617
618 // Otherwise, we're clear of the last duplicate run, so reset the
619 // water marks.
620 low_water_mark_ = high_water_mark_ = t;
621 return t;
622}
623
ckitagawa0faa5e42020-06-17 17:30:54624NavigationControllerImpl::ScopedShowRepostDialogForTesting::
625 ScopedShowRepostDialogForTesting()
626 : was_disallowed_(g_check_for_repost) {
627 g_check_for_repost = true;
628}
629
630NavigationControllerImpl::ScopedShowRepostDialogForTesting::
631 ~ScopedShowRepostDialogForTesting() {
632 g_check_for_repost = was_disallowed_;
633}
634
Nate Chapin9eb16be72022-09-23 22:54:31635NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
636 base::SafeRef<NavigationControllerImpl> controller)
637 : controller_(controller) {
638 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
639 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
640 frame_tree_node_id_to_keys_.insert(
641 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
642 if (auto* frame_entry = frame_tree_node->current_frame_host()
643 ->last_committed_frame_entry()) {
644 frame_tree_node_id_to_doc_seq_nos_.insert(
645 {frame_tree_node->frame_tree_node_id(),
646 frame_entry->document_sequence_number()});
647 }
648 }
649 PopulateKeySet(Direction::kBack);
650 PopulateKeySet(Direction::kForward);
651}
652
653void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
654 Direction direction) {
655 // Keep track of which FrameTreeNodes may still have relevant API keys in
656 // additional FrameNavigationEntries.
657 std::set<FrameTreeNode*> nodes_to_process;
658 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
659 nodes_to_process.insert(node);
660 }
661
662 const int offset = direction == Direction::kForward ? 1 : -1;
663 const int start = direction == Direction::kForward
664 ? controller_->GetLastCommittedEntryIndex()
665 : controller_->GetLastCommittedEntryIndex() - 1;
666 for (int i = start;
667 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
668 i += offset) {
669 std::set<FrameTreeNode*> nodes_to_continue_processing;
670
671 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
672 entry->ForEachFrameEntry([this, &nodes_to_process,
673 &nodes_to_continue_processing,
674 &entry](FrameNavigationEntry* frame_entry) {
675 // Find the |node| that matches |frame_entry|, if any.
676 FrameTreeNode* node = nullptr;
677 if (frame_entry == entry->root_node()->frame_entry) {
678 node = controller_->frame_tree().root();
679 } else {
680 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
681 if (it == names_to_nodes_.end())
682 return;
683 node = it->second;
684 }
685
686 // Skip this node if a previous step determine there are no longer
687 // relevant navigation API keys in this direction.
688 if (nodes_to_process.find(node) == nodes_to_process.end())
689 return;
690
691 // Stop processing |node| if we reach a point where it's cross-origin.
692 // See also PopulateSingleNavigationApiHistoryEntryVector().
693 url::Origin frame_entry_origin =
694 frame_entry->committed_origin().value_or(url::Origin::Resolve(
695 frame_entry->url(),
696 frame_entry->initiator_origin().value_or(url::Origin())));
697 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
698 return;
699
700 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
701 frame_entry->navigation_api_key());
702 // Mark |node| as needing more processing for the next entry.
703 nodes_to_continue_processing.insert(node);
704
705 // Check whether |node| went cross-document. If so, its children are
706 // no longer the same conceptual iframe as the current one, and
707 // should no longer be processed. This check is intentionally done
708 // after processing the current |node|, which may still have relevant
709 // discarded API keys.
710 if (frame_entry->document_sequence_number() !=
711 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
712 for (auto* descendant : node->frame_tree()->SubtreeNodes(node))
713 nodes_to_process.erase(descendant);
714 }
715 });
716
717 nodes_to_process.swap(nodes_to_continue_processing);
718 }
719}
720
721NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
722 std::set<std::string> all_keys;
723 // Find all remaining navigation API keys after some entries have been
724 // removed.
725 for (auto& entry : controller_->entries_) {
726 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
727 all_keys.insert(frame_entry->navigation_api_key());
728 });
729 }
730
731 // Notify each frame in the renderer of any disposed navigation API keys.
732 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
733 std::vector<std::string> disposed_keys;
734 for (const auto& key : id_to_keys.second) {
735 if (all_keys.find(key) == all_keys.end())
736 disposed_keys.push_back(key);
737 }
738 if (disposed_keys.empty())
739 continue;
740
741 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
742 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
743 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
744 }
745}
746
[email protected]d202a7c2012-01-04 07:53:47747NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00748 BrowserContext* browser_context,
749 FrameTree& frame_tree,
750 NavigationControllerDelegate* delegate)
751 : frame_tree_(frame_tree),
752 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57753 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22754 ssl_manager_(this),
Lei Zhang96031532019-10-10 19:05:47755 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)) {
[email protected]3d7474ff2011-07-27 17:47:37756 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29757}
758
[email protected]d202a7c2012-01-04 07:53:47759NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00760 // The NavigationControllerImpl might be called inside its delegate
761 // destructor. Calling it is not valid anymore.
762 delegate_ = nullptr;
763 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29764}
765
Matt Falkenhagen548ed1562021-07-06 01:38:26766WebContents* NavigationControllerImpl::DeprecatedGetWebContents() {
767 return delegate_->DeprecatedGetWebContents();
[email protected]fbc5e5f92012-01-02 06:08:32768}
769
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57770BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55771 return browser_context_;
772}
773
[email protected]d202a7c2012-01-04 07:53:47774void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30775 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36776 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57777 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47778 // Note that it's possible for `entries_` to contain multiple entries at this
779 // point, as Restore() might be called on a NavigationController that is
780 // already used (e.g. due to WebView's restoreState() API), not only for fresh
781 // NavigationControllers. These entries are not cleared to preserve legacy
782 // behavior and also because `pending_entry_` might point to one of the
783 // pre-existing entries. An exception for this is when `entries_` contains
784 // only the initial NavigationEntry, which must be removed.
785
786 // Do not proceed if selected_navigation will be out of bounds for the updated
787 // entries_ list, since it will be assigned to last_committed_entry_index_ and
788 // used to index entries_.
789 // TODO(https://crbug.com/1287624): Consider also returning early if entries
790 // is empty, since there should be no work to do (rather than marking the
791 // existing entries as needing reload). Also consider returning early if the
792 // selected index is -1, which represents a no-committed-entry state.
793 if (selected_navigation < -1 ||
794 selected_navigation >=
795 base::checked_cast<int>(entries->size() + entries_.size())) {
796 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24797 }
Charlie Reis23c26da2022-01-29 00:57:47798
799 if (blink::features::IsInitialNavigationEntryEnabled()) {
800 // In InitialNavigationEntry mode, there will always be at least one entry.
801 if (selected_navigation == -1)
802 selected_navigation = 0;
803
804 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
805 // If we are on the initial NavigationEntry, it must be the only entry in
806 // the list. Since it's impossible to do a history navigation to the
807 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
808 // `pending_entry` might be set for a new non-history navigation).
809 // Note that we should not clear `entries_` if `entries` is empty (when
810 // InitialNavigationEntry mode is enabled), since that would leave us
811 // without any NavigationEntry.
812 CHECK_EQ(1, GetEntryCount());
813 CHECK_EQ(-1, pending_entry_index_);
814 entries_.clear();
815 }
816 }
[email protected]ce3fa3c2009-04-20 19:55:57817
[email protected]ce3fa3c2009-04-20 19:55:57818 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44819 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03820 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47821 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43822 if (entry->GetURL().is_empty()) {
823 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01824 // persisting the initial NavigationEntry [which is no longer possible but
825 // some old persisted sessions might still contain it] or when the
826 // serializer failed to write the URL because it's too long). Trying to
827 // restore and navigate to an entry with an empty URL will result in
828 // crashes, so change the URL to about:blank. See also
829 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43830 entry->SetURL(GURL(url::kAboutBlankURL));
831 }
dcheng36b6aec92015-12-26 06:16:36832 entries_.push_back(
833 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47834 }
avif16f85a72015-11-13 18:25:03835
836 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
837 // cleared out safely.
838 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57839
840 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36841 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57842}
843
toyoshim6142d96f2016-12-19 09:07:25844void NavigationControllerImpl::Reload(ReloadType reload_type,
845 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03846 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
847 (int)reload_type);
848 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
849 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28850 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28851 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32852 int current_index = -1;
853
Carlos IL42b416592019-10-07 23:10:36854 if (entry_replaced_by_post_commit_error_) {
855 // If there is an entry that was replaced by a currently active post-commit
856 // error navigation, this can't be the initial navigation.
857 DCHECK(!IsInitialNavigation());
858 // If the current entry is a post commit error, we reload the entry it
859 // replaced instead. We leave the error entry in place until a commit
860 // replaces it, but the pending entry points to the original entry in the
861 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
862 // case that pending_entry_ != entries_[pending_entry_index_].
863 entry = entry_replaced_by_post_commit_error_.get();
864 current_index = GetCurrentEntryIndex();
865 } else if (IsInitialNavigation() && pending_entry_) {
866 // If we are reloading the initial navigation, just use the current
867 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32868 entry = pending_entry_;
869 // The pending entry might be in entries_ (e.g., after a Clone), so we
870 // should also update the current_index.
871 current_index = pending_entry_index_;
872 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00873 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32874 current_index = GetCurrentEntryIndex();
875 if (current_index != -1) {
creis3da03872015-02-20 21:12:32876 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32877 }
[email protected]979a4bc2013-04-24 01:27:15878 }
[email protected]241db352013-04-22 18:04:05879
[email protected]59167c22013-06-03 18:07:32880 // If we are no where, then we can't reload. TODO(darin): We should add a
881 // CanReload method.
882 if (!entry)
883 return;
884
Rakina Zata Amnif297a802022-01-18 03:53:43885 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
886 // We should never navigate to an existing initial NavigationEntry that is
887 // the initial NavigationEntry for the initial empty document that hasn't
888 // been overridden by the synchronous about:blank commit, to preserve
889 // legacy behavior where trying to reload when the main frame is on the
890 // initial empty document won't result in a navigation. See also
891 // https://crbug.com/1277414.
892 return;
893 }
894
Aran Gilman37d11632019-10-08 23:07:15895 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30896 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07897 // they really want to do this. If they do, the dialog will call us back
898 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57899 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02900
[email protected]106a0812010-03-18 00:15:12901 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57902 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47903 return;
initial.commit09911bf2008-07-26 23:55:29904 }
Lei Zhang96031532019-10-10 19:05:47905
Wang Huia25efabc2022-09-24 17:27:22906 // Set ReloadType for |entry|.
907 entry->set_reload_type(reload_type);
908
Lei Zhang96031532019-10-10 19:05:47909 if (!IsInitialNavigation())
910 DiscardNonCommittedEntries();
911
912 pending_entry_ = entry;
913 pending_entry_index_ = current_index;
914 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
915
Nate Chapin45f620582021-09-30 17:45:43916 // location.reload() goes through BeginNavigation, so all reloads triggered
917 // via this codepath are browser initiated.
Nate Chapinbf682fa32022-09-26 22:41:20918 NavigateToExistingPendingEntry(reload_type, nullptr /* initiator_frame */,
919 nullptr /* navigation_api_key */);
initial.commit09911bf2008-07-26 23:55:29920}
921
[email protected]d202a7c2012-01-04 07:53:47922void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48923 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12924}
925
[email protected]d202a7c2012-01-04 07:53:47926void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49927 // If the pending reload type has been cleared by another navigation
928 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48929 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49930 return;
[email protected]106a0812010-03-18 00:15:12931 }
Wang Hui96ab1012022-10-11 02:05:49932 Reload(pending_reload_, false);
933 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12934}
935
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57936bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09937 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11938}
939
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57940bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni2322f4f82022-01-24 13:24:24941 if (blink::features::IsInitialNavigationEntryEnabled()) {
942 // Check that we're on the initial NavigationEntry and that this is not a
943 // cloned tab.
944 return IsInitialNavigation() && GetEntryCount() == 1 &&
945 GetLastCommittedEntry()->IsInitialEntry() &&
946 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
947 } else {
948 return IsInitialNavigation() && GetEntryCount() == 0;
949 }
creis10a4ab72015-10-13 17:22:40950}
951
Aran Gilman37d11632019-10-08 23:07:15952NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
953 int nav_entry_id) const {
avi254eff02015-07-01 08:27:58954 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:03955 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:58956}
957
Adithya Srinivasan9b0c99c2021-08-10 15:19:45958NavigationEntryImpl*
959NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
960 int nav_entry_id) const {
961 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
962 if (entry)
963 return entry;
964 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:52965 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:45966 : nullptr;
967}
968
W. James MacLeanc07dc41b2022-07-25 18:52:16969void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:57970 const url::Origin& origin) {
971 for (int i = 0; i < GetEntryCount(); i++) {
972 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:16973 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57974 }
975 if (entry_replaced_by_post_commit_error_) {
976 // It's possible we could come back to this entry if the error
977 // page/interstitial goes away.
978 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:16979 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57980 }
W. James MacLean1c40862c2020-04-27 21:05:57981}
982
avi25764702015-06-23 15:43:37983void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:57984 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:00985 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:37986 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:27987 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:20988}
989
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57990NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:47991 if (pending_entry_)
992 return pending_entry_;
993 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:20994}
995
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57996NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:32997 // The pending entry is safe to return for new (non-history), browser-
998 // initiated navigations. Most renderer-initiated navigations should not
999 // show the pending entry, to prevent URL spoof attacks.
1000 //
1001 // We make an exception for renderer-initiated navigations in new tabs, as
1002 // long as no other page has tried to access the initial empty document in
1003 // the new tab. If another page modifies this blank page, a URL spoof is
1004 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321005 bool safe_to_show_pending =
1006 pending_entry_ &&
1007 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091008 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321009 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461010 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321011
1012 // Also allow showing the pending entry for history navigations in a new tab,
1013 // such as Ctrl+Back. In this case, no existing page is visible and no one
1014 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151015 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1016 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321017 safe_to_show_pending = true;
1018
1019 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191020 return pending_entry_;
1021 return GetLastCommittedEntry();
1022}
1023
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571024int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201025 if (pending_entry_index_ != -1)
1026 return pending_entry_index_;
1027 return last_committed_entry_index_;
1028}
1029
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571030NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni2322f4f82022-01-24 13:24:241031 if (last_committed_entry_index_ == -1) {
1032 // The last committed entry must always exist when InitialNavigationEntry
1033 // is enabled. TODO(https://crbug.com/524208): Remove this case and all
1034 // related nullchecks entirely.
1035 DCHECK(!blink::features::IsInitialNavigationEntryEnabled());
Ivan Kotenkov2c0d2bb32017-11-01 15:41:281036 return nullptr;
Rakina Zata Amni2322f4f82022-01-24 13:24:241037 }
avif16f85a72015-11-13 18:25:031038 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201039}
1040
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571041bool NavigationControllerImpl::CanViewSource() {
Jeremy Roman2d8dfe132021-07-06 20:51:261042 const std::string& mime_type =
1043 frame_tree_.root()->current_frame_host()->GetPage().contents_mime_type();
Kinuko Yasuda74702f92017-07-31 03:27:531044 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1045 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271046 NavigationEntry* visible_entry = GetVisibleEntry();
1047 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391048 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161049}
1050
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571051int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271052 // The last committed entry index must always be less than the number of
Rakina Zata Amni2322f4f82022-01-24 13:24:241053 // entries. If there are no entries, it must be -1.
arthursonzogni5c4c202d2017-04-25 23:41:271054 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
Rakina Zata Amni2322f4f82022-01-24 13:24:241055 DCHECK(GetEntryCount() || last_committed_entry_index_ == -1);
[email protected]a26023822011-12-29 00:23:551056 return last_committed_entry_index_;
1057}
1058
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571059int NavigationControllerImpl::GetEntryCount() {
Carlos IL4dea8902020-05-26 15:14:291060 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551061 return static_cast<int>(entries_.size());
1062}
1063
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571064NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371065 if (index < 0 || index >= GetEntryCount())
1066 return nullptr;
1067
avif16f85a72015-11-13 18:25:031068 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251069}
1070
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571071NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471072 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201073}
1074
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571075int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461076 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031077}
1078
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571079bool NavigationControllerImpl::CanGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031080 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
1081 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1082 return true;
1083 }
1084 return false;
[email protected]765b35502008-08-21 00:51:201085}
1086
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571087bool NavigationControllerImpl::CanGoForward() {
WangHui74286d52021-03-31 16:17:151088 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1089 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1090 return true;
1091 }
1092 return false;
[email protected]765b35502008-08-21 00:51:201093}
1094
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571095bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031096 int index = GetIndexForOffset(offset);
1097 return index >= 0 && index < GetEntryCount();
1098}
1099
Xiaohan Wang7f8052e02022-01-14 18:44:281100#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151101bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151102 if (offset == 0)
1103 return true;
1104 int increment = offset > 0 ? 1 : -1;
1105 int non_skippable_entries = 0;
1106 for (int index = GetIndexForOffset(increment);
1107 index >= 0 && index < GetEntryCount(); index += increment) {
1108 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1109 non_skippable_entries++;
1110
1111 if (non_skippable_entries == std::abs(offset))
1112 return true;
1113 }
1114 return false;
1115}
1116#endif
1117
[email protected]d202a7c2012-01-04 07:53:471118void NavigationControllerImpl::GoBack() {
shivanisha55201872018-12-13 04:29:061119 int target_index = GetIndexForOffset(-1);
1120
Elly Fong-Jones40ee8112021-06-23 19:10:521121 // Move the target index past the skippable entries.
Shivani Sharma298d12852019-01-22 20:04:031122 bool all_skippable_entries = true;
Elly Fong-Jones40ee8112021-06-23 19:10:521123 while (target_index >= 0) {
1124 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui()) {
Shivani Sharma298d12852019-01-22 20:04:031125 all_skippable_entries = false;
shivanisha55201872018-12-13 04:29:061126 break;
Shivani Sharma2d5b4b6b2019-01-08 16:07:161127 }
Elly Fong-Jones40ee8112021-06-23 19:10:521128 target_index--;
shivanisha55201872018-12-13 04:29:061129 }
Miyoung Shin1c565c912021-03-17 12:11:211130
Shivani Sharma298d12852019-01-22 20:04:031131 // Do nothing if all entries are skippable. Normally this path would not
1132 // happen as consumers would have already checked it in CanGoBack but a lot of
1133 // tests do not do that.
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421134 if (all_skippable_entries)
Shivani Sharma298d12852019-01-22 20:04:031135 return;
shivanisha55201872018-12-13 04:29:061136
shivanisha55201872018-12-13 04:29:061137 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201138}
1139
[email protected]d202a7c2012-01-04 07:53:471140void NavigationControllerImpl::GoForward() {
shivanisha55201872018-12-13 04:29:061141 int target_index = GetIndexForOffset(1);
1142
Shivani Sharma2d5b4b6b2019-01-08 16:07:161143 // Note that at least one entry (the last one) will be non-skippable since
1144 // entries are marked skippable only when they add another entry because of
1145 // redirect or pushState.
Elly Fong-Jones40ee8112021-06-23 19:10:521146 while (target_index < static_cast<int>(entries_.size())) {
1147 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui())
shivanisha55201872018-12-13 04:29:061148 break;
Elly Fong-Jones40ee8112021-06-23 19:10:521149 target_index++;
shivanisha55201872018-12-13 04:29:061150 }
shivanisha55201872018-12-13 04:29:061151 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201152}
1153
[email protected]d202a7c2012-01-04 07:53:471154void NavigationControllerImpl::GoToIndex(int index) {
Nate Chapinbf682fa32022-09-26 22:41:201155 GoToIndex(index, nullptr /* initiator_frame */,
1156 nullptr /* navigation_api_key */);
Dave Tapuska8bfd84c2019-03-26 20:47:161157}
1158
Nate Chapinbf682fa32022-09-26 22:41:201159void NavigationControllerImpl::GoToIndex(
1160 int index,
1161 RenderFrameHostImpl* initiator_rfh,
1162 const std::string* navigation_api_key) {
Rakina Zata Amnid605d462022-06-01 10:17:031163 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
sunjian30574a62017-03-21 21:39:441164 TRACE_EVENT0("browser,navigation,benchmark",
1165 "NavigationControllerImpl::GoToIndex");
[email protected]765b35502008-08-21 00:51:201166 if (index < 0 || index >= static_cast<int>(entries_.size())) {
1167 NOTREACHED();
1168 return;
1169 }
1170
Rakina Zata Amnif297a802022-01-18 03:53:431171 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1172 // We should never navigate to an existing initial NavigationEntry that is
1173 // the initial NavigationEntry for the initial empty document that hasn't
1174 // been overridden by the synchronous about:blank commit, to preserve
1175 // legacy behavior where trying to reload when the main frame is on the
1176 // initial empty document won't result in a navigation. See also
1177 // https://crbug.com/1277414.
1178 return;
1179 }
1180
[email protected]cbab76d2008-10-13 22:42:471181 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201182
arthursonzogni5c4c202d2017-04-25 23:41:271183 DCHECK_EQ(nullptr, pending_entry_);
1184 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431185
arthursonzogni5c4c202d2017-04-25 23:41:271186 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201187 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271188 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1189 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201190 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
1191 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201192}
1193
[email protected]d202a7c2012-01-04 07:53:471194void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121195 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031196 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201197 return;
1198
[email protected]9ba14052012-06-22 23:50:031199 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201200}
1201
Nate Chapinbf682fa32022-09-26 22:41:201202void NavigationControllerImpl::GoToOffsetFromRenderer(
1203 int offset,
1204 RenderFrameHostImpl* initiator_rfh) {
Nate Chapin45f620582021-09-30 17:45:431205 // Note: This is actually reached in unit tests.
1206 if (!CanGoToOffset(offset))
1207 return;
1208
Nate Chapinbf682fa32022-09-26 22:41:201209 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
1210 nullptr /* navigation_api_key */);
Nate Chapin45f620582021-09-30 17:45:431211}
1212
Xiaohan Wang7f8052e02022-01-14 18:44:281213#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151214void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1215 // Note: This is actually reached in unit tests.
1216 if (!CanGoToOffsetWithSkipping(offset))
1217 return;
1218
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421219 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151220 GoToIndex(GetIndexForOffset(offset));
1221 return;
1222 }
1223 int increment = offset > 0 ? 1 : -1;
1224 // Find the offset without counting skippable entries.
1225 int target_index = GetIndexForOffset(increment);
1226 int non_skippable_entries = 0;
1227 for (int index = target_index; index >= 0 && index < GetEntryCount();
1228 index += increment) {
1229 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1230 non_skippable_entries++;
1231
1232 if (non_skippable_entries == std::abs(offset)) {
1233 target_index = index;
1234 break;
1235 }
1236 }
1237
1238 GoToIndex(target_index);
1239}
1240#endif
1241
[email protected]41374f12013-07-24 02:49:281242bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151243 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281244 return false;
[email protected]6a13a6c2011-12-20 21:47:121245
[email protected]43032342011-03-21 14:10:311246 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281247 return true;
[email protected]cbab76d2008-10-13 22:42:471248}
1249
Michael Thiessen9b14d512019-09-23 21:19:471250void NavigationControllerImpl::PruneForwardEntries() {
1251 DiscardNonCommittedEntries();
1252 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471253 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471254 if (num_removed <= 0)
1255 return;
Nate Chapin9eb16be72022-09-23 22:54:311256 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471257 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1258 NotifyPrunedEntries(this, remove_start_index /* start index */,
1259 num_removed /* count */);
1260}
1261
Aran Gilman37d11632019-10-08 23:07:151262void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1263 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321264 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311265 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511266 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1267 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321268 }
1269}
1270
Harkiran Bolariaba823e42021-05-21 18:30:361271base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1272 const GURL& url,
1273 const Referrer& referrer,
1274 ui::PageTransition transition,
1275 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471276 LoadURLParams params(url);
1277 params.referrer = referrer;
1278 params.transition_type = transition;
1279 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361280 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471281}
1282
Harkiran Bolariaba823e42021-05-21 18:30:361283base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1284 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061285 if (params.is_renderer_initiated)
1286 DCHECK(params.initiator_origin.has_value());
1287
naskob8744d22014-08-28 17:07:431288 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151289 "NavigationControllerImpl::LoadURLWithParams", "url",
1290 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291291 bool is_explicit_navigation =
1292 GetContentClient()->browser()->IsExplicitNavigation(
1293 params.transition_type);
1294 if (HandleDebugURL(params.url, params.transition_type,
1295 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431296 // If Telemetry is running, allow the URL load to proceed as if it's
1297 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491298 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431299 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361300 return nullptr;
[email protected]47752982014-07-29 08:01:431301 }
[email protected]8bf1048012012-02-08 01:22:181302
[email protected]cf002332012-08-14 19:17:471303 // Checks based on params.load_type.
1304 switch (params.load_type) {
1305 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431306 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471307 break;
1308 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261309 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471310 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361311 return nullptr;
[email protected]cf002332012-08-14 19:17:471312 }
1313 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461314 }
[email protected]e47ae9472011-10-13 19:48:341315
[email protected]e47ae9472011-10-13 19:48:341316 // The user initiated a load, we don't need to reload anymore.
1317 needs_reload_ = false;
1318
Harkiran Bolariaba823e42021-05-21 18:30:361319 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441320}
1321
Mohamed Abdelhalim833de902019-09-16 17:41:451322bool NavigationControllerImpl::PendingEntryMatchesRequest(
1323 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191324 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451325 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191326}
1327
[email protected]d202a7c2012-01-04 07:53:471328bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321329 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071330 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331331 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441332 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251333 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471334 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131335 NavigationRequest* navigation_request) {
1336 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331337
1338 // Note: validation checks and renderer kills due to invalid commit messages
1339 // must happen before getting here, in
1340 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1341 // effects of the navigation have already occurred.
1342
[email protected]cd2e15742013-03-08 04:08:311343 is_initial_navigation_ = false;
1344
Wang Hui96ab1012022-10-11 02:05:491345 // Any pending request to repost a form submission is no longer valid, since a
1346 // different NavigationEntry is committing.
1347 pending_reload_ = ReloadType::NONE;
1348
[email protected]0e8db942008-09-24 21:21:481349 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431350 bool overriding_user_agent_changed = false;
[email protected]0e8db942008-09-24 21:21:481351 if (GetLastCommittedEntry()) {
Carlos IL42b416592019-10-07 23:10:361352 if (entry_replaced_by_post_commit_error_) {
Chris Bookholt27faf8d2022-01-20 01:03:331353 // Same document navigation events with a post-commit error should already
1354 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1355 // reaching here.
1356 CHECK(!is_same_document_navigation);
1357
Carlos IL42b416592019-10-07 23:10:361358 // Any commit while a post-commit error page is showing should put the
1359 // original entry back, replacing the error page's entry. This includes
1360 // reloads, where the original entry was used as the pending entry and
1361 // should now be at the correct index at commit time.
1362 entries_[last_committed_entry_index_] =
1363 std::move(entry_replaced_by_post_commit_error_);
1364 }
Fergal Daly8e33cf62020-12-12 01:06:071365 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
[email protected]a26023822011-12-29 00:23:551366 details->previous_entry_index = GetLastCommittedEntryIndex();
Charlie Reisf8cde712022-10-20 16:25:091367 if (PendingEntryMatchesRequest(navigation_request) &&
aelias100c9192017-01-13 00:01:431368 pending_entry_->GetIsOverridingUserAgent() !=
Charlie Reisf8cde712022-10-20 16:25:091369 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
aelias100c9192017-01-13 00:01:431370 overriding_user_agent_changed = true;
Charlie Reisf8cde712022-10-20 16:25:091371 }
Xiaohan Wang7f8052e02022-01-14 18:44:281372#if BUILDFLAG(IS_ANDROID)
Shu Yang5756fa422021-11-05 23:02:541373 // TODO(crbug.com/1266277): Clean up the logic of setting
1374 // |overriding_user_agent_changed| post-launch.
Shu Yangd7cb62142022-08-04 21:08:161375 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1376 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
Shu Yang5756fa422021-11-05 23:02:541377 // Must honor user agent overrides in the |navigation_request|, such as
1378 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1379 // result, besides comparing |pending_entry_|'s user agent against
1380 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1381 // agent against LastCommittedEntry's.
1382 if (navigation_request->is_overriding_user_agent() !=
1383 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1384 overriding_user_agent_changed = true;
1385 }
1386 }
Xiaohan Wang7f8052e02022-01-14 18:44:281387#endif // BUILDFLAG(IS_ANDROID)
[email protected]0e8db942008-09-24 21:21:481388 } else {
Gang Wu325f03f42021-02-25 20:00:461389 // GetLastCommittedEntry() is null, so this is the first entry.
Fergal Daly8e33cf62020-12-12 01:06:071390 details->previous_main_frame_url = GURL();
[email protected]0e8db942008-09-24 21:21:481391 details->previous_entry_index = -1;
Charlie Reisf8cde712022-10-20 16:25:091392 if (PendingEntryMatchesRequest(navigation_request) &&
1393 pending_entry_->GetIsOverridingUserAgent()) {
Gang Wu325f03f42021-02-25 20:00:461394 // Default setting is NOT override the user agent, so overriding the user
1395 // agent in first entry should be considered as user agent changed as
1396 // well.
1397 overriding_user_agent_changed = true;
1398 }
Xiaohan Wang7f8052e02022-01-14 18:44:281399#if BUILDFLAG(IS_ANDROID)
Shu Yang5756fa422021-11-05 23:02:541400 // TODO(crbug.com/1266277): Clean up the logic of setting
1401 // |overriding_user_agent_changed| post-launch.
Shu Yangd7cb62142022-08-04 21:08:161402 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1403 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
Shu Yang5756fa422021-11-05 23:02:541404 // Must honor user agent overrides in the |navigation_request|, such as
1405 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1406 // result, besides checking |pending_entry_|'s user agent, also need to
1407 // check |navigation_request|'s.
1408 if (navigation_request->is_overriding_user_agent()) {
1409 overriding_user_agent_changed = true;
1410 }
1411 }
Xiaohan Wang7f8052e02022-01-14 18:44:281412#endif // BUILDFLAG(IS_ANDROID)
[email protected]0e8db942008-09-24 21:21:481413 }
[email protected]ecd9d8702008-08-28 22:10:171414
Dave Tapuskaa2ab4f252021-07-08 21:31:281415 bool is_main_frame_navigation = !rfh->GetParent();
1416
Alexander Timind2f2e4f22019-04-02 20:04:531417 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1418 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281419 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141420 // BackForwardCacheMetrics to be associated with the new navigation's
1421 // NavigationEntry, by either creating a new object or reusing the previous
1422 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281423 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
1424 if (navigation_request->frame_tree_node()->frame_tree()->type() ==
1425 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141426 back_forward_cache_metrics = BackForwardCacheMetrics::
1427 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281428 GetLastCommittedEntry(), is_main_frame_navigation,
1429 params.document_sequence_number);
1430 }
Alexander Timind2f2e4f22019-04-02 20:04:531431 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281432 if (is_main_frame_navigation && !is_same_document_navigation) {
Alexander Timind2f2e4f22019-04-02 20:04:531433 if (NavigationEntryImpl* navigation_entry = GetLastCommittedEntry()) {
1434 if (auto* metrics = navigation_entry->back_forward_cache_metrics()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141435 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531436 }
1437 }
1438 }
1439
Charlie Reisf8cde712022-10-20 16:25:091440 // The renderer tells us whether the navigation replaces the current entry.
1441 // (See below for a case where we might override that.)
1442 details->did_replace_entry = params.should_replace_current_entry;
1443
fdegans9caf66a2015-07-30 21:10:421444 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111445 // except for restored entries. This should be true even if the current commit
1446 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291447 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481448 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081449 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111450
1451 // Only make changes based on the pending entry if the NavigationRequest
1452 // matches it. Otherwise, the pending entry may be for a different request
1453 // (e.g., if a slow history navigation is pending while an auto-subframe
1454 // commit occurs).
1455 if (PendingEntryMatchesRequest(navigation_request)) {
1456 // It is no longer necessary to consider the pending entry as restored.
1457 if (pending_entry_->IsRestored()) {
1458 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1459 was_restored = true;
1460 }
[email protected]e9ba4472008-09-14 15:42:431461
Charlie Reisf8cde712022-10-20 16:25:091462 // If the SiteInstance has changed from the matching pending entry, this
1463 // must be treated as a new navigation with replacement. Set the replacement
1464 // bit here and ClassifyNavigation will identify this case and return
1465 // NEW_ENTRY.
1466 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1467 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1468 DCHECK_NE(-1, pending_entry_index_);
1469 // TODO(nasko,creis): Instead of setting this value here, set
1470 // should_replace_current_entry on the parameters we send to the
1471 // renderer process as part of CommitNavigation. The renderer should
1472 // in turn send it back here as part of |params| and it can be just
1473 // enforced and renderer process terminated on mismatch.
1474 details->did_replace_entry = true;
1475 }
Nasko Oskovaee2f862018-06-15 00:05:521476 }
[email protected]bcd904482012-02-01 01:54:221477
[email protected]e9ba4472008-09-14 15:42:431478 // Do navigation-type specific actions. These will make and commit an entry.
Rakina Zata Amni2322f4f82022-01-24 13:24:241479 details->type = ClassifyNavigation(rfh, params, navigation_request);
shivanigithub189833f2022-04-27 18:08:451480
1481 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node()) &&
1482 GetLastCommittedEntry()) {
1483 // Ensure that this navigation does not add a navigation entry, since
1484 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1485 // beyond the last committed one. Therefore, `should_replace_current_entry`
1486 // should be set, which replaces the current entry, or this should be a
1487 // reload, which does not create a new entry.
1488 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1489 // navigation that is restored will not be creating a new entry anyways, so
1490 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1491 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1492 // pointed out in the issue.
1493 DCHECK(params.should_replace_current_entry ||
1494 navigation_request->GetReloadType() != ReloadType::NONE ||
1495 details->type == NAVIGATION_TYPE_AUTO_SUBFRAME);
1496 }
1497
Rakina Zata Amni2322f4f82022-01-24 13:24:241498 if (GetLastCommittedEntry() && GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551499 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241500 // This is a subframe navigation on the initial empty document, which used
1501 // to not have a NavigationEntry to attach to. Now it can attach to the
1502 // initial NavigationEntry, and we must ensure that its NavigationEntry
1503 // will keep the "initial NavigationEntry" status and won't append a new
1504 // NavigationEntry (it should always do replacement instead).
1505 // See also https://crbug.com/1277414.
1506 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551507 // Subframe navigation on initial NavigationEntry must not append a new
1508 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1509 // means every subframe navigation that happens while we're on the initial
1510 // NavigationEntry will always reuse the existing NavigationEntry and
1511 // just update the corresponding FrameNavigationEntry.
1512 DCHECK_EQ(details->type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1513 } else if (details->type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
1514 // This is a navigation that modifies the initial NavigationEntry, either
1515 // for a replacement or a reload. The initial NavigationEntry should
1516 // retain its "initial NavigationEntry" status in this case.
1517 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241518 } else if (navigation_request->is_synchronous_renderer_commit() &&
1519 !navigation_request->IsSameDocument() && !rfh->GetParent() &&
1520 params.should_replace_current_entry) {
1521 // This is a synchronous about:blank navigation on the main frame, which
1522 // used to not create a NavigationEntry when we have no NavigationEntry on
1523 // FrameTree creation. We now have the initial NavigationEntry and are on
1524 // the initial NavigationEntry. To preserve old behavior, we should still
1525 // keep the "initial" status for the new NavigationEntry that we will
1526 // create for this navigation, so that subframe navigations under the
1527 // synchronously committed about:blank document will never append new
1528 // NavigationEntry, and instead will just reuse the initial
1529 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1530 // See also https://crbug.com/1277414.
1531 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551532 }
1533 }
1534 DCHECK(!details->should_stay_as_initial_entry ||
1535 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201536
eugenebutee08663a2017-04-27 17:43:121537 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441538 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121539
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071540 details->is_prerender_activation =
1541 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241542 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1543 ->GetOutermostMainFrame()
1544 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071545
Peter Boströmd7592132019-01-30 04:50:311546 // Make sure we do not discard the pending entry for a different ongoing
1547 // navigation when a same document commit comes in unexpectedly from the
1548 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1549 // other navigation types. See https://crbug.com/900036.
1550 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061551 bool keep_pending_entry =
1552 is_same_document_navigation &&
1553 details->type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
1554 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311555
[email protected]0e8db942008-09-24 21:21:481556 switch (details->type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061557 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491558 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051559 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001560 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431561 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061562 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491563 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1564 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001565 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431566 break;
[email protected]8ff00d72012-10-23 19:12:211567 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471568 RendererDidNavigateNewSubframe(
1569 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001570 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431571 break;
[email protected]8ff00d72012-10-23 19:12:211572 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391573 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251574 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001575 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081576 // We don't send a notification about auto-subframe PageState during
1577 // UpdateStateForFrame, since it looks like nothing has changed. Send
1578 // it here at commit time instead.
1579 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431580 return false;
creis59d5a47cb2016-08-24 23:57:191581 }
[email protected]e9ba4472008-09-14 15:42:431582 break;
Rakina Zata Amni2322f4f82022-01-24 13:24:241583 case NAVIGATION_TYPE_NAV_IGNORE:
1584 // If a pending navigation was in progress, this canceled it. We should
1585 // discard it and make sure it is removed from the URL bar. After that,
1586 // there is nothing we can do with this navigation, so we just return to
1587 // the caller that nothing has happened.
1588 if (pending_entry_)
1589 DiscardNonCommittedEntries();
1590 return false;
Aran Gilman37d11632019-10-08 23:07:151591 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431592 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151593 break;
[email protected]765b35502008-08-21 00:51:201594 }
1595
[email protected]688aa65c62012-09-28 04:32:221596 // At this point, we know that the navigation has just completed, so
1597 // record the time.
1598 //
1599 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261600 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331601 base::Time timestamp =
1602 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1603 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131604 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221605
Peter Boströmd7592132019-01-30 04:50:311606 // If we aren't keeping the pending entry, there shouldn't be one at this
1607 // point. Clear it again in case any error cases above forgot to do so.
1608 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1609 // been cleared instead of protecting against it.
1610 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551611 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141612
[email protected]e9ba4472008-09-14 15:42:431613 // All committed entries should have nonempty content state so WebKit doesn't
1614 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471615 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321616 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221617 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441618 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141619
Alexander Timind2f2e4f22019-04-02 20:04:531620 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1621 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281622 if (back_forward_cache_metrics &&
1623 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531624 active_entry->set_back_forward_cache_metrics(
1625 std::move(back_forward_cache_metrics));
1626 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281627
1628 // `back_forward_cache_metrics()` may return null as we do not record
1629 // back-forward cache metrics for navigations in non-primary frame trees.
1630 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141631 // TODO(https://crbug.com/1338089): Remove this.
1632 // These are both only available from details at this point, so we capture
1633 // them here.
1634 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
1635 details->type);
1636 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1637 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281638 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1639 navigation_request,
1640 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1641 }
naskoc7533512016-05-06 17:01:121642
Charles Reisc0507202017-09-21 00:40:021643 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1644 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1645 // A mismatch can occur if the renderer lies or due to a unique name collision
1646 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121647 FrameNavigationEntry* frame_entry =
1648 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021649 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1650 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031651 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081652 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1653 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031654 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201655
1656 // Remember the bindings the renderer process has at this point, so that
1657 // we do not grant this entry additional bindings if we come back to it.
1658 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301659 }
[email protected]132e281a2012-07-31 18:32:441660
[email protected]97d8f0d2013-10-29 16:49:211661 // Once it is committed, we no longer need to track several pieces of state on
1662 // the entry.
naskoc7533512016-05-06 17:01:121663 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131664
[email protected]49bd30e62011-03-22 20:12:591665 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221666 // TODO(creis): This check won't pass for subframes until we create entries
1667 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001668 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421669 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591670
[email protected]e9ba4472008-09-14 15:42:431671 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001672 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001673 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311674 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531675
arthursonzogni7ddc6542021-04-09 09:16:501676 active_entry->SetIsOverridingUserAgent(
1677 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031678
[email protected]93f230e02011-06-01 14:40:001679 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291680
aelias100c9192017-01-13 00:01:431681 if (overriding_user_agent_changed)
1682 delegate_->UpdateOverridingUserAgent();
1683
creis03b48002015-11-04 00:54:561684 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1685 // one knows the latest NavigationEntry it is showing (whether it has
1686 // committed anything in this navigation or not). This allows things like
1687 // state and title updates from RenderFrames to apply to the latest relevant
1688 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381689 int nav_entry_id = active_entry->GetUniqueID();
Carlos Caballero40b0efd2021-01-26 11:55:001690 for (FrameTreeNode* node : frame_tree_.Nodes())
dcheng57e39e22016-01-21 00:25:381691 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431692
1693 if (navigation_request->IsPrerenderedPageActivation()) {
1694 BroadcastHistoryOffsetAndLength();
1695 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1696 // is activated. As a result, a "prerenderingchange" event listener sees the
1697 // history.length which is not updated yet. We should guarantee that
1698 // history's length and offset should be updated before a
1699 // "prerenderingchange" event listener runs. One possible approach is to use
1700 // the same IPC which "prerenderingchange" uses, and propagate history's
1701 // length and offset together with that.
1702 }
1703
[email protected]e9ba4472008-09-14 15:42:431704 return true;
initial.commit09911bf2008-07-26 23:55:291705}
1706
[email protected]8ff00d72012-10-23 19:12:211707NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321708 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101709 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241710 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591711 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511712 "ClassifyNavigation");
1713
avi7c6f35e2015-05-08 17:52:381714 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241715 // A new entry. We may or may not have a corresponding pending entry, and
1716 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001717 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491718 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061719 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381720 }
1721
Rakina Zata Amni2322f4f82022-01-24 13:24:241722 // When this is a new subframe navigation, we should have a committed page
1723 // in which it's a subframe. This may not be the case when an iframe is
1724 // navigated on a popup navigated to about:blank (the iframe would be
1725 // written into the popup by script on the main page). For these cases,
1726 // there isn't any navigation stuff we can do, so just ignore it.
1727 if (!GetLastCommittedEntry()) {
1728 trace_return.set_return_reason("new entry, no last committed, ignore");
1729 return NAVIGATION_TYPE_NAV_IGNORE;
1730 }
1731
1732 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511733 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381734 return NAVIGATION_TYPE_NEW_SUBFRAME;
1735 }
1736
Charlie Reisc0f17d2d2021-01-12 18:52:491737 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381738 DCHECK(!params.history_list_was_cleared);
1739
avi39c1edd32015-06-04 20:06:001740 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381741 // All manual subframes would be did_create_new_entry and handled above, so
1742 // we know this is auto.
Rakina Zata Amni2322f4f82022-01-24 13:24:241743 if (GetLastCommittedEntry()) {
1744 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1745 return NAVIGATION_TYPE_AUTO_SUBFRAME;
1746 }
1747
1748 // We ignore subframes created in non-committed pages; we'd appreciate if
1749 // people stopped doing that.
1750 trace_return.set_return_reason("subframe, no last commmited, ignore");
1751 return NAVIGATION_TYPE_NAV_IGNORE;
avi7c6f35e2015-05-08 17:52:381752 }
1753
Rakina Zata Amnif6950d552020-11-24 03:26:101754 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1755 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381756 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1757 // create a new page.
1758
Rakina Zata Amni2322f4f82022-01-24 13:24:241759 // Just like above in the did_create_new_entry case, it's possible to
1760 // scribble onto an uncommitted page. Again, there isn't any navigation
1761 // stuff that we can do, so ignore it here as well.
1762 NavigationEntry* last_committed = GetLastCommittedEntry();
1763 if (!last_committed) {
1764 trace_return.set_return_reason("nav entry 0, no last committed, ignore");
1765 return NAVIGATION_TYPE_NAV_IGNORE;
1766 }
1767
Hayato Ito2ae49442021-07-02 02:59:251768 // This main frame navigation is not a history navigation (since
1769 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1770 // reload or a replacement navigation, which will modify the existing entry.
1771 //
Nasko Oskov332593c2018-08-16 17:21:341772 // TODO(nasko): With error page isolation, reloading an existing session
1773 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491774 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341775 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511776 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491777 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061778 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381779 }
1780
Charlie Reisf8cde712022-10-20 16:25:091781 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521782 // If the SiteInstance of the |pending_entry_| does not match the
1783 // SiteInstance that got committed, treat this as a new navigation with
1784 // replacement. This can happen if back/forward/reload encounters a server
1785 // redirect to a different site or an isolated error page gets successfully
1786 // reloaded into a different SiteInstance.
1787 if (pending_entry_->site_instance() &&
1788 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491789 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061790 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521791 }
creis77c9aa32015-09-25 19:59:421792
Nasko Oskovaee2f862018-06-15 00:05:521793 if (pending_entry_index_ == -1) {
1794 // In this case, we have a pending entry for a load of a new URL but Blink
1795 // didn't do a new navigation (params.did_create_new_entry). First check
1796 // to make sure Blink didn't treat a new cross-process navigation as
1797 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161798 // we must treat it as NEW rather than the converted reload case below,
1799 // since the new SiteInstance doesn't match the last committed entry.
Nasko Oskovaee2f862018-06-15 00:05:521800 if (!GetLastCommittedEntry() ||
1801 GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161802 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061803 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521804 }
1805
1806 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161807 // We will create a pending entry, but NavigateWithoutEntry will convert
1808 // it to a reload since it's the same page and not create a new entry for
1809 // it. (The user doesn't want to have a new back/forward entry when they
1810 // do this.) Therefore we want to just ignore the pending entry and go
1811 // back to where we were (the "existing entry").
1812 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061813 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521814 }
avi7c6f35e2015-05-08 17:52:381815 }
1816
creis26d22632017-04-21 20:23:561817 // Everything below here is assumed to be an existing entry, but if there is
1818 // no last committed entry, we must consider it a new navigation instead.
Nasko Oskovae49e292020-08-13 02:08:511819 if (!GetLastCommittedEntry()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491820 trace_return.set_return_reason("no last committed, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061821 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovae49e292020-08-13 02:08:511822 }
creis26d22632017-04-21 20:23:561823
Rakina Zata Amni153d5702021-09-13 22:48:001824 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381825 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491826 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1827 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161828 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061829 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381830 }
1831
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121832 if (navigation_request->DidEncounterError() &&
1833 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101834 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381835 // If the renderer was going to a new pending entry that got cleared because
1836 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491837 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381838 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511839 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491840 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061841 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381842 }
1843
Charlie Reisc0f17d2d2021-01-12 18:52:491844 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101845 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511846 trace_return.traced_value()->SetInteger("existing_entry_index",
1847 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381848 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441849 // The renderer has committed a navigation to an entry that no longer
1850 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491851 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061852 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381853 }
1854
avi7c6f35e2015-05-08 17:52:381855 // Since we weeded out "new" navigations above, we know this is an existing
1856 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491857 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061858 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381859}
1860
Rakina Zata Amni3460d382021-10-29 00:43:371861void NavigationControllerImpl::UpdateNavigationEntryDetails(
1862 NavigationEntryImpl* entry,
1863 RenderFrameHostImpl* rfh,
1864 const mojom::DidCommitProvisionalLoadParams& params,
1865 NavigationRequest* request,
1866 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001867 bool is_new_entry,
1868 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371869 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171870 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371871 entry->AddOrUpdateFrameEntry(
1872 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571873 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371874 rfh->GetSiteInstance(), nullptr, params.url,
1875 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171876 Referrer(*params.referrer),
1877 request ? request->common_params().initiator_origin : params.origin,
1878 request ? request->GetRedirectChain() : redirects, params.page_state,
1879 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
1880 (request && request->web_bundle_navigation_info())
Rakina Zata Amni3460d382021-10-29 00:43:371881 ? request->web_bundle_navigation_info()->Clone()
1882 : nullptr,
Rakina Zata Amniafd3c6582021-11-30 06:19:171883 (request ? request->GetSubresourceWebBundleNavigationInfo() : nullptr),
Rakina Zata Amni3460d382021-10-29 00:43:371884 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171885 rfh, request && request->IsSameDocument(),
1886 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371887
1888 if (rfh->GetParent()) {
1889 // Only modify the NavigationEntry for main frame navigations.
1890 return;
1891 }
1892 if (entry->update_virtual_url_with_url())
1893 UpdateVirtualURLToURL(entry, params.url);
1894 // Don't use the page type from the pending entry. Some interstitial page
1895 // may have set the type to interstitial. Once we commit, however, the page
1896 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171897 entry->set_page_type((request && request->DidEncounterError())
1898 ? PAGE_TYPE_ERROR
1899 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431900 if (commit_details && commit_details->should_stay_as_initial_entry) {
1901 // Retain the "initial NavigationEntry" status.
1902 if (request->IsSameDocument()) {
1903 // If this is for a same-document navigation, the NavigationEntry must be
1904 // reused and should already be marked as the initial NavigationEntry.
1905 DCHECK(entry->IsInitialEntry());
1906 } else {
1907 // If this is for a cross-document navigation, it can be caused by a
1908 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1909 // "for synchronous about:blank" in the latter case, and also when it is
1910 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1911 // is not for a synchronous about:blank commit.
1912 NavigationEntryImpl::InitialNavigationEntryState new_state =
1913 NavigationEntryImpl::InitialNavigationEntryState::
1914 kInitialNotForSynchronousAboutBlank;
1915 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1916 request->is_synchronous_renderer_commit()) {
1917 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1918 kInitialForSynchronousAboutBlank;
1919 }
1920 entry->set_initial_navigation_entry_state(new_state);
1921 }
1922 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1923 // Remove the "initial NavigationEntry" status.
1924 entry->set_initial_navigation_entry_state(
1925 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001926 }
Rakina Zata Amniddf10502022-01-15 02:56:551927
Rakina Zata Amni3460d382021-10-29 00:43:371928 if (is_new_entry) {
1929 // Some properties of the NavigationEntry are only set when the entry is
1930 // new (we aren't reusing it).
1931 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171932 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1933 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371934 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1935 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1936 } else {
1937 // We are reusing the NavigationEntry. The site instance will normally be
1938 // the same except for a few cases:
1939 // 1) session restore, when no site instance will be assigned or
1940 // 2) redirect, when the site instance is reset.
1941 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1942 entry->site_instance() == rfh->GetSiteInstance());
1943 }
1944}
1945
Rakina Zata Amniafd3c6582021-11-30 06:19:171946void NavigationControllerImpl::CreateInitialEntry() {
1947 DCHECK_EQ(entries_.size(), 0u);
1948 RenderFrameHostImpl* rfh = frame_tree_.root()->current_frame_host();
1949 auto params = mojom::DidCommitProvisionalLoadParams::New();
1950 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1951 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1952 // before we have initial NavigationEntries.
1953 params->url = GURL::EmptyGURL();
1954 params->http_status_code = 0;
1955 params->url_is_unreachable = false;
1956 params->method = "GET";
1957 params->should_replace_current_entry = false;
1958 params->post_id = -1;
1959 params->embedding_token = base::UnguessableToken::Create();
1960 params->navigation_token = base::UnguessableToken::Create();
1961 params->did_create_new_entry = true;
1962 params->origin = rfh->GetLastCommittedOrigin();
1963 params->should_update_history = true;
1964 params->item_sequence_number = 0;
1965 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151966 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171967 params->transition = is_in_fenced_frame_tree
1968 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1969 : ui::PAGE_TRANSITION_LINK;
1970 params->referrer = blink::mojom::Referrer::New();
1971
1972 // Create and insert the initial NavigationEntry.
1973 auto new_entry = std::make_unique<NavigationEntryImpl>(
1974 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
1975 rfh->GetLastCommittedOrigin(), std::u16string() /* title */,
1976 ui::PAGE_TRANSITION_TYPED, false /* renderer_initiated */,
1977 nullptr /* blob_url_loader_factory */, true /* is_initial_entry */);
1978 UpdateNavigationEntryDetails(
1979 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001980 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1981 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171982
1983 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1984 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001985 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171986}
1987
Charlie Reisc0f17d2d2021-01-12 18:52:491988void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321989 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071990 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361991 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441992 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471993 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001994 NavigationRequest* request,
1995 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571996 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071997 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451998 request->common_params().initiator_origin;
Lukasz Anforowicz435bcb582019-07-12 20:50:061999
creisf49dfc92016-07-26 17:05:182000 // First check if this is an in-page navigation. If so, clone the current
2001 // entry instead of looking at the pending entry, because the pending entry
2002 // does not have any subframe history items.
eugenebut604866f2017-05-10 21:35:362003 if (is_same_document && GetLastCommittedEntry()) {
Nate Chapin63db0d12022-01-20 22:03:302004 FrameNavigationEntry* previous_frame_entry =
2005 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452006 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482007 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572008 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082009 rfh->GetSiteInstance(), nullptr, params.url,
2010 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amni82fafba2021-03-11 07:07:092011 Referrer(*params.referrer), initiator_origin,
2012 request->GetRedirectChain(), params.page_state, params.method,
2013 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392014 nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482015 request->GetSubresourceWebBundleNavigationInfo(),
Antonio Sartori78a749f2020-11-30 12:03:392016 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302017 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572018 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302019 // FrameNavigationEntry.
2020 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572021 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032022
creisf49dfc92016-07-26 17:05:182023 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Harkiran Bolaria081c5c22021-09-13 08:44:532024 frame_entry, true, request->frame_tree_node(), frame_tree_.root());
Mike West800532c2021-10-14 09:26:522025 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2026 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572027 // TODO(jam): we had one report of this with a URL that was redirecting to
2028 // only tildes. Until we understand that better, don't copy the cert in
2029 // this case.
2030 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:572031 }
creisf49dfc92016-07-26 17:05:182032
Patrick Monette50e8bd82019-06-13 22:40:452033 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2034 // that |frame_entry| should now have a reference count of exactly 2: one
2035 // due to the local variable |frame_entry|, and another due to |new_entry|
2036 // also retaining one. This should never fail, because it's the main frame.
2037 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182038 }
2039
Harkiran Bolaria59290d62021-03-17 01:53:012040 // If this is an activation navigation from a prerendered page, transfer the
2041 // new entry from an entry already created and stored in the
2042 // NavigationRequest. |new_entry| will not have been set prior to this as
2043 // |is_same_document| is mutually exclusive with
2044 // |IsPrerenderedPageActivation|.
2045 if (request->IsPrerenderedPageActivation()) {
2046 DCHECK(!is_same_document);
2047 DCHECK(!new_entry);
2048 new_entry = request->TakePrerenderNavigationEntry();
2049 DCHECK(new_entry);
2050 }
2051
Charlie Reisc0f17d2d2021-01-12 18:52:492052 // Only make a copy of the pending entry if it is appropriate for the new
2053 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452054 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042055 // 1. The SiteInstance hasn't been assigned to something else.
2056 // 2. The pending entry was intended as a new entry, rather than being a
2057 // history navigation that was interrupted by an unrelated,
2058 // renderer-initiated navigation.
2059 // TODO(csharrison): Investigate whether we can remove some of the coarser
2060 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452061 if (!new_entry && PendingEntryMatchesRequest(request) &&
2062 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342063 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432064 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352065 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432066
Camille Lamy62b826012019-02-26 09:15:472067 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452068 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182069 }
2070
Charlie Reisc0f17d2d2021-01-12 18:52:492071 // For cross-document commits with no matching pending entry, create a new
2072 // entry.
creisf49dfc92016-07-26 17:05:182073 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062074 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072075 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
2076 initiator_origin,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582077 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452078 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172079 nullptr, // blob_url_loader_factory
2080 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242081
2082 // Find out whether the new entry needs to update its virtual URL on URL
2083 // change and set up the entry accordingly. This is needed to correctly
2084 // update the virtual URL when replaceState is called after a pushState.
2085 GURL url = params.url;
2086 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492087 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412088 // update the virtual URL based on the new URL. For example, this is needed
2089 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2090 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372091 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2092 &url, browser_context_, &needs_update);
2093 new_entry->set_update_virtual_url_with_url(needs_update);
2094
Camille Lamy62b826012019-02-26 09:15:472095 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452096 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432097 }
2098
Harkiran Bolaria59290d62021-03-17 01:53:012099 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
2100 // for prerendered contents, if any. This is because prerendering/activation
2101 // technically won't be creating a new document. Unlike BFCache, prerendering
2102 // creates a new NavigationEntry rather than using an existing one.
2103 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372104 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2105 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002106 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082107
Harkiran Bolaria59290d62021-03-17 01:53:012108 // history.pushState() is classified as a navigation to a new page, but sets
2109 // is_same_document to true. In this case, we already have the title and
2110 // favicon available, so set them immediately.
2111 if (is_same_document && GetLastCommittedEntry()) {
2112 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2113 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2114 }
[email protected]3a868f212014-08-09 10:41:192115 }
[email protected]ff64b3e2014-05-31 04:07:332116
[email protected]60d6cca2013-04-30 08:47:132117 DCHECK(!params.history_list_was_cleared || !replace_entry);
2118 // The browser requested to clear the session history when it initiated the
2119 // navigation. Now we know that the renderer has updated its state accordingly
2120 // and it is safe to also clear the browser side history.
2121 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552122 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132123 entries_.clear();
2124 last_committed_entry_index_ = -1;
2125 }
2126
Nasko Oskovaee2f862018-06-15 00:05:522127 // If this is a new navigation with replacement and there is a
2128 // pending_entry_ which matches the navigation reported by the renderer
2129 // process, then it should be the one replaced, so update the
2130 // last_committed_entry_index_ to use it.
2131 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092132 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522133 last_committed_entry_index_ = pending_entry_index_;
2134 }
2135
Alexander Timine3ec4192020-04-20 16:39:402136 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412137 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402138 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052139
Carlos IL42b416592019-10-07 23:10:362140 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312141 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152142 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432143}
2144
Charlie Reisc0f17d2d2021-01-12 18:52:492145void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322146 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072147 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362148 bool is_same_document,
jam48cea9082017-02-15 06:13:292149 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452150 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002151 bool keep_pending_entry,
2152 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562153 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2154 << "that a last committed entry exists.";
2155
[email protected]e9ba4472008-09-14 15:42:432156 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002157 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432158
Charlie Reis7e2cb6d2021-01-26 01:27:162159 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002160 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162161 // We're guaranteed to have a last committed entry if intended_as_new_entry
2162 // is true.
avicbdc4c12015-07-01 16:07:112163 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162164 DCHECK(entry);
2165
2166 // If the NavigationRequest matches a new pending entry and is classified as
2167 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2168 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092169 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162170 // Note: The pending entry will usually have a real ReloadType here, but
2171 // it can still be ReloadType::NONE in cases that
2172 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2173
2174 // If we classified this correctly, the SiteInstance should not have
2175 // changed.
2176 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2177
2178 // For converted reloads, we assign the entry's unique ID to be that of
2179 // the new one. Since this is always the result of a user action, we want
2180 // to dismiss infobars, etc. like a regular user-initiated navigation.
2181 entry->set_unique_id(pending_entry_->GetUniqueID());
2182
2183 // The extra headers may have changed due to reloading with different
2184 // headers.
2185 entry->set_extra_headers(pending_entry_->extra_headers());
2186 }
2187 // Otherwise, this was intended as a new entry but the pending entry was
2188 // lost in the meantime and no new entry was created. We are stuck at the
2189 // last committed entry.
2190
2191 // Even if this is a converted reload from pressing enter in the omnibox,
2192 // the server could redirect, requiring an update to the SSL status. If this
2193 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452194 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162195 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472196 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452197 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162198 }
Rakina Zata Amnif6950d552020-11-24 03:26:102199 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112200 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102201 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b90ce2016-09-01 16:58:162202
eugenebut604866f2017-05-10 21:35:362203 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452204 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362205 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2206 // this was a restored same document navigation entry, then it won't have
2207 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2208 // navigated it.
jam48cea9082017-02-15 06:13:292209 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522210 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2211 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292212 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2213 was_restored) {
2214 entry->GetSSL() = last_entry->GetSSL();
2215 }
2216 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452217 // In rapid back/forward navigations |request| sometimes won't have a cert
2218 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192219 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452220 if (request->GetSSLInfo().has_value() &&
2221 request->GetSSLInfo()->is_valid()) {
2222 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522223 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2224 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192225 entry->GetSSL() = SSLStatus();
2226 }
jam48cea9082017-02-15 06:13:292227 }
avicbdc4c12015-07-01 16:07:112228 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272229 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572230 // navigations that are EXISTING_ENTRY are same-document navigations that
2231 // result in replacement (e.g. history.replaceState(), location.replace(),
2232 // forced replacements for trivial session history contexts). For these
2233 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112234 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102235
Mikel Astizba9cf2fd2017-12-17 10:38:102236 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2237 // to avoid misleading interpretations (e.g. URLs paired with
2238 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2239 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2240 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2241
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572242 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102243
eugenebut604866f2017-05-10 21:35:362244 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452245 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362246 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472247 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452248 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112249 }
2250 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432251
Rakina Zata Amni3460d382021-10-29 00:43:372252 UpdateNavigationEntryDetails(entry, rfh, params, request,
2253 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002254 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302255
[email protected]5ccd4dc2012-10-24 02:28:142256 // The redirected to page should not inherit the favicon from the previous
2257 // page.
eugenebut604866f2017-05-10 21:35:362258 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482259 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142260
Peter Boströmd7592132019-01-30 04:50:312261 // We should also usually discard the pending entry if it corresponds to a
2262 // different navigation, since that one is now likely canceled. In rare
2263 // cases, we leave the pending entry for another navigation in place when we
2264 // know it is still ongoing, to avoid a flicker in the omnibox (see
2265 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432266 //
2267 // Note that we need to use the "internal" version since we don't want to
2268 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312269 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002270 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392271
Carlos IL4dea8902020-05-26 15:14:292272 // Update the last committed index to reflect the committed entry.
avicbdc4c12015-07-01 16:07:112273 last_committed_entry_index_ = GetIndexOfEntry(entry);
[email protected]e9ba4472008-09-14 15:42:432274}
2275
[email protected]d202a7c2012-01-04 07:53:472276void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322277 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072278 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362279 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472280 bool replace_entry,
2281 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002282 NavigationRequest* request,
2283 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262284 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2285 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552286 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2287 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112288
[email protected]e9ba4472008-09-14 15:42:432289 // Manual subframe navigations just get the current entry cloned so the user
2290 // can go back or forward to it. The actual subframe information will be
2291 // stored in the page state for each of those entries. This happens out of
2292 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092293 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2294 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382295
Mikel Astizba9cf2fd2017-12-17 10:38:102296 // The DCHECK below documents the fact that we don't know of any situation
2297 // where |replace_entry| is true for subframe navigations. This simplifies
2298 // reasoning about the replacement struct for subframes (see
2299 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2300 DCHECK(!replace_entry);
2301
Patrick Monette50e8bd82019-06-13 22:40:452302 // This FrameNavigationEntry might not end up being used in the
2303 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072304 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452305 request->common_params().initiator_origin;
Nate Chapin63db0d12022-01-20 22:03:302306 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2307 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2308 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572309 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302310 if (is_same_document) {
2311 FrameNavigationEntry* previous_frame_entry =
2312 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572313 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302314 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572315 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302316 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572317 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302318 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572319 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302320 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572321 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302322 policy_container_policies->referrer_policy);
2323 }
2324
Patrick Monette50e8bd82019-06-13 22:40:452325 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482326 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572327 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082328 rfh->GetSiteInstance(), nullptr, params.url,
2329 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amni82fafba2021-03-11 07:07:092330 Referrer(*params.referrer), initiator_origin, request->GetRedirectChain(),
arthursonzogni73fe3212020-11-17 13:24:072331 params.page_state, params.method, params.post_id,
2332 nullptr /* blob_url_loader_factory */,
Tsuyoshi Horo0c605782020-05-27 00:21:032333 request->web_bundle_navigation_info()
2334 ? request->web_bundle_navigation_info()->Clone()
Antonio Sartori78a749f2020-11-30 12:03:392335 : nullptr,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482336 request->GetSubresourceWebBundleNavigationInfo(),
Domenic Denicolacc094fb2022-03-16 23:40:572337 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032338
creisce0ef3572017-01-26 17:53:082339 std::unique_ptr<NavigationEntryImpl> new_entry =
2340 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452341 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Carlos Caballero40b0efd2021-01-26 11:55:002342 frame_tree_.root());
creise062d542015-08-25 02:01:552343
Alexander Timine3ec4192020-04-20 16:39:402344 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412345 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402346 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472347
creisce0ef3572017-01-26 17:53:082348 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452349 // to replace, which can happen due to a unique name change. See
2350 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2351 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382352
Dave Tapuska87696ae2021-11-18 18:48:312353 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152354 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432355}
2356
[email protected]d202a7c2012-01-04 07:53:472357bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322358 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072359 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392360 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252361 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002362 NavigationRequest* request,
2363 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292364 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2365 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2366
[email protected]e9ba4472008-09-14 15:42:432367 // We're guaranteed to have a previously committed entry, and we now need to
2368 // handle navigation inside of a subframe in it without creating a new entry.
2369 DCHECK(GetLastCommittedEntry());
2370
creis913c63ce2016-07-16 19:52:522371 // For newly created subframes, we don't need to send a commit notification.
2372 // This is only necessary for history navigations in subframes.
2373 bool send_commit_notification = false;
2374
Rakina Zata Amnif6950d552020-11-24 03:26:102375 // If |nav_entry_id| is non-zero and matches an existing entry, this
2376 // is a history navigation. Update the last committed index accordingly. If
2377 // we don't recognize the |nav_entry_id|, it might be a recently
2378 // pruned entry. We'll handle it below.
2379 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2380 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472381 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062382 // Make sure that a subframe commit isn't changing the main frame's
2383 // origin. Otherwise the renderer process may be confused, leading to a
2384 // URL spoof. We can't check the path since that may change
2385 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572386 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2387 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242388 // We should use checks similar to RenderFrameHostImpl's
2389 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2390 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572391 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2392 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2393 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2394 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522395 current_top_url.DeprecatedGetOriginAsURL() !=
2396 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442397 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512398 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062399 }
creis3cdc3b02015-05-29 23:00:472400
creis913c63ce2016-07-16 19:52:522401 // We only need to discard the pending entry in this history navigation
2402 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062403 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002404 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522405
2406 // History navigations should send a commit notification.
2407 send_commit_notification = true;
avi98405c22015-05-21 20:47:062408 }
[email protected]e9ba4472008-09-14 15:42:432409 }
[email protected]f233e4232013-02-23 00:55:142410
creisce0ef3572017-01-26 17:53:082411 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2412 // it may be a "history auto" case where we update an existing one.
2413 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372414
2415 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2416 // exists), or we may want to clobber it and create a new one. We update in
2417 // cases where the corresponding FrameNavigationEntry is conceptually similar
2418 // to the document described by the commit params: same-document
2419 // navigations, history traversal to an existing entry, and reloads (including
2420 // a "soft reload" where we navigate to the same url without flagging it as a
2421 // reload). But in the case of a different document that is not logically
2422 // related to the committed FrameNavigationEntry's document (cross-document,
2423 // not same url, not a reload, not a history traversal), we replace rather
2424 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252425 //
Nate Chapin9f169072021-06-09 19:32:372426 // In the case where we update, the FrameNavigationEntry will potentially be
2427 // shared across multiple NavigationEntries, and any updates will be reflected
2428 // in all of those NavigationEntries. In the replace case, any existing
2429 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252430 //
2431 // When navigating away from the initial empty document, we also update rather
2432 // than replace. Either update or replace will overwrite the initial empty
2433 // document state for |last_committed|, but if the FrameNavigationEntry for
2434 // the initial empty document is shared across multiple NavigationEntries (due
2435 // to a navigation in another frame), we want to make sure we overwrite the
2436 // initial empty document state everywhere this FrameNavigationEntry is used,
2437 // which is accompished by updating the existing FrameNavigationEntry.
Nate Chapin9f169072021-06-09 19:32:372438 FrameNavigationEntry* last_committed_frame_entry =
2439 last_committed->GetFrameEntry(rfh->frame_tree_node());
2440 NavigationEntryImpl::UpdatePolicy update_policy =
2441 NavigationEntryImpl::UpdatePolicy::kUpdate;
2442 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312443 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372444 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252445 last_committed_frame_entry->url() != params.url &&
2446 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372447 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2448 }
2449
Rakina Zata Amni3460d382021-10-29 00:43:372450 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002451 update_policy, false /* is_new_entry */,
2452 commit_details);
creis625a0c7d2015-03-24 23:17:122453
creis913c63ce2016-07-16 19:52:522454 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432455}
2456
[email protected]d202a7c2012-01-04 07:53:472457int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232458 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032459 for (size_t i = 0; i < entries_.size(); ++i) {
2460 if (entries_[i].get() == entry)
2461 return i;
2462 }
2463 return -1;
[email protected]765b35502008-08-21 00:51:202464}
2465
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572466void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242467 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572468 NavigationControllerImpl* source =
2469 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572470 // Verify that we look new.
Rakina Zata Amni2322f4f82022-01-24 13:24:242471 if (blink::features::IsInitialNavigationEntryEnabled()) {
2472 DCHECK_EQ(1, GetEntryCount());
2473 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
2474 } else {
2475 DCHECK_EQ(0, GetEntryCount());
2476 }
Lei Zhang96031532019-10-10 19:05:472477 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172478 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572479
Rakina Zata Amniafd3c6582021-11-30 06:19:172480 if (source->GetEntryCount() == 0) {
Rakina Zata Amniafd3c6582021-11-30 06:19:172481 return;
2482 }
[email protected]ce3fa3c2009-04-20 19:55:572483
Francois Dorayeaace782017-06-21 16:37:242484 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442485 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572486 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572487
Fergal Dalya1d569972021-03-16 03:24:532488 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302489 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532490 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2491 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302492 }
[email protected]4e6419c2010-01-15 04:50:342493
Lukasz Anforowicz0de0f452020-12-02 19:57:152494 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572495}
2496
Aran Gilman37d11632019-10-08 23:07:152497void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2498 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162499 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012500 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162501
[email protected]d202a7c2012-01-04 07:53:472502 NavigationControllerImpl* source =
2503 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252504
avi2b177592014-12-10 02:08:022505 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012506 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252507
[email protected]474f8512013-05-31 22:31:162508 // We now have one entry, possibly with a new pending entry. Ensure that
2509 // adding the entries from source won't put us over the limit.
2510 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572511 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572512 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252513
Carlos IL4dea8902020-05-26 15:14:292514 // Insert the entries from source. Ignore any pending entry, since it has not
2515 // committed in source.
[email protected]474f8512013-05-31 22:31:162516 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172517 DCHECK_NE(max_source_index, -1);
2518 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572519
2520 // Ignore the source's current entry if merging with replacement.
2521 // TODO(davidben): This should preserve entries forward of the current
2522 // too. http://crbug.com/317872
2523 if (replace_entry && max_source_index > 0)
2524 max_source_index--;
2525
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572526 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252527
2528 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552529 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142530
Hayato Ito2c8c08d02021-06-23 03:38:432531 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252532}
2533
[email protected]79368982013-11-13 01:11:012534bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162535 // If there is no last committed entry, we cannot prune. Even if there is a
2536 // pending entry, it may not commit, leaving this WebContents blank, despite
2537 // possibly giving it new entries via CopyStateFromAndPrune.
2538 if (last_committed_entry_index_ == -1)
2539 return false;
[email protected]9350602e2013-02-26 23:27:442540
[email protected]474f8512013-05-31 22:31:162541 // We cannot prune if there is a pending entry at an existing entry index.
2542 // It may not commit, so we have to keep the last committed entry, and thus
2543 // there is no sensible place to keep the pending entry. It is ok to have
2544 // a new pending entry, which can optionally commit as a new navigation.
2545 if (pending_entry_index_ != -1)
2546 return false;
2547
[email protected]474f8512013-05-31 22:31:162548 return true;
2549}
2550
[email protected]79368982013-11-13 01:11:012551void NavigationControllerImpl::PruneAllButLastCommitted() {
2552 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162553
avi2b177592014-12-10 02:08:022554 DCHECK_EQ(0, last_committed_entry_index_);
2555 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442556
Hayato Ito2c8c08d02021-06-23 03:38:432557 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442558}
2559
[email protected]79368982013-11-13 01:11:012560void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162561 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012562 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262563
Nate Chapin9eb16be72022-09-23 22:54:312564 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2565
[email protected]474f8512013-05-31 22:31:162566 // Erase all entries but the last committed entry. There may still be a
2567 // new pending entry after this.
2568 entries_.erase(entries_.begin(),
2569 entries_.begin() + last_committed_entry_index_);
2570 entries_.erase(entries_.begin() + 1, entries_.end());
2571 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262572}
2573
Christian Dullweber1af31e62018-02-22 11:49:482574void NavigationControllerImpl::DeleteNavigationEntries(
2575 const DeletionPredicate& deletionPredicate) {
2576 // It is up to callers to check the invariants before calling this.
2577 CHECK(CanPruneAllButLastCommitted());
2578 std::vector<int> delete_indices;
2579 for (size_t i = 0; i < entries_.size(); i++) {
2580 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572581 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482582 delete_indices.push_back(i);
2583 }
2584 }
2585 if (delete_indices.empty())
2586 return;
2587
2588 if (delete_indices.size() == GetEntryCount() - 1U) {
2589 PruneAllButLastCommitted();
2590 } else {
2591 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382592 for (const auto& index : base::Reversed(delete_indices)) {
2593 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482594 }
Hayato Ito2c8c08d02021-06-23 03:38:432595 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482596 }
2597 delegate()->NotifyNavigationEntriesDeleted();
2598}
2599
Shivani Sharma883f5f32019-02-12 18:20:012600bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2601 auto* entry = GetEntryAtIndex(index);
2602 return entry && entry->should_skip_on_back_forward_ui();
2603}
2604
Carlos Caballero35ce710c2019-09-19 10:59:452605BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2606 return back_forward_cache_;
2607}
2608
clamy987a3752018-05-03 17:36:262609void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2610 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2611 // progress, since this will cause a use-after-free. (We only allow this
2612 // when the tab is being destroyed for shutdown, since it won't return to
2613 // NavigateToEntry in that case.) http://crbug.com/347742.
Takashi Toyoshimaea534ef22021-07-21 03:27:592614 CHECK(!in_navigate_to_pending_entry_ || frame_tree_.IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262615
2616 if (was_failure && pending_entry_) {
2617 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2618 } else {
2619 failed_pending_entry_id_ = 0;
2620 }
2621
2622 if (pending_entry_) {
2623 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332624 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262625 pending_entry_index_ = -1;
2626 pending_entry_ = nullptr;
2627 }
arthursonzogni66f711c2019-10-08 14:40:362628
2629 // Ensure any refs to the current pending entry are ignored if they get
2630 // deleted, by clearing the set of known refs. All future pending entries will
2631 // only be affected by new refs.
2632 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262633}
2634
2635void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2636 if (pending_entry_)
2637 pending_entry_->set_ssl_error(error);
2638}
2639
Xiaohan Wang7f8052e02022-01-14 18:44:282640#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422641// static
2642bool NavigationControllerImpl::ValidateDataURLAsString(
2643 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2644 if (!data_url_as_string)
2645 return false;
2646
2647 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2648 return false;
2649
2650 // The number of characters that is enough for validating a data: URI.
2651 // From the GURL's POV, the only important part here is scheme, it doesn't
2652 // check the actual content. Thus we can take only the prefix of the url, to
2653 // avoid unneeded copying of a potentially long string.
2654 const size_t kDataUriPrefixMaxLen = 64;
2655 GURL data_url(
2656 std::string(data_url_as_string->front_as<char>(),
2657 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2658 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2659 return false;
2660
2661 return true;
2662}
2663#endif
2664
Shivani Sharma194877032019-03-07 17:52:472665void NavigationControllerImpl::NotifyUserActivation() {
2666 // When a user activation occurs, ensure that all adjacent entries for the
2667 // same document clear their skippable bit, so that the history manipulation
2668 // intervention does not apply to them.
2669 auto* last_committed_entry = GetLastCommittedEntry();
2670 if (!last_committed_entry)
2671 return;
Shivani Sharma194877032019-03-07 17:52:472672
shivanigithub99368382021-06-16 18:33:372673 if (base::FeatureList::IsEnabled(
2674 features::kDebugHistoryInterventionNoUserActivation)) {
2675 return;
2676 }
2677
Shivani Sharmac4cc8922019-04-18 03:11:172678 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472679}
2680
clamy987a3752018-05-03 17:36:262681bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2682 RenderFrameHostImpl* render_frame_host,
Julie Jeongeun Kimed2e5ba72019-09-12 10:14:172683 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client) {
clamy987a3752018-05-03 17:36:262684 NavigationEntryImpl* entry =
2685 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2686 if (!entry)
2687 return false;
2688
2689 FrameNavigationEntry* frame_entry =
2690 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2691 if (!frame_entry)
2692 return false;
2693
Nate Chapin45f620582021-09-30 17:45:432694 // |is_browser_initiated| is false here because a navigation in a new subframe
2695 // always begins with renderer action (i.e., an HTML element being inserted
2696 // into the DOM), so it is always renderer-initiated.
Camille Lamy5193caa2018-10-12 11:59:422697 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572698 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232699 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432700 true /* is_history_navigation_in_new_child */,
2701 false /* is_browser_initiated */);
clamyea99ea12018-05-28 13:54:232702
2703 if (!request)
2704 return false;
2705
arthursonzognif046d4a2019-12-12 19:08:102706 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412707
Lukasz Anforowicz9ee83c272020-12-01 20:14:052708 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2709 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232710
2711 return true;
clamy987a3752018-05-03 17:36:262712}
2713
Tsuyoshi Horo52fd08e2020-07-07 07:03:452714bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2715 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2716 if (!entry)
2717 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432718
2719 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2720 // We should never navigate to an existing initial NavigationEntry that is
2721 // the initial NavigationEntry for the initial empty document that hasn't
2722 // been overridden by the synchronous about:blank commit, to preserve
2723 // legacy behavior where trying to reload when the main frame is on the
2724 // initial empty document won't result in a navigation. See also
2725 // https://crbug.com/1277414.
2726 return false;
2727 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452728 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2729 if (!frame_entry)
2730 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142731 ReloadType reload_type = ReloadType::NORMAL;
2732 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452733 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142734 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452735 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432736 false /* is_history_navigation_in_new_child */,
2737 true /* is_browser_initiated */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452738 if (!request)
2739 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052740 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452741 return true;
2742}
2743
clamy987a3752018-05-03 17:36:262744void NavigationControllerImpl::NavigateFromFrameProxy(
2745 RenderFrameHostImpl* render_frame_host,
2746 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022747 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452748 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072749 const absl::optional<url::Origin>& initiator_origin,
clamy987a3752018-05-03 17:36:262750 bool is_renderer_initiated,
2751 SiteInstance* source_site_instance,
2752 const Referrer& referrer,
2753 ui::PageTransition page_transition,
2754 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252755 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262756 const std::string& method,
2757 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092758 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142759 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212760 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502761 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392762 const absl::optional<blink::Impression>& impression,
Nan Lin944e9b4e2022-04-12 13:51:222763 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492764 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462765 bool is_unfenced_top_navigation,
2766 bool force_new_browsing_instance) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582767 if (is_renderer_initiated)
2768 DCHECK(initiator_origin.has_value());
2769
clamy987a3752018-05-03 17:36:262770 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582771
Rakina Zata Amni2322f4f82022-01-24 13:24:242772 // Don't allow an entry replacement if there is no entry to replace.
2773 // http://crbug.com/457149
2774 if (GetEntryCount() == 0)
2775 should_replace_current_entry = false;
2776
clamy987a3752018-05-03 17:36:262777 // Create a NavigationEntry for the transfer, without making it the pending
2778 // entry. Subframe transfers should have a clone of the last committed entry
2779 // with a FrameNavigationEntry for the target frame. Main frame transfers
2780 // should have a new NavigationEntry.
2781 // TODO(creis): Make this unnecessary by creating (and validating) the params
2782 // directly, passing them to the destination RenderFrameHost. See
2783 // https://crbug.com/536906.
2784 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262785 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262786 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amni2322f4f82022-01-24 13:24:242787 if (GetLastCommittedEntry()) {
2788 entry = GetLastCommittedEntry()->Clone();
2789 entry->set_extra_headers(extra_headers);
2790 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2791 // Renderer-initiated navigation that target a remote frame are currently
2792 // classified as browser-initiated when this one has already navigated.
2793 // See https://crbug.com/722251.
2794 } else {
2795 // If there's no last committed entry, create an entry for about:blank
2796 // with a subframe entry for our destination.
2797 // TODO(creis): Ensure this case can't exist in https://crbug.com/524208.
2798 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
2799 GURL(url::kAboutBlankURL), referrer, initiator_origin,
2800 source_site_instance, page_transition, is_renderer_initiated,
2801 extra_headers, browser_context_,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172802 nullptr /* blob_url_loader_factory */,
2803 false /* rewrite_virtual_urls */));
Rakina Zata Amni2322f4f82022-01-24 13:24:242804 }
Rakina Zata Amniafd3c6582021-11-30 06:19:172805 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2806 // Renderer-initiated navigation that target a remote frame are currently
2807 // classified as browser-initiated when this one has already navigated.
2808 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372809 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2810 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2811 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2812 // same-document navigation), they will still be present in the
2813 // committed NavigationEntry that will be referenced to construct the new
2814 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262815 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082816 node, NavigationEntryImpl::UpdatePolicy::kReplace, -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 /* commit_origin */, referrer, initiator_origin,
Miyoung Shin5d77f72072020-10-09 15:14:202819 std::vector<GURL>(), blink::PageState(), method, -1,
Antonio Sartori78a749f2020-11-30 12:03:392820 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482821 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori79d549d2021-02-18 12:59:542822 nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262823 } else {
2824 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172825 // If `node` is the outermost main frame, it rewrites a virtual url in order
2826 // to adjust the original input url if needed. For inner frames such as
2827 // fenced frames or subframes, they don't rewrite urls as the urls are not
2828 // input urls by users.
2829 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy987a3752018-05-03 17:36:262830 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz641234d52019-11-07 21:07:102831 url, referrer, initiator_origin, source_site_instance, page_transition,
2832 is_renderer_initiated, extra_headers, browser_context_,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172833 blob_url_loader_factory, rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262834 entry->root_node()->frame_entry->set_source_site_instance(
2835 static_cast<SiteInstanceImpl*>(source_site_instance));
2836 entry->root_node()->frame_entry->set_method(method);
2837 }
clamy987a3752018-05-03 17:36:262838
Camille Lamy5193caa2018-10-12 11:59:422839 bool override_user_agent = false;
clamy987a3752018-05-03 17:36:262840 if (GetLastCommittedEntry() &&
2841 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
2842 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422843 override_user_agent = true;
clamy987a3752018-05-03 17:36:262844 }
2845 // TODO(creis): Set user gesture and intent received timestamp on Android.
2846
2847 // We may not have successfully added the FrameNavigationEntry to |entry|
2848 // above (per https://crbug.com/608402), in which case we create it from
2849 // scratch. This works because we do not depend on |frame_entry| being inside
2850 // |entry| during NavigateToEntry. This will go away when we shortcut this
2851 // further in https://crbug.com/536906.
2852 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2853 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452854 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082855 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582856 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072857 absl::nullopt /* origin */, referrer, initiator_origin,
Rakina Zata Amni3a1c0ec2021-04-15 03:35:122858 std::vector<GURL>(), blink::PageState(), method, -1,
2859 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482860 nullptr /* subresource_web_bundle_navigation_info */,
Nate Chapin63db0d12022-01-20 22:03:302861 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572862 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262863 }
2864
Camille Lamy5193caa2018-10-12 11:59:422865 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022866 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452867 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292868 params.initiator_origin = initiator_origin;
Camille Lamy5193caa2018-10-12 11:59:422869 params.source_site_instance = source_site_instance;
2870 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2871 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032872 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422873 params.referrer = referrer;
2874 /* params.redirect_chain: skip */
2875 params.extra_headers = extra_headers;
2876 params.is_renderer_initiated = is_renderer_initiated;
2877 params.override_user_agent = UA_OVERRIDE_INHERIT;
2878 /* params.base_url_for_data_url: skip */
2879 /* params.virtual_url_for_data_url: skip */
2880 /* params.data_url_as_string: skip */
2881 params.post_data = post_body;
2882 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582883 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422884 /* params.frame_name: skip */
2885 // TODO(clamy): See if user gesture should be propagated to this function.
2886 params.has_user_gesture = false;
2887 params.should_clear_history_list = false;
2888 params.started_from_context_menu = false;
2889 /* params.navigation_ui_data: skip */
2890 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222891 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542892 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212893 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412894 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502895 params.is_form_submission = is_form_submission;
Camille Lamy5193caa2018-10-12 11:59:422896
2897 std::unique_ptr<NavigationRequest> request =
2898 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032899 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142900 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392901 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492902 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
2903 is_unfenced_top_navigation);
clamyea99ea12018-05-28 13:54:232904
2905 if (!request)
2906 return;
2907
Garrett Tanzerbb8db412022-09-27 21:59:462908 // Force the navigation to take place in a new browsing instance.
2909 // This is used by _unfencedTop in fenced frames to ensure that navigations
2910 // leaving the fenced context create a new browsing instance.
2911 if (force_new_browsing_instance) {
2912 request->coop_status().ForceBrowsingInstanceSwap();
2913 }
2914
Arthur Hemery948742762019-09-18 10:06:242915 // At this stage we are proceeding with this navigation. If this was renderer
2916 // initiated with user gesture, we need to make sure we clear up potential
2917 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2918 DiscardNonCommittedEntries();
2919
Lukasz Anforowicz9ee83c272020-12-01 20:14:052920 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262921}
2922
[email protected]d1198fd2012-08-13 22:50:192923void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252924 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212925 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192926 if (!session_storage_namespace)
2927 return;
2928
2929 // We can't overwrite an existing SessionStorage without violating spec.
2930 // Attempts to do so may give a tab access to another tab's session storage
2931 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152932 bool successful_insert =
2933 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252934 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052935 static_cast<SessionStorageNamespaceImpl*>(
2936 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302937 .second;
2938 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192939}
2940
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572941bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amni2322f4f82022-01-24 13:24:242942 return IsInitialNavigation() &&
2943 (!GetLastCommittedEntry() ||
2944 GetLastCommittedEntry()->IsInitialEntry()) &&
Carlos Caballeroede6f8c2021-01-28 11:01:502945 !frame_tree_.has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462946}
2947
Aran Gilman37d11632019-10-08 23:07:152948SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252949 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302950 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252951 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032952 DOMStorageContextWrapper* context_wrapper =
2953 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2954
2955 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252956 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032957 if (it != session_storage_namespace_map_.end()) {
2958 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152959 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2960 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472961
michaelnbacbcbd2016-02-09 00:32:032962 return it->second.get();
2963 }
2964
2965 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102966 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2967 SessionStorageNamespaceImpl::Create(context_wrapper);
2968 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2969 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252970 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102971 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302972
Daniel Murphy31bbb8b12018-02-07 21:44:102973 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302974}
2975
2976SessionStorageNamespace*
2977NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252978 return GetSessionStorageNamespace(
2979 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302980}
2981
2982const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572983NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302984 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552985}
[email protected]d202a7c2012-01-04 07:53:472986
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572987bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562988 return needs_reload_;
2989}
[email protected]a26023822011-12-29 00:23:552990
[email protected]46bb5e9c2013-10-03 22:16:472991void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412992 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2993}
2994
2995void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472996 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412997 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542998
2999 if (last_committed_entry_index_ != -1) {
3000 entries_[last_committed_entry_index_]->SetTransitionType(
3001 ui::PAGE_TRANSITION_RELOAD);
3002 }
[email protected]46bb5e9c2013-10-03 22:16:473003}
3004
[email protected]d202a7c2012-01-04 07:53:473005void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573006 DCHECK_LT(index, GetEntryCount());
3007 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313008 DiscardNonCommittedEntries();
3009
Nate Chapin9eb16be72022-09-23 22:54:313010 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313011 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123012 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313013 last_committed_entry_index_--;
3014}
3015
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573016NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273017 // If there is no pending_entry_, there should be no pending_entry_index_.
3018 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3019
3020 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363021 // at that index. An exception is while a reload of a post commit error page
3022 // is ongoing; in that case pending entry will point to the entry replaced
3023 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273024 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363025 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3026 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273027
[email protected]022af742011-12-28 18:37:253028 return pending_entry_;
3029}
3030
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573031int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273032 // The pending entry index must always be less than the number of entries.
Rakina Zata Amni2322f4f82022-01-24 13:24:243033 // If there are no entries, it must be exactly -1.
arthursonzogni5c4c202d2017-04-25 23:41:273034 DCHECK_LT(pending_entry_index_, GetEntryCount());
Rakina Zata Amni2322f4f82022-01-24 13:24:243035 DCHECK(GetEntryCount() != 0 || pending_entry_index_ == -1);
[email protected]a26023822011-12-29 00:23:553036 return pending_entry_index_;
3037}
3038
avi25764702015-06-23 15:43:373039void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573040 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363041 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313042 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003043 bool in_fenced_frame_tree,
3044 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313045 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3046 // set because:
3047 // 1) They don't influence the history of the outer page.
3048 // 2) They are always replace only navigation (there is always only one entry
3049 // in their history stack).
3050 // 3) Are not top level navigations and appear similar to iframes.
3051 // Navigations of the fenced frame might create a new NavigationEntry, which
3052 // will call this function. Non fenced frame navigations will never have
3053 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3054 // InsertOrReplaceEntry.
3055 DCHECK_EQ(in_fenced_frame_tree,
3056 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3057 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203058
avi5cad4912015-06-19 05:25:443059 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3060 // need to keep continuity with the pending entry, so copy the pending entry's
3061 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3062 // then the renderer navigated on its own, independent of the pending entry,
3063 // so don't copy anything.
3064 if (pending_entry_ && pending_entry_index_ == -1)
3065 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203066
Rakina Zata Amnia4e27222021-12-22 01:05:003067 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203068
creisee17e932015-07-17 17:56:223069 // When replacing, don't prune the forward history.
Carlos IL42b416592019-10-07 23:10:363070 if ((replace || was_post_commit_error) && entries_.size() > 0) {
Mikel Astizba9cf2fd2017-12-17 10:38:103071 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573072 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363073 // If the new entry is a post-commit error page, we store the current last
3074 // committed entry to the side so that we can put it back when navigating
3075 // away from the error.
3076 if (was_post_commit_error) {
3077 DCHECK(!entry_replaced_by_post_commit_error_);
3078 entry_replaced_by_post_commit_error_ =
3079 std::move(entries_[last_committed_entry_index_]);
3080 }
dcheng36b6aec92015-12-26 06:16:363081 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223082 return;
3083 }
[email protected]765b35502008-08-21 00:51:203084
creis37979a62015-08-04 19:48:183085 // We shouldn't see replace == true when there's no committed entries.
3086 DCHECK(!replace);
3087
Michael Thiessen9b14d512019-09-23 21:19:473088 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203089
Shivani Sharmad8c8d652019-02-13 17:27:573090 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203091
dcheng36b6aec92015-12-26 06:16:363092 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203093 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293094}
3095
Shivani Sharmad8c8d652019-02-13 17:27:573096void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163097 if (entries_.size() < max_entry_count())
3098 return;
3099
3100 DCHECK_EQ(max_entry_count(), entries_.size());
3101 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573102 CHECK_EQ(pending_entry_index_, -1);
3103
3104 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423105 // Retrieve the oldest skippable entry.
3106 for (; index < GetEntryCount(); index++) {
3107 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3108 break;
Shivani Sharmad8c8d652019-02-13 17:27:573109 }
3110
3111 // If there is no skippable entry or if it is the last committed entry then
3112 // fall back to pruning the oldest entry. It is not safe to prune the last
3113 // committed entry.
3114 if (index == GetEntryCount() || index == last_committed_entry_index_)
3115 index = 0;
3116
3117 bool should_succeed = RemoveEntryAtIndex(index);
3118 DCHECK_EQ(true, should_succeed);
3119
3120 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253121}
3122
clamy3cb9bea92018-07-10 12:42:023123void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163124 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203125 RenderFrameHostImpl* initiator_rfh,
3126 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503127 TRACE_EVENT0("navigation",
3128 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273129 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023130 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363131 if (pending_entry_index_ != -1) {
3132 // The pending entry may not be in entries_ if a post-commit error page is
3133 // showing.
3134 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3135 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3136 }
Gyuyoung Kim107c2a02021-04-13 01:49:303137 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573138 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013139 needs_reload_ = false;
Carlos Caballero40b0efd2021-01-26 11:55:003140 FrameTreeNode* root = frame_tree_.root();
Arthur Sonzogni620cec62018-12-13 13:08:573141 int nav_entry_id = pending_entry_->GetUniqueID();
Nate Chapinbf682fa32022-09-26 22:41:203142 bool is_browser_initiated = !initiator_rfh;
Arthur Sonzogni620cec62018-12-13 13:08:573143
[email protected]83c2e232011-10-07 21:36:463144 // If we were navigating to a slow-to-commit page, and the user performs
3145 // a session history navigation to the last committed page, RenderViewHost
3146 // will force the throbber to start, but WebKit will essentially ignore the
3147 // navigation, and won't send a message to stop the throbber. To prevent this
3148 // from happening, we drop the navigation here and stop the slow-to-commit
3149 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023150 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083151 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273152 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Takashi Toyoshimabf549472021-07-01 07:47:203153 frame_tree_.StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123154
[email protected]83c2e232011-10-07 21:36:463155 DiscardNonCommittedEntries();
3156 return;
3157 }
3158
creisce0ef3572017-01-26 17:53:083159 // Compare FrameNavigationEntries to see which frames in the tree need to be
3160 // navigated.
clamy3cb9bea92018-07-10 12:42:023161 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3162 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Nate Chapin45f620582021-09-30 17:45:433163 FindFramesToNavigate(root, reload_type, is_browser_initiated,
3164 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303165
3166 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573167 // We were unable to match any frames to navigate. This can happen if a
3168 // history navigation targets a subframe that no longer exists
3169 // (https://crbug.com/705550). In this case, we need to update the current
3170 // history entry to the pending one but keep the main document loaded. We
3171 // also need to ensure that observers are informed about the updated
3172 // current history entry (e.g., for greying out back/forward buttons), and
3173 // that renderer processes update their history offsets. The easiest way
3174 // to do all that is to schedule a "redundant" same-document navigation in
3175 // the main frame.
3176 //
3177 // Note that we don't want to remove this history entry, as it might still
3178 // be valid later, since a frame that it's targeting may be recreated.
3179 //
3180 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3181 // need to repeat history navigations until finding the one that works.
3182 // Consider changing this behavior to keep looking for the first valid
3183 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023184 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423185 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573186 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573187 ReloadType::NONE /* reload_type */,
3188 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433189 false /* is_history_navigation_in_new_child */,
3190 is_browser_initiated);
clamy3cb9bea92018-07-10 12:42:023191 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573192 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023193 DiscardPendingEntry(false);
3194 return;
3195 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573196 same_document_loads.push_back(std::move(navigation_request));
3197
3198 // Sanity check that we never take this branch for any kinds of reloads,
3199 // as those should've queued a different-document load in the main frame.
3200 DCHECK(!is_forced_reload);
3201 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303202 }
3203
Nate Chapinbf682fa32022-09-26 22:41:203204 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163205 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203206 if (initiator_rfh && initiator_rfh->IsSandboxed(
3207 network::mojom::WebSandboxFlags::kTopNavigation)) {
3208 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3209 initiator_rfh, same_document_loads) &&
3210 DoesSandboxNavigationStayWithinSubtree(
3211 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503212 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163213 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203214 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3215 initiator_rfh,
3216 navigates_inside_tree
3217 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3218 : blink::mojom::WebFeature::
3219 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523220
3221 // If the navigation occurred outside the tree discard it because
3222 // the sandboxed frame didn't have permission to navigate outside
3223 // its tree. If it is possible that the navigation is both inside and
3224 // outside the frame tree and we discard it entirely because we don't
3225 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143226 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203227 // If a |navigation_api_key| was provided, this navigation originated from
3228 // the navigation API. Notify the renderer that the navigation was
3229 // cancelled so the navigation API can fire an error event and reject the
3230 // relevant promise.
3231 if (navigation_api_key) {
3232 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3233 *navigation_api_key,
3234 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3235 }
Dave Tapuska855c1e12019-08-23 20:45:523236 DiscardPendingEntry(false);
3237 return;
3238 }
Dave Tapuska8bfd84c2019-03-26 20:47:163239 }
3240
Carlos Caballero539a421c2020-07-06 10:25:573241 // BackForwardCache:
3242 // Navigate immediately if the document is in the BackForwardCache.
3243 if (back_forward_cache_.GetEntry(nav_entry_id)) {
3244 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3245 DCHECK_EQ(reload_type, ReloadType::NONE);
3246 auto navigation_request = CreateNavigationRequestFromEntry(
3247 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3248 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433249 false /* is_history_navigation_in_new_child */, is_browser_initiated);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053250 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573251
3252 return;
3253 }
3254
3255 // History navigation might try to reuse a specific BrowsingInstance, already
3256 // used by a page in the cache. To avoid having two different main frames that
3257 // live in the same BrowsingInstance, evict the all pages with this
3258 // BrowsingInstance from the cache.
3259 //
3260 // For example, take the following scenario:
3261 //
3262 // A1 = Some page on a.com
3263 // A2 = Some other page on a.com
3264 // B3 = An uncacheable page on b.com
3265 //
3266 // Then the following navigations occur:
3267 // A1->A2->B3->A1
3268 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3269 // take its place) and A1 will be created in the same BrowsingInstance (and
3270 // SiteInstance), as A2.
3271 //
3272 // If we didn't do anything, both A1 and A2 would remain alive in the same
3273 // BrowsingInstance/SiteInstance, which is unsupported by
3274 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3275 // A2 from the cache.
3276 if (pending_entry_->site_instance()) {
3277 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3278 pending_entry_->site_instance());
3279 }
3280
Rakina Zata Amnid605d462022-06-01 10:17:033281 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3282 pending_entry_ && pending_entry_->IsRestored());
3283 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3284 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3285 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3286 pending_entry_index_);
3287 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3288 last_committed_entry_index_);
3289 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3290 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3291 pending_entry_ && pending_entry_->IsInitialEntry());
3292 SCOPED_CRASH_KEY_BOOL(
3293 "nav_reentrancy", "pending_entry_initial2",
3294 pending_entry_ &&
3295 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3296 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3297 IsInitialNavigation());
3298 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3299 IsInitialBlankNavigation());
3300 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3301 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3302 (int)pending_reload_);
3303
clamy3cb9bea92018-07-10 12:42:023304 // This call does not support re-entrancy. See http://crbug.com/347742.
3305 CHECK(!in_navigate_to_pending_entry_);
3306 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303307
Rakina Zata Amnid605d462022-06-01 10:17:033308 // If the navigation-reentrancy is caused by calling
3309 // NavigateToExistingPendingEntry twice, this will note the previous call's
3310 // pending entry's ID.
3311 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3312 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3313
arthursonzogni66f711c2019-10-08 14:40:363314 // It is not possible to delete the pending NavigationEntry while navigating
3315 // to it. Grab a reference to delay potential deletion until the end of this
3316 // function.
3317 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3318
creis4e2ecb72015-06-20 00:46:303319 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023320 for (auto& item : same_document_loads) {
3321 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053322 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303323 }
clamy3cb9bea92018-07-10 12:42:023324 for (auto& item : different_document_loads) {
3325 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053326 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303327 }
clamy3cb9bea92018-07-10 12:42:023328
3329 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303330}
3331
Alex Moshchuk3a4e77a2020-05-29 21:32:573332NavigationControllerImpl::HistoryNavigationAction
3333NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303334 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573335 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423336 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583337 // Only active and prerendered documents are allowed to navigate in their
3338 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423339 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013340 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583341 // - If the document is in pending deletion, the browser already committed
3342 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3343 // - If the document is in back-forward cache, it's not allowed to navigate
3344 // as it should remain frozen. Ignore the request and evict the document
3345 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423346 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583347 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423348 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113349 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3350 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423351 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113352 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423353 }
arthursonzogni03f76152019-02-12 10:35:203354
Alex Moshchuk3a4e77a2020-05-29 21:32:573355 // If there's no last committed entry, there is no previous history entry to
3356 // compare against, so fall back to a different-document load. Note that we
3357 // should only reach this case for the root frame and not descend further
3358 // into subframes.
3359 if (!GetLastCommittedEntry()) {
3360 DCHECK(frame->IsMainFrame());
3361 return HistoryNavigationAction::kDifferentDocument;
3362 }
3363
3364 // Reloads should result in a different-document load. Note that reloads may
3365 // also happen via the |needs_reload_| mechanism where the reload_type is
3366 // NONE, so detect this by comparing whether we're going to the same
3367 // entry that we're currently on. Similarly to above, only main frames
3368 // should reach this. Note that subframes support reloads, but that's done
3369 // via a different path that doesn't involve FindFramesToNavigate (see
3370 // RenderFrameHost::Reload()).
3371 if (reload_type != ReloadType::NONE ||
3372 pending_entry_index_ == last_committed_entry_index_) {
3373 DCHECK(frame->IsMainFrame());
3374 return HistoryNavigationAction::kDifferentDocument;
3375 }
3376
Alex Moshchuk47d1a4bd2020-06-01 22:15:343377 // If there is no new FrameNavigationEntry for the frame, ignore the
3378 // load. For example, this may happen when going back to an entry before a
3379 // frame was created. Suppose we commit a same-document navigation that also
3380 // results in adding a new subframe somewhere in the tree. If we go back,
3381 // the new subframe will be missing a FrameNavigationEntry in the previous
3382 // NavigationEntry, but we shouldn't delete or change what's loaded in
3383 // it.
3384 //
Alex Moshchuke65c39272020-06-03 17:55:373385 // Note that in this case, there is no need to keep looking for navigations
3386 // in subframes, which would be missing FrameNavigationEntries as well.
3387 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343388 // It's important to check this before checking |old_item| below, since both
3389 // might be null, and in that case we still shouldn't change what's loaded in
3390 // this frame. Note that scheduling any loads assumes that |new_item| is
3391 // non-null. See https://crbug.com/1088354.
3392 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3393 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373394 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343395
Charlie Reisa474fb62022-03-17 02:31:363396 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3397 // which history item it is currently on, since this may be different than the
3398 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3399 // (e.g., if a history navigation is targeting multiple frames and only some
3400 // have committed so far).
creis4e2ecb72015-06-20 00:46:303401 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363402 frame->current_frame_host()->last_committed_frame_entry();
3403 if (!old_item) {
3404 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3405 // fall back to the last committed NavigationEntry's record for this frame.
3406 // This may happen in cases like the initial state of the RenderFrameHost.
3407 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3408 // accurate FrameNavigationEntry and eliminate this case.
3409 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3410 }
3411 // If neither approach finds a FrameNavigationEntry, schedule a
3412 // different-document load.
3413 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573414 if (!old_item)
3415 return HistoryNavigationAction::kDifferentDocument;
3416
Alex Moshchuk3a4e77a2020-05-29 21:32:573417 // If the new item is not in the same SiteInstance, schedule a
3418 // different-document load. Newly restored items may not have a SiteInstance
3419 // yet, in which case it will be assigned on first commit.
3420 if (new_item->site_instance() &&
3421 new_item->site_instance() != old_item->site_instance())
3422 return HistoryNavigationAction::kDifferentDocument;
3423
3424 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313425 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3426 // that we do this even if the history navigation would not be modifying this
3427 // frame were it live.
3428 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573429 return HistoryNavigationAction::kDifferentDocument;
3430
3431 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313432 // Starting a navigation after a crash early-promotes the speculative
3433 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3434 // committed yet, so we can not possibly perform a same-document history
3435 // navigation. The frame would need to be reloaded with a cross-document
3436 // navigation.
3437 if (!frame->current_frame_host()->has_committed_any_navigation())
3438 return HistoryNavigationAction::kDifferentDocument;
3439
creis54131692016-08-12 18:32:253440 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493441 // sequence number but different item sequence number.
3442 if (new_item->document_sequence_number() ==
3443 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573444 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493445 }
avib48cb312016-05-05 21:35:003446
Alex Moshchuk3a4e77a2020-05-29 21:32:573447 // Otherwise, if both item and document sequence numbers differ, this
3448 // should be a different document load.
3449 return HistoryNavigationAction::kDifferentDocument;
3450 }
3451
3452 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373453 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573454 DCHECK_EQ(new_item->document_sequence_number(),
3455 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373456 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573457}
3458
3459void NavigationControllerImpl::FindFramesToNavigate(
3460 FrameTreeNode* frame,
3461 ReloadType reload_type,
Nate Chapin45f620582021-09-30 17:45:433462 bool is_browser_initiated,
Alex Moshchuk3a4e77a2020-05-29 21:32:573463 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3464 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3465 DCHECK(pending_entry_);
3466 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3467
3468 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3469
3470 if (action == HistoryNavigationAction::kSameDocument) {
3471 std::unique_ptr<NavigationRequest> navigation_request =
3472 CreateNavigationRequestFromEntry(
3473 frame, pending_entry_, new_item, reload_type,
3474 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433475 false /* is_history_navigation_in_new_child */,
3476 is_browser_initiated);
Alex Moshchuk3a4e77a2020-05-29 21:32:573477 if (navigation_request) {
3478 // Only add the request if was properly created. It's possible for the
3479 // creation to fail in certain cases, e.g. when the URL is invalid.
3480 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303481 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573482 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473483 std::unique_ptr<NavigationRequest> navigation_request =
3484 CreateNavigationRequestFromEntry(
3485 frame, pending_entry_, new_item, reload_type,
3486 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433487 false /* is_history_navigation_in_new_child */,
3488 is_browser_initiated);
Lei Zhang96031532019-10-10 19:05:473489 if (navigation_request) {
3490 // Only add the request if was properly created. It's possible for the
3491 // creation to fail in certain cases, e.g. when the URL is invalid.
3492 different_document_loads->push_back(std::move(navigation_request));
3493 }
3494 // For a different document, the subframes will be destroyed, so there's
3495 // no need to consider them.
3496 return;
Alex Moshchuke65c39272020-06-03 17:55:373497 } else if (action == HistoryNavigationAction::kStopLooking) {
3498 return;
creis4e2ecb72015-06-20 00:46:303499 }
3500
3501 for (size_t i = 0; i < frame->child_count(); i++) {
Nate Chapin45f620582021-09-30 17:45:433502 FindFramesToNavigate(frame->child_at(i), reload_type, is_browser_initiated,
3503 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303504 }
3505}
3506
Harkiran Bolariaba823e42021-05-21 18:30:363507base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243508 const LoadURLParams& params) {
3509 // Find the appropriate FrameTreeNode.
3510 FrameTreeNode* node = nullptr;
3511 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3512 !params.frame_name.empty()) {
3513 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Carlos Caballero40b0efd2021-01-26 11:55:003514 ? frame_tree_.FindByID(params.frame_tree_node_id)
3515 : frame_tree_.FindByName(params.frame_name);
Hayato Ito7a80db42021-07-05 06:18:543516 DCHECK(!node || node->frame_tree() == &frame_tree_);
clamy21718cc22018-06-13 13:34:243517 }
3518
3519 // If no FrameTreeNode was specified, navigate the main frame.
3520 if (!node)
Carlos Caballero40b0efd2021-01-26 11:55:003521 node = frame_tree_.root();
clamy21718cc22018-06-13 13:34:243522
Camille Lamy5193caa2018-10-12 11:59:423523 // Compute overrides to the LoadURLParams for |override_user_agent|,
3524 // |should_replace_current_entry| and |has_user_gesture| that will be used
3525 // both in the creation of the NavigationEntry and the NavigationRequest.
3526 // Ideally, the LoadURLParams themselves would be updated, but since they are
3527 // passed as a const reference, this is not possible.
3528 // TODO(clamy): When we only create a NavigationRequest, move this to
3529 // CreateNavigationRequestFromLoadURLParams.
3530 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3531 GetLastCommittedEntry());
3532
3533 // Don't allow an entry replacement if there is no entry to replace.
3534 // http://crbug.com/457149
Hayato Ito7a80db42021-07-05 06:18:543535 //
3536 // If there is an entry, an entry replacement must happen if the current
3537 // browsing context should maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333538 bool should_replace_current_entry =
3539 (params.should_replace_current_entry ||
3540 ShouldMaintainTrivialSessionHistory(node)) &&
3541 entries_.size();
Camille Lamy5193caa2018-10-12 11:59:423542
clamy21718cc22018-06-13 13:34:243543 // Javascript URLs should not create NavigationEntries. All other navigations
3544 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243545 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373546 std::unique_ptr<NavigationEntryImpl> entry =
3547 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3548 should_replace_current_entry,
3549 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243550 DiscardPendingEntry(false);
3551 SetPendingEntry(std::move(entry));
3552 }
3553
3554 // Renderer-debug URLs are sent to the renderer process immediately for
3555 // processing and don't need to create a NavigationRequest.
3556 // Note: this includes navigations to JavaScript URLs, which are considered
3557 // renderer-debug URLs.
3558 // Note: we intentionally leave the pending entry in place for renderer debug
3559 // URLs, unlike the cases below where we clear it if the navigation doesn't
3560 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303561 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483562 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3563 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153564 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Oleg Davydov2cc0167b2019-02-05 14:32:483565 params.url, browser_context_)) {
3566 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363567 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483568 }
3569
clamy21718cc22018-06-13 13:34:243570 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363571 return nullptr;
clamy21718cc22018-06-13 13:34:243572 }
3573
Antonio Sartori78a749f2020-11-30 12:03:393574 DCHECK(pending_entry_);
3575
clamy21718cc22018-06-13 13:34:243576 // Convert navigations to the current URL to a reload.
3577 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3578 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3579 // DevTools sometimes issues navigations to main frames that they do not
3580 // expect to see treated as reload, and it only works because they pass a
3581 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3582 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543583 ReloadType reload_type = params.reload_type;
3584 if (reload_type == ReloadType::NONE &&
3585 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043586 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243587 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243588 params.load_type ==
3589 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543590 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243591 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473592 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393593
3594 // If this is a reload of an existing FrameNavigationEntry and we had a
3595 // policy container for it, then we should copy it into the pending entry,
3596 // so that it is copied to the navigation request in
3597 // CreateNavigationRequestFromLoadParams later.
3598 if (GetLastCommittedEntry()) {
3599 FrameNavigationEntry* previous_frame_entry =
3600 GetLastCommittedEntry()->GetFrameEntry(node);
Titouan Rigoudy6ec70402021-02-02 15:42:193601 if (previous_frame_entry &&
3602 previous_frame_entry->policy_container_policies()) {
3603 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Titouan Rigoudy72f892d2022-05-02 18:21:233604 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393605 }
3606 }
3607 }
3608
3609 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173610 // document, then we should copy the document polices from RenderFrameHost's
3611 // PolicyContainerHost. The NavigationRequest will create a new
3612 // PolicyContainerHost with the document policies from the |pending_entry_|,
3613 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3614 // the navigation. This way, we ensure that we keep enforcing the right
3615 // policies on the initial empty document after the reload.
Rakina Zata Amni2322f4f82022-01-24 13:24:243616 if ((!GetLastCommittedEntry() || GetLastCommittedEntry()->IsInitialEntry()) &&
3617 params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393618 if (node->current_frame_host() &&
3619 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193620 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163621 node->current_frame_host()
3622 ->policy_container_host()
3623 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233624 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393625 }
clamy21718cc22018-06-13 13:34:243626 }
3627
3628 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263629 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243630
Tsuyoshi Horo167ca6432022-03-09 05:16:393631 // This will be used to set the Navigation Timing API navigationStart
3632 // parameter for browser navigations in new tabs (intents, tabs opened through
3633 // "Open link in new tab"). If the navigation must wait on the current
3634 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3635 // will be updated when the BeforeUnload ack is received.
3636 const auto navigation_start_time = base::TimeTicks::Now();
3637
Camille Lamy5193caa2018-10-12 11:59:423638 std::unique_ptr<NavigationRequest> request =
3639 CreateNavigationRequestFromLoadParams(
3640 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143641 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393642 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3643 navigation_start_time);
clamy21718cc22018-06-13 13:34:243644
3645 // If the navigation couldn't start, return immediately and discard the
3646 // pending NavigationEntry.
3647 if (!request) {
3648 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363649 return nullptr;
clamy21718cc22018-06-13 13:34:243650 }
3651
Camille Lamy5193caa2018-10-12 11:59:423652#if DCHECK_IS_ON()
3653 // Safety check that NavigationRequest and NavigationEntry match.
3654 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3655#endif
3656
clamy21718cc22018-06-13 13:34:243657 // This call does not support re-entrancy. See http://crbug.com/347742.
3658 CHECK(!in_navigate_to_pending_entry_);
3659 in_navigate_to_pending_entry_ = true;
3660
arthursonzogni66f711c2019-10-08 14:40:363661 // It is not possible to delete the pending NavigationEntry while navigating
3662 // to it. Grab a reference to delay potential deletion until the end of this
3663 // function.
3664 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3665
Harkiran Bolariaba823e42021-05-21 18:30:363666 base::WeakPtr<NavigationHandle> created_navigation_handle(
3667 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053668 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243669
3670 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363671 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243672}
3673
clamyea99ea12018-05-28 13:54:233674void NavigationControllerImpl::HandleRendererDebugURL(
3675 FrameTreeNode* frame_tree_node,
3676 const GURL& url) {
3677 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243678 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3679 // the renderer process is not live, unless it is the initial navigation
3680 // of the tab.
clamyea99ea12018-05-28 13:54:233681 if (!IsInitialNavigation()) {
3682 DiscardNonCommittedEntries();
3683 return;
3684 }
Fergal Dalyecd3b0202020-06-25 01:57:373685 // The current frame is always a main frame. If IsInitialNavigation() is
3686 // true then there have been no navigations and any frames of this tab must
3687 // be in the same renderer process. If that has crashed then the only frame
3688 // that can be revived is the main frame.
3689 frame_tree_node->render_manager()
3690 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233691 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223692
3693 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3694 // notification, so set is loading to true here to properly surface it when
3695 // the renderer process is done handling the URL.
3696 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3697 if (!url.SchemeIs(url::kJavaScriptScheme)) {
3698 bool was_loading = frame_tree_node->frame_tree()
3699 ->LoadingTree()
3700 ->IsLoadingIncludingInnerFrameTrees();
3701 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
3702 frame_tree_node->DidStartLoading(true /* should_show_loading_ui */,
3703 was_loading);
3704 }
clamyea99ea12018-05-28 13:54:233705 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3706}
3707
clamy21718cc22018-06-13 13:34:243708std::unique_ptr<NavigationEntryImpl>
3709NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3710 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423711 const LoadURLParams& params,
3712 bool override_user_agent,
3713 bool should_replace_current_entry,
3714 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393715 // Browser initiated navigations might not have a blob_url_loader_factory set
3716 // in params even if the navigation is to a blob URL. If that happens, lookup
3717 // the correct url loader factory to use here.
3718 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483719 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473720 // Resolve the blob URL in the storage partition associated with the target
3721 // frame. This is the storage partition the URL will be loaded in, and only
3722 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393723 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473724 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393725 }
3726
clamy21718cc22018-06-13 13:34:243727 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443728 // extra_headers in params are \n separated; navigation entries want \r\n.
3729 std::string extra_headers_crlf;
3730 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243731
3732 // For subframes, create a pending entry with a corresponding frame entry.
3733 if (!node->IsMainFrame()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:243734 if (GetLastCommittedEntry()) {
3735 entry = GetLastCommittedEntry()->Clone();
3736 } else {
3737 // If there's no last committed entry, create an entry for about:blank
3738 // with a subframe entry for our destination.
3739 // TODO(creis): Ensure this case can't exist in https://crbug.com/524208.
3740 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
3741 GURL(url::kAboutBlankURL), params.referrer, params.initiator_origin,
3742 params.source_site_instance.get(), params.transition_type,
3743 params.is_renderer_initiated, extra_headers_crlf, browser_context_,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173744 blob_url_loader_factory, false /* rewrite_virtual_urls */));
Rakina Zata Amni2322f4f82022-01-24 13:24:243745 }
clamy21718cc22018-06-13 13:34:243746 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083747 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243748 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073749 params.url, absl::nullopt, params.referrer, params.initiator_origin,
Miyoung Shin5d77f72072020-10-09 15:14:203750 params.redirect_chain, blink::PageState(), "GET", -1,
Antonio Sartori78a749f2020-11-30 12:03:393751 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:483752 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori78a749f2020-11-30 12:03:393753 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163754 // a conversion of a new navigation into a reload, we will set the right
3755 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193756 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243757 } else {
3758 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173759 // If `node` is the outermost main frame, it rewrites a virtual url in order
3760 // to adjust the original input url if needed. For inner frames such as
3761 // fenced frames or subframes, they don't rewrite urls as the urls are not
3762 // input urls by users.
3763 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy21718cc22018-06-13 13:34:243764 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063765 params.url, params.referrer, params.initiator_origin,
Lukasz Anforowicz641234d52019-11-07 21:07:103766 params.source_site_instance.get(), params.transition_type,
3767 params.is_renderer_initiated, extra_headers_crlf, browser_context_,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173768 blob_url_loader_factory, rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243769 entry->set_source_site_instance(
3770 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3771 entry->SetRedirectChain(params.redirect_chain);
3772 }
3773
3774 // Set the FTN ID (only used in non-site-per-process, for tests).
3775 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243776 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423777 entry->SetIsOverridingUserAgent(override_user_agent);
3778 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543779 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243780
clamy21718cc22018-06-13 13:34:243781 switch (params.load_type) {
3782 case LOAD_TYPE_DEFAULT:
3783 break;
3784 case LOAD_TYPE_HTTP_POST:
3785 entry->SetHasPostData(true);
3786 entry->SetPostData(params.post_data);
3787 break;
3788 case LOAD_TYPE_DATA:
3789 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3790 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283791#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243792 entry->SetDataURLAsString(params.data_url_as_string);
3793#endif
3794 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3795 break;
clamy21718cc22018-06-13 13:34:243796 }
3797
3798 // TODO(clamy): NavigationEntry is meant for information that will be kept
3799 // after the navigation ended and therefore is not appropriate for
3800 // started_from_context_menu. Move started_from_context_menu to
3801 // NavigationUIData.
3802 entry->set_started_from_context_menu(params.started_from_context_menu);
3803
3804 return entry;
3805}
3806
clamyea99ea12018-05-28 13:54:233807std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423808NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3809 FrameTreeNode* node,
3810 const LoadURLParams& params,
3811 bool override_user_agent,
3812 bool should_replace_current_entry,
3813 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143814 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423815 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573816 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393817 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223818 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493819 bool is_embedder_initiated_fenced_frame_navigation,
3820 bool is_unfenced_top_navigation) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573821 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283822 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533823 // All renderer-initiated navigations must have an initiator_origin.
3824 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513825
Camille Lamy5193caa2018-10-12 11:59:423826 GURL url_to_load;
3827 GURL virtual_url;
Anton Bikineevf62d1bf2021-05-15 17:56:073828 absl::optional<url::Origin> origin_to_commit =
3829 frame_entry ? frame_entry->committed_origin() : absl::nullopt;
Nasko Oskov03912102019-01-11 00:21:323830
Camille Lamy2baa8022018-10-19 16:43:173831 // For main frames, rewrite the URL if necessary and compute the virtual URL
3832 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263833 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423834 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173835 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423836 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423837
Camille Lamy2baa8022018-10-19 16:43:173838 // For DATA loads, override the virtual URL.
3839 if (params.load_type == LOAD_TYPE_DATA)
3840 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423841
Camille Lamy2baa8022018-10-19 16:43:173842 if (virtual_url.is_empty())
3843 virtual_url = url_to_load;
3844
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573845 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283846
Aran Gilman249eb122019-12-02 23:32:463847 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3848 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3849 // return different results, leading to a different URL in the
3850 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3851 // pending NavigationEntry, as we'll only make one call to
3852 // RewriteUrlForNavigation.
3853 VLOG_IF(1, (url_to_load != frame_entry->url()))
3854 << "NavigationRequest and FrameEntry have different URLs: "
3855 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283856
Camille Lamy2baa8022018-10-19 16:43:173857 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423858 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173859 // NavigationRequest.
3860 } else {
3861 url_to_load = params.url;
3862 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243863 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173864 }
Camille Lamy5193caa2018-10-12 11:59:423865
Ehsan Karamad44fc72112019-02-26 18:15:473866 if (node->render_manager()->is_attaching_inner_delegate()) {
3867 // Avoid starting any new navigations since this node is now preparing for
3868 // attaching an inner delegate.
3869 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203870 }
Camille Lamy5193caa2018-10-12 11:59:423871
Ian Vollick1c6dd3e2022-04-13 02:06:263872 if (!IsValidURLForNavigation(node->IsOutermostMainFrame(), virtual_url,
3873 url_to_load))
Camille Lamy5193caa2018-10-12 11:59:423874 return nullptr;
3875
Kunihiko Sakamoto346a74e2021-03-10 08:57:483876 if (!DoesURLMatchOriginForNavigation(
3877 url_to_load, origin_to_commit,
Wang Hui14cac7a2022-01-28 06:07:473878 frame_entry->subresource_web_bundle_navigation_info(), entry,
Ian Vollick1c6dd3e2022-04-13 02:06:263879 node->IsOutermostMainFrame())) {
Nasko Oskov03912102019-01-11 00:21:323880 DCHECK(false) << " url:" << url_to_load
3881 << " origin:" << origin_to_commit.value();
3882 return nullptr;
3883 }
3884
danakjd83d706d2020-11-25 22:11:123885 // Look for a pending commit that is to another document in this
3886 // FrameTreeNode. If one exists, then the last committed URL will not be the
3887 // current URL by the time this navigation commits.
3888 bool has_pending_cross_document_commit =
3889 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213890 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123891
Minggang Wangb9f3fa92021-07-01 15:30:313892 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493893 /*old_url=*/node->current_url(),
3894 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3895 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133896 /*is_same_document_history_load=*/false,
3897 is_embedder_initiated_fenced_frame_navigation,
3898 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423899
3900 // Create the NavigationParams based on |params|.
3901
Hiroki Nakagawa4ed61282021-06-18 05:37:233902 bool is_view_source_mode = entry->IsViewSourceMode();
3903 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293904
Antonio Sartori6984c742021-08-26 08:03:413905 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Hiroki Nakagawa4ed61282021-06-18 05:37:233906 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293907 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253908 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293909
Minggang Wangb9f3fa92021-07-01 15:30:313910 blink::mojom::CommonNavigationParamsPtr common_params =
3911 blink::mojom::CommonNavigationParams::New(
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513912 url_to_load, params.initiator_origin,
3913 blink::mojom::Referrer::New(params.referrer.url,
3914 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213915 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513916 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393917 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513918 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143919 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413920 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273921 false /* has_text_fragment_token */,
3922 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3923 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513924 false /* is_history_navigation_in_new_child_frame */,
Nan Lind91c8152021-10-21 16:22:373925 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423926
Minggang Wangb9f3fa92021-07-01 15:30:313927 blink::mojom::CommitNavigationParamsPtr commit_params =
3928 blink::mojom::CommitNavigationParams::New(
Antonio Sartori3e8de6d2021-07-26 10:28:413929 frame_entry->committed_origin(),
3930 // The correct storage key will be computed before committing the
3931 // navigation.
Pâris Meuleman4d97a702022-07-05 10:42:003932 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323933 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503934 std::vector<net::RedirectInfo>(), params.post_content_type,
3935 common_params->url, common_params->method,
3936 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313937 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143938 entry->GetSubframeUniqueNames(node), true /* intended_as_new_entry */,
3939 -1 /* pending_history_list_offset */,
3940 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3941 params.should_clear_history_list ? 0 : GetEntryCount(),
3942 false /* was_discarded */, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313943 params.should_clear_history_list,
3944 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223945 blink::mojom::WasActivatedOption::kUnknown,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143946 base::UnguessableToken::Create() /* navigation_token */,
Minggang Wang7ee0c742021-06-16 16:16:513947 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283948#if BUILDFLAG(IS_ANDROID)
Lucas Furukawa Gadania9c45682019-07-31 22:05:143949 std::string(), /* data_url_as_string */
3950#endif
arthursonzogni14379782020-05-15 09:09:273951 !params.is_renderer_initiated, /* is_browser_initiated */
Tsuyoshi Horoe86d7702019-11-29 01:52:473952 GURL() /* web_bundle_physical_url */,
Charlie Hu5ffc0152019-12-06 15:59:533953 GURL() /* base_url_override_for_web_bundle */,
Yue Ru Sun128804932020-09-30 22:19:173954 ukm::kInvalidSourceId /* document_ukm_source_id */,
Jiewei Qian0406fc02020-03-09 06:02:073955 node->pending_frame_policy(),
Domenic Denicola4778c35392020-06-25 21:25:163956 std::vector<std::string>() /* force_enabled_origin_trials */,
Domenic Denicola55701ee2021-01-14 00:18:333957 false /* origin_agent_cluster */,
Daniel Vogelheim243df9f2022-02-22 10:32:033958 true /* origin_agent_cluster_left_as_default */,
Maks Orlovichc66745a2020-06-30 17:40:023959 std::vector<
Shuran Huanga055ce72020-07-23 14:13:213960 network::mojom::WebClientHintsType>() /* enabled_client_hints */,
Nate Chapind1fe3612021-04-16 20:45:573961 false /* is_cross_browsing_instance */, nullptr /* old_page_info */,
3962 -1 /* http_response_code */,
Domenic Denicolacd30f5f82022-03-16 21:48:013963 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Matt Menke4e209082021-11-09 04:59:313964 std::vector<GURL>() /* early_hints_preloaded_resources */,
Clark DuVall8ee487a22021-11-10 02:25:583965 absl::nullopt /* ad_auction_components */,
shivanigithubc7b97ca2022-04-05 19:41:403966 /*fenced_frame_reporting_metadata=*/nullptr,
Clark DuVall8ee487a22021-11-10 02:25:583967 // This timestamp will be populated when the commit IPC is sent.
Arthur Sonzognie41678a2022-06-16 15:51:193968 base::TimeTicks() /* commit_sent */, std::string() /* srcdoc_value */,
W. James MacLeanb7d6092682022-10-05 15:23:263969 GURL() /* fallback_srcdoc_baseurl_value */,
Liam Bradyd2a41e152022-07-19 13:58:483970 false /* should_load_data_url */,
Victor Tan10d93aca2022-08-12 16:46:283971 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
3972 std::string() /* reduced_accept_language */);
Xiaohan Wang7f8052e02022-01-14 18:44:283973#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423974 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143975 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423976 }
3977#endif
3978
Lucas Furukawa Gadania9c45682019-07-31 22:05:143979 commit_params->was_activated = params.was_activated;
Camille Lamy5193caa2018-10-12 11:59:423980
Camille Lamy5193caa2018-10-12 11:59:423981 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3982 std::string extra_headers_crlf;
3983 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:093984
3985 auto navigation_request = NavigationRequest::CreateBrowserInitiated(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143986 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:083987 !params.is_renderer_initiated, params.was_opener_suppressed,
Antonio Sartori9a82f6f32020-12-14 09:22:453988 params.initiator_frame_token.has_value()
3989 ? &(params.initiator_frame_token.value())
3990 : nullptr,
3991 params.initiator_process_id, extra_headers_crlf, frame_entry, entry,
jongdeok.kim5de823b32022-06-14 04:37:503992 params.is_form_submission,
John Delaney50425f82020-04-07 16:26:213993 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Garrett Tanzer47852462022-07-20 18:16:413994 params.impression, params.is_pdf,
3995 is_embedder_initiated_fenced_frame_navigation);
Yao Xiaodc5ed102019-06-04 19:19:093996 navigation_request->set_from_download_cross_origin_redirect(
3997 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:553998 navigation_request->set_force_new_browsing_instance(
3999 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:094000 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424001}
4002
4003std::unique_ptr<NavigationRequest>
4004NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234005 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574006 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234007 FrameNavigationEntry* frame_entry,
4008 ReloadType reload_type,
4009 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434010 bool is_history_navigation_in_new_child_frame,
4011 bool is_browser_initiated) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344012 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234013 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434014 // We should never navigate to an existing initial NavigationEntry that is the
4015 // initial NavigationEntry for the initial empty document that hasn't been
4016 // overridden by the synchronous about:blank commit, to preserve previous
4017 // behavior where trying to reload when the main frame is on the initial empty
4018 // document won't result in a navigation.
4019 // See also https://crbug.com/1277414.
4020 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Anton Bikineevf62d1bf2021-05-15 17:56:074021 absl::optional<url::Origin> origin_to_commit =
Nasko Oskov03912102019-01-11 00:21:324022 frame_entry->committed_origin();
4023
clamyea99ea12018-05-28 13:54:234024 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:014025 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574026 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:234027 // We may have been redirected when navigating to the current URL.
4028 // Use the URL the user originally intended to visit as signaled by the
4029 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:014030 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574031 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:234032 dest_referrer = Referrer();
Nasko Oskov03912102019-01-11 00:21:324033 origin_to_commit.reset();
clamyea99ea12018-05-28 13:54:234034 }
4035
Ehsan Karamad44fc72112019-02-26 18:15:474036 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4037 // Avoid starting any new navigations since this node is now preparing for
4038 // attaching an inner delegate.
4039 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204040 }
4041
Ian Vollick1c6dd3e2022-04-13 02:06:264042 if (!IsValidURLForNavigation(frame_tree_node->IsOutermostMainFrame(),
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574043 entry->GetVirtualURL(), dest_url)) {
clamyea99ea12018-05-28 13:54:234044 return nullptr;
4045 }
4046
Kunihiko Sakamoto346a74e2021-03-10 08:57:484047 if (!DoesURLMatchOriginForNavigation(
4048 dest_url, origin_to_commit,
Wang Hui14cac7a2022-01-28 06:07:474049 frame_entry->subresource_web_bundle_navigation_info(), entry,
Ian Vollick1c6dd3e2022-04-13 02:06:264050 frame_tree_node->IsOutermostMainFrame())) {
Kunihiko Sakamoto346a74e2021-03-10 08:57:484051 DCHECK(false) << " url:" << dest_url
Wang Hui14cac7a2022-01-28 06:07:474052 << " base_url_for_data_url: " << entry->GetBaseURLForDataURL()
Kunihiko Sakamoto346a74e2021-03-10 08:57:484053 << " origin:" << origin_to_commit.value();
Nasko Oskov03912102019-01-11 00:21:324054 return nullptr;
4055 }
4056
clamyea99ea12018-05-28 13:54:234057 // This will be used to set the Navigation Timing API navigationStart
4058 // parameter for browser navigations in new tabs (intents, tabs opened through
4059 // "Open link in new tab"). If the navigation must wait on the current
4060 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4061 // will be updated when the BeforeUnload ack is received.
4062 base::TimeTicks navigation_start = base::TimeTicks::Now();
clamyea99ea12018-05-28 13:54:234063
danakjd83d706d2020-11-25 22:11:124064 // Look for a pending commit that is to another document in this
4065 // FrameTreeNode. If one exists, then the last committed URL will not be the
4066 // current URL by the time this navigation commits.
4067 bool has_pending_cross_document_commit =
4068 frame_tree_node->render_manager()
4069 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494070 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214071 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124072
Minggang Wangb9f3fa92021-07-01 15:30:314073 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124074 /*old_url=*/frame_tree_node->current_url(),
4075 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:494076 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494077 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134078 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494079 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424080
4081 // A form submission may happen here if the navigation is a
4082 // back/forward/reload navigation that does a form resubmission.
4083 scoped_refptr<network::ResourceRequestBody> request_body;
4084 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:504085 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
4086 // entry. This way, it could be directly retrieved here. Right now, it is only
4087 // partially recovered when request.method == "POST" and request.body exists.
4088 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424089 if (frame_entry->method() == "POST") {
4090 request_body = frame_entry->GetPostData(&post_content_type);
4091 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304092 post_content_type = std::string(
4093 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504094 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424095 }
4096
4097 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314098 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514099 entry->ConstructCommonNavigationParams(
4100 *frame_entry, request_body, dest_url,
4101 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384102 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534103 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514104 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554105 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424106
4107 // TODO(clamy): |intended_as_new_entry| below should always be false once
4108 // Reload no longer leads to this being called for a pending NavigationEntry
4109 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314110 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144111 entry->ConstructCommitNavigationParams(
4112 *frame_entry, common_params->url, origin_to_commit,
4113 common_params->method, entry->GetSubframeUniqueNames(frame_tree_node),
4114 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534115 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484116 frame_tree_node->pending_frame_policy(),
4117 frame_tree_node->AncestorOrSelfHasCSPEE());
Lucas Furukawa Gadania9c45682019-07-31 22:05:144118 commit_params->post_content_type = post_content_type;
Camille Lamy5193caa2018-10-12 11:59:424119
W. James MacLeanb7d6092682022-10-05 15:23:264120 if (common_params->url.IsAboutSrcdoc()) {
4121 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4122 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594123 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264124 }
clamyea99ea12018-05-28 13:54:234125 return NavigationRequest::CreateBrowserInitiated(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144126 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434127 is_browser_initiated, false /* was_opener_suppressed */,
Takashi Toyoshimae87b7be2021-01-22 11:51:084128 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:454129 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
jongdeok.kim5de823b32022-06-14 04:37:504130 entry->extra_headers(), frame_entry, entry, is_form_submission,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474131 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
4132 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234133}
4134
[email protected]d202a7c2012-01-04 07:53:474135void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214136 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274137 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404138
Takashi Toyoshimaea534ef22021-07-21 03:27:594139 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404140 // location bar will have up-to-date information about the security style
4141 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134142 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404143
Rakina Zata Amnidaa84f62022-02-17 00:55:314144 bool should_fire_navigation_state_changed = true;
4145#if BUILDFLAG(IS_ANDROID)
4146 if (details && details->should_stay_as_initial_entry) {
4147 // For initial NavigationEntries, only fire NavigationStateChanged() if the
4148 // embedder wants to hear about it.
4149 should_fire_navigation_state_changed =
4150 !GetContentClient()
4151 ->browser()
4152 ->ShouldIgnoreInitialNavigationEntryNavigationStateChangedForLegacySupport();
4153 }
4154#endif
4155 if (should_fire_navigation_state_changed)
4156 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
4157
[email protected]ec6c05f2013-10-23 18:41:574158 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:464159
[email protected]b0f724c2013-09-05 04:21:134160 // TODO(avi): Remove. http://crbug.com/170921
4161 NotificationDetails notification_details =
4162 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154163 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4164 Source<NavigationController>(this),
4165 notification_details);
initial.commit09911bf2008-07-26 23:55:294166}
4167
initial.commit09911bf2008-07-26 23:55:294168// static
[email protected]d202a7c2012-01-04 07:53:474169size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234170 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154171 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214172 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234173}
4174
[email protected]d202a7c2012-01-04 07:53:474175void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224176 if (is_active && needs_reload_)
4177 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294178}
4179
[email protected]d202a7c2012-01-04 07:53:474180void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034181 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4182 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294183 if (!needs_reload_)
4184 return;
4185
Bo Liucdfa4b12018-11-06 00:21:444186 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4187 needs_reload_type_);
4188
initial.commit09911bf2008-07-26 23:55:294189 // Calling Reload() results in ignoring state, and not loading.
4190 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4191 // cached state.
avicc872d7242015-08-19 21:26:344192 if (pending_entry_) {
Dave Tapuska8bfd84c2019-03-26 20:47:164193 NavigateToExistingPendingEntry(ReloadType::NONE,
Nate Chapinbf682fa32022-09-26 22:41:204194 nullptr /* initiator_frame */,
4195 nullptr /* navigation_api_key */);
Rakina Zata Amni2322f4f82022-01-24 13:24:244196 } else if (last_committed_entry_index_ != -1 &&
4197 !GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434198 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274199 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344200 pending_entry_index_ = last_committed_entry_index_;
Dave Tapuska8bfd84c2019-03-26 20:47:164201 NavigateToExistingPendingEntry(ReloadType::NONE,
Nate Chapinbf682fa32022-09-26 22:41:204202 nullptr /* initiator_frame */,
4203 nullptr /* navigation_api_key */);
avicc872d7242015-08-19 21:26:344204 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434205 // We should never navigate to an existing initial NavigationEntry that is
4206 // the initial NavigationEntry for the initial empty document that hasn't
4207 // been overridden by the synchronous about:blank commit, to preserve
4208 // legacy behavior where trying to reload when the main frame is on the
4209 // initial empty document won't result in a navigation. See also
4210 // https://crbug.com/1277414. If there is something to reload, the
4211 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4212 // it here.
avicc872d7242015-08-19 21:26:344213 needs_reload_ = false;
4214 }
initial.commit09911bf2008-07-26 23:55:294215}
4216
Kevin McNeeccca6172021-10-19 17:11:144217base::WeakPtr<NavigationHandle>
4218NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364219 RenderFrameHost* render_frame_host,
4220 const GURL& url,
4221 const std::string& error_page_html,
4222 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134223 RenderFrameHostImpl* rfhi =
4224 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584225
4226 // Only active documents can load post-commit error pages:
4227 // - If the document is in pending deletion, the browser already committed to
4228 // destroying this RenderFrameHost so ignore loading the error page.
4229 // - If the document is in back-forward cache, it's not allowed to navigate as
4230 // it should remain frozen. Ignore the request and evict the document from
4231 // back-forward cache.
4232 // - If the document is prerendering, it can navigate but when loading error
4233 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114234 if (rfhi->IsInactiveAndDisallowActivation(
4235 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144236 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114237 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584238
Rakina Zata Amni919b7922020-12-11 09:03:134239 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414240
Minggang Wangb9f3fa92021-07-01 15:30:314241 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434242 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594243 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4244 // the frame actually committed (e.g. iframe with "src" set to a
4245 // slow-responding URL). We should rewrite the URL to about:blank in this
4246 // case, as the renderer will only think a page is an error page if it has a
4247 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134248 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314249 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434250 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334251 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414252
arthursonzogni70ac7302020-05-28 08:49:054253 // Error pages have a fully permissive FramePolicy.
4254 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4255 // error pages.
4256 commit_params->frame_policy = blink::FramePolicy();
4257
John Delaney131ad362019-08-08 21:57:414258 std::unique_ptr<NavigationRequest> navigation_request =
4259 NavigationRequest::CreateBrowserInitiated(
4260 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084261 true /* browser_initiated */, false /* was_opener_suppressed */,
Lingqi Chi82efa95e2020-12-29 05:31:194262 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:454263 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
John Delaneyf43556d2020-05-04 23:19:064264 "" /* extra_headers */, nullptr /* frame_entry */,
jongdeok.kim5de823b32022-06-14 04:37:504265 nullptr /* entry */, false /* is_form_submission */,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474266 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
4267 false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364268 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414269 navigation_request->set_net_error(error);
4270 node->CreatedNavigationRequest(std::move(navigation_request));
4271 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144272
4273 // Calling BeginNavigation may destroy the NavigationRequest.
4274 base::WeakPtr<NavigationRequest> created_navigation_request(
4275 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414276 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144277 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414278}
4279
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574280void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214281 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094282 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154283 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144284 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294285}
4286
[email protected]d202a7c2012-01-04 07:53:474287void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364288 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474289 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4290 // represent a no-committed-entry state.
4291 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364292 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474293 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4294 // if `entries_` contains pre-existing entries from the NavigationController
4295 // before restore, which would not be removed and will be at the front of the
4296 // entries list, causing the index to be off by the amount of pre-existing
4297 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294298 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294299}
[email protected]765b35502008-08-21 00:51:204300
arthursonzogni69a6a1b2019-09-17 09:23:004301void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004302 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4303}
4304
4305void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4306 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474307 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104308 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4309 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294310 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474311 return;
Michael Thiessenc5676d22019-09-25 22:32:104312 }
avi45a72532015-04-07 21:01:454313 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314314
4315 if (!delegate_)
4316 return;
4317
4318 bool should_fire_navigation_state_changed = true;
4319#if BUILDFLAG(IS_ANDROID)
4320 if (commit_details && commit_details->should_stay_as_initial_entry) {
4321 // For initial NavigationEntries, only fire NavigationStateChanged() if the
4322 // embedder wants to hear about it.
4323 should_fire_navigation_state_changed =
4324 !GetContentClient()
4325 ->browser()
4326 ->ShouldIgnoreInitialNavigationEntryNavigationStateChangedForLegacySupport();
Rakina Zata Amniddf10502022-01-15 02:56:554327 }
Rakina Zata Amnidaa84f62022-02-17 00:55:314328#endif
4329 if (should_fire_navigation_state_changed)
4330 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484331}
4332
avi7c6f35e2015-05-08 17:52:384333int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4334 int nav_entry_id) const {
4335 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4336 if (entries_[i]->GetUniqueID() == nav_entry_id)
4337 return i;
4338 }
4339 return -1;
4340}
4341
[email protected]d202a7c2012-01-04 07:53:474342void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574343 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254344 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574345 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574346 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4347 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254348 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374349 // Normally, cloning a NavigationEntryImpl results in sharing
4350 // FrameNavigationEntries between the original and the clone. However, when
4351 // cloning from a different NavigationControllerImpl, we want to fork the
4352 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374353 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574354 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254355 }
arthursonzogni5c4c202d2017-04-25 23:41:274356 DCHECK(pending_entry_index_ == -1 ||
4357 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254358}
[email protected]c5b88d82012-10-06 17:03:334359
4360void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184361 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334362 get_timestamp_callback_ = get_timestamp_callback;
4363}
[email protected]8ff00d72012-10-23 19:12:214364
Shivani Sharmaffb32b82019-04-09 16:58:474365// History manipulation intervention:
4366void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474367 bool replace_entry,
4368 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404369 bool is_renderer_initiated,
4370 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454371 // Note that for a subframe, previous_document_was_activated is true if the
4372 // gesture happened in any subframe (propagated to main frame) or in the main
4373 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474374 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274375 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474376 return;
4377 }
4378 if (last_committed_entry_index_ == -1)
4379 return;
4380
Shivani Sharmac4cc8922019-04-18 03:11:174381 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474382
Alexander Timine3ec4192020-04-20 16:39:404383 // Log UKM with the URL we are navigating away from.
4384 ukm::builders::HistoryManipulationIntervention(
4385 previous_page_load_ukm_source_id)
4386 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474387}
4388
Shivani Sharmac4cc8922019-04-18 03:11:174389void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4390 int reference_index,
4391 bool skippable) {
4392 auto* reference_entry = GetEntryAtIndex(reference_index);
4393 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4394
4395 int64_t document_sequence_number =
4396 reference_entry->root_node()->frame_entry->document_sequence_number();
4397 for (int index = 0; index < GetEntryCount(); index++) {
4398 auto* entry = GetEntryAtIndex(index);
4399 if (entry->root_node()->frame_entry->document_sequence_number() ==
4400 document_sequence_number) {
4401 entry->set_should_skip_on_back_forward_ui(skippable);
4402 }
4403 }
4404}
4405
arthursonzogni66f711c2019-10-08 14:40:364406std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4407NavigationControllerImpl::ReferencePendingEntry() {
4408 DCHECK(pending_entry_);
4409 auto pending_entry_ref =
4410 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4411 pending_entry_refs_.insert(pending_entry_ref.get());
4412 return pending_entry_ref;
4413}
4414
4415void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4416 // Ignore refs that don't correspond to the current pending entry.
4417 auto it = pending_entry_refs_.find(ref);
4418 if (it == pending_entry_refs_.end())
4419 return;
4420 pending_entry_refs_.erase(it);
4421
4422 if (!pending_entry_refs_.empty())
4423 return;
4424
4425 // The pending entry may be deleted before the last PendingEntryRef.
4426 if (!pending_entry_)
4427 return;
4428
4429 // We usually clear the pending entry when the matching NavigationRequest
4430 // fails, so that an arbitrary URL isn't left visible above a committed page.
4431 //
4432 // However, we do preserve the pending entry in some cases, such as on the
4433 // initial navigation of an unmodified blank tab. We also allow the delegate
4434 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4435 // user edit the URL and try again. This may be useful in cases that the
4436 // committed page cannot be attacker-controlled. In these cases, we still
4437 // allow the view to clear the pending entry and typed URL if the user
4438 // requests (e.g., hitting Escape with focus in the address bar).
4439 //
4440 // Do not leave the pending entry visible if it has an invalid URL, since this
4441 // might be formatted in an unexpected or unsafe way.
4442 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364443 bool should_preserve_entry =
4444 (pending_entry_ == GetVisibleEntry()) &&
4445 pending_entry_->GetURL().is_valid() &&
4446 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4447 if (should_preserve_entry)
4448 return;
4449
4450 DiscardPendingEntry(true);
4451 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
4452}
4453
Titouan Rigoudy6ec70402021-02-02 15:42:194454std::unique_ptr<PolicyContainerPolicies>
4455NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394456 RenderFrameHostImpl* rfh,
4457 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174458 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394459 if (is_same_document) {
Rakina Zata Amni2322f4f82022-01-24 13:24:244460 // TODO(https://crbug.com/524208): Remove this nullptr check when we can
4461 // ensure we always have a FrameNavigationEntry here.
4462 if (!GetLastCommittedEntry())
4463 return nullptr;
Charlie Reis73e356242021-04-02 17:10:314464
Antonio Sartori78a749f2020-11-30 12:03:394465 FrameNavigationEntry* previous_frame_entry =
4466 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4467
4468 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4469 // ensure we always have a FrameNavigationEntry here.
4470 if (!previous_frame_entry)
4471 return nullptr;
4472
Titouan Rigoudy6ec70402021-02-02 15:42:194473 const PolicyContainerPolicies* previous_policies =
4474 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394475
Titouan Rigoudy6ec70402021-02-02 15:42:194476 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394477 return nullptr;
4478
4479 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234480 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394481 }
4482
Titouan Rigoudy72f892d2022-05-02 18:21:234483 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394484}
4485
Hayato Ito2c8c08d02021-06-23 03:38:434486void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504487 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434488 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4489 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4490 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504491
4492 auto callback = base::BindRepeating(
4493 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4494 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4495 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4496 }
4497 },
Hayato Ito2c8c08d02021-06-23 03:38:434498 GetLastCommittedEntryIndex(), GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504499 frame_tree_.root()->render_manager()->ExecutePageBroadcastMethod(callback);
4500}
4501
4502void NavigationControllerImpl::DidAccessInitialMainDocument() {
4503 // We may have left a failed browser-initiated navigation in the address bar
4504 // to let the user edit it and try again. Clear it now that content might
4505 // show up underneath it.
Yu Gaoc8c18552022-06-22 14:38:454506 if (!frame_tree_.IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504507 DiscardPendingEntry(false);
4508
4509 // Update the URL display.
4510 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
4511}
4512
4513void NavigationControllerImpl::UpdateStateForFrame(
4514 RenderFrameHostImpl* rfhi,
4515 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564516 OPTIONAL_TRACE_EVENT1("content",
4517 "NavigationControllerImpl::UpdateStateForFrame",
4518 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504519 // The state update affects the last NavigationEntry associated with the given
4520 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4521 // in the case of an UpdateState from a frame being swapped out). We track
4522 // which entry this is in the RenderFrameHost's nav_entry_id.
4523 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4524 if (!entry)
4525 return;
4526
4527 FrameNavigationEntry* frame_entry =
4528 entry->GetFrameEntry(rfhi->frame_tree_node());
4529 if (!frame_entry)
4530 return;
4531
4532 // The SiteInstance might not match if we do a cross-process navigation with
4533 // replacement (e.g., auto-subframe), in which case the swap out of the old
4534 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4535 // has already been replaced and destroyed.
4536 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4537 return;
4538
4539 if (page_state == frame_entry->page_state())
4540 return; // Nothing to update.
4541
4542 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4543
4544 // The document_sequence_number and item_sequence_number recorded in the
4545 // FrameNavigationEntry should not differ from the one coming with the update,
4546 // since it must come from the same document. Do not update it if a difference
4547 // is detected, as this indicates that |frame_entry| is not the correct one.
4548 blink::ExplodedPageState exploded_state;
4549 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4550 return;
4551
4552 if (exploded_state.top.document_sequence_number !=
4553 frame_entry->document_sequence_number() ||
4554 exploded_state.top.item_sequence_number !=
4555 frame_entry->item_sequence_number()) {
4556 return;
4557 }
4558
4559 frame_entry->SetPageState(page_state);
4560 NotifyEntryChanged(entry);
4561}
4562
Domenic Denicolacd30f5f82022-03-16 21:48:014563std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4564NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574565 Direction direction,
4566 int entry_index,
4567 const url::Origin& pending_origin,
4568 FrameTreeNode* node,
4569 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304570 int64_t pending_item_sequence_number,
4571 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014572 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amni2322f4f82022-01-24 13:24:244573 if (GetLastCommittedEntry() && GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174574 // Don't process the initial entry.
4575 DCHECK_EQ(GetEntryCount(), 1);
4576 return entries;
4577 }
Nate Chapind1fe3612021-04-16 20:45:574578 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304579 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574580 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4581 i += offset) {
4582 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414583 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574584 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014585 // An entry should only appear in the navigation API entries if it is for
4586 // the same origin as the document being committed. Check the committed
4587 // origin, or if that is not available (during restore), check against the
4588 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414589 url::Origin frame_entry_origin =
4590 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4591 frame_entry->url(),
4592 frame_entry->initiator_origin().value_or(url::Origin())));
4593 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574594 break;
4595 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4596 continue;
4597 blink::ExplodedPageState exploded_page_state;
4598 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4599 &exploded_page_state)) {
4600 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304601
4602 // If the document represented by this FNE hid its full url from appearing
4603 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014604 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304605 // document).
4606 std::u16string url;
4607 if (pending_document_sequence_number ==
4608 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574609 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304610 url = frame_state.url_string.value_or(std::u16string());
4611 }
4612
Domenic Denicolacd30f5f82022-03-16 21:48:014613 blink::mojom::NavigationApiHistoryEntryPtr entry =
4614 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574615 frame_state.navigation_api_key.value_or(std::u16string()),
4616 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094617 frame_state.item_sequence_number,
4618 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304619 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174620
Nate Chapin63db0d12022-01-20 22:03:304621 DCHECK(entry->url.empty() ||
4622 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574623 entries.push_back(std::move(entry));
4624 previous_item_sequence_number = frame_entry->item_sequence_number();
4625 }
4626 }
4627 // If |entries| was constructed by iterating backwards from
4628 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4629 // earliest-at-the-front. Reverse it.
4630 if (direction == Direction::kBack)
4631 std::reverse(entries.begin(), entries.end());
4632 return entries;
4633}
4634
Domenic Denicolacd30f5f82022-03-16 21:48:014635blink::mojom::NavigationApiHistoryEntryArraysPtr
4636NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554637 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574638 NavigationRequest* request) {
4639 url::Origin pending_origin =
Nate Chapin97d2f542022-02-18 01:34:554640 request ? request->commit_params().origin_to_commit
4641 ? *request->commit_params().origin_to_commit
4642 : url::Origin::Create(request->common_params().url)
4643 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574644
Nate Chapind1fe3612021-04-16 20:45:574645 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554646 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574647
Nate Chapine82339d02022-05-03 23:48:254648 // NOTE: |entry_index| is the index where this entry will commit if no
4649 // modifications are made between now and DidCommitNavigation. This is used to
4650 // walk |entries_| and determine which entries should be exposed by the
4651 // navigation API. It is important to calculate this correctly, because blink
4652 // will cancel a same-document history commit if it's not present in the
4653 // entries blink knows about.
4654 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574655 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304656 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254657 bool will_create_new_entry = false;
4658 if (GetPendingEntryIndex() != -1) {
4659 entry_index = GetPendingEntryIndex();
4660 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4661 pending_item_sequence_number = frame_entry->item_sequence_number();
4662 pending_document_sequence_number =
4663 frame_entry->document_sequence_number();
4664 }
4665 } else if (request &&
4666 !NavigationTypeUtils::IsReload(
4667 request->common_params().navigation_type) &&
4668 !NavigationTypeUtils::IsHistory(
4669 request->common_params().navigation_type) &&
4670 !request->common_params().should_replace_current_entry &&
4671 !request->common_params()
4672 .is_history_navigation_in_new_child_frame) {
4673 will_create_new_entry = true;
4674 entry_index = GetLastCommittedEntryIndex() + 1;
4675 // Don't set pending_item_sequence_number or
4676 // pending_document_sequence_number in this case - a new unique isn/dsn will
4677 // be calculated in the renderer later.
4678 } else if (GetLastCommittedEntryIndex() != -1) {
4679 entry_index = GetLastCommittedEntryIndex();
4680 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574681 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304682 pending_document_sequence_number =
4683 frame_entry->document_sequence_number();
4684 }
Nate Chapind1fe3612021-04-16 20:45:574685 }
4686
Domenic Denicolacd30f5f82022-03-16 21:48:014687 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254688 if (entry_index == -1) {
4689 // TODO(rakina): Exit early when there is no last committed entry.
4690 // Remove when InitialNavigationEntry ships.
4691 return entry_arrays;
4692 }
4693
Domenic Denicolacd30f5f82022-03-16 21:48:014694 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574695 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374696 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574697
4698 // Don't populate forward entries if they will be truncated by a new entry.
4699 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014700 entry_arrays->forward_entries =
4701 PopulateSingleNavigationApiHistoryEntryVector(
4702 Direction::kForward, entry_index, pending_origin, node,
4703 site_instance.get(), pending_item_sequence_number,
4704 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574705 }
Nate Chapin4e657a472022-02-06 03:38:374706 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574707}
4708
Nate Chapinfbfe5af2021-06-10 17:22:084709NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574710NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084711 FrameNavigationEntry* current_entry,
4712 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574713 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084714 if (!target_entry || !target_entry->committed_origin())
4715 return HistoryNavigationAction::kStopLooking;
4716 if (current_entry->site_instance() != target_entry->site_instance())
4717 return HistoryNavigationAction::kStopLooking;
4718 if (!current_entry->committed_origin()->IsSameOriginWith(
4719 *target_entry->committed_origin())) {
4720 return HistoryNavigationAction::kStopLooking;
4721 }
4722
4723 // NOTE: We don't actually care between kSameDocument and
4724 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574725 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084726 return HistoryNavigationAction::kDifferentDocument;
4727 return HistoryNavigationAction::kKeepLooking;
4728}
4729
Domenic Denicolacc094fb2022-03-16 23:40:574730void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204731 RenderFrameHostImpl* initiator_rfh,
Domenic Denicolacc094fb2022-03-16 23:40:574732 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204733 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084734 FrameNavigationEntry* current_entry =
4735 GetLastCommittedEntry()->GetFrameEntry(node);
4736 if (!current_entry)
4737 return;
4738
4739 // We want to find the nearest matching entry that is contiguously
4740 // same-instance and same-origin. Check back first, then forward.
4741 // TODO(japhet): Link spec here once it exists.
4742 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574743 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084744 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4745 if (result == HistoryNavigationAction::kStopLooking)
4746 break;
4747 if (result != HistoryNavigationAction::kKeepLooking) {
Nate Chapinbf682fa32022-09-26 22:41:204748 GoToIndex(i, initiator_rfh, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084749 return;
4750 }
4751 }
4752 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574753 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084754 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4755 if (result == HistoryNavigationAction::kStopLooking)
4756 break;
4757 if (result != HistoryNavigationAction::kKeepLooking) {
Nate Chapinbf682fa32022-09-26 22:41:204758 GoToIndex(i, initiator_rfh, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084759 return;
4760 }
4761 }
Nate Chapinbf682fa32022-09-26 22:41:204762
4763 // If we fall through to here, a matching NavigationEntry couldn't be found.
4764 // Notify the renderer that the navigation was cancelled.
4765 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4766 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084767}
4768
Domenic Denicolacc094fb2022-03-16 23:40:574769bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304770 network::mojom::ReferrerPolicy referrer_policy) {
4771 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4772 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4773}
4774
shivanigithubf405bf0d2021-11-05 17:58:334775bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4776 const FrameTreeNode* frame_tree_node) const {
4777 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4778 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544779 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
shivanigithubf405bf0d2021-11-05 17:58:334780 return frame_tree_.is_prerendering() ||
4781 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544782}
4783
[email protected]8ff00d72012-10-23 19:12:214784} // namespace content