blob: 6cad17946d240bff75bec30aeaf2e8385ebeabe7 [file] [log] [blame]
[email protected]d4a8ca482013-10-30 21:06:401// Copyright 2013 The Chromium Authors. All rights reserved.
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"
Chris Hamilton83272dc2021-02-23 00:24:0248#include "base/stl_util.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"
servolkf3955532015-05-16 00:01:5956#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2857#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1858#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3959#include "content/browser/blob_storage/chrome_blob_storage_context.h"
[email protected]825b1662012-03-12 19:07:3160#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4161#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0462#include "content/browser/dom_storage/session_storage_namespace_impl.h"
danakjc492bf82020-09-09 20:02:4463#include "content/browser/renderer_host/debug_urls.h"
64#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0065#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3366#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4467#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5768#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4469#include "content/browser/renderer_host/navigation_request.h"
70#include "content/browser/renderer_host/navigator.h"
71#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0072#include "content/browser/renderer_host/render_view_host_impl.h"
Sharon Yangd70a5392021-10-26 23:06:3273#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3374#include "content/browser/site_instance_impl.h"
Kunihiko Sakamoto346a74e2021-03-10 08:57:4875#include "content/browser/web_package/subresource_web_bundle_navigation_info.h"
Tsuyoshi Horo37493af2019-11-21 23:43:1476#include "content/browser/web_package/web_bundle_navigation_info.h"
Camille Lamy5193caa2018-10-12 11:59:4277#include "content/common/content_constants_internal.h"
Nate Chapind1fe3612021-04-16 20:45:5778#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5179#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1180#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1981#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1182#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4683#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0084#include "content/public/browser/navigation_details.h"
[email protected]7f6f44c2011-12-14 13:23:3885#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1686#include "content/public/browser/notification_types.h"
Lei Zhang96031532019-10-10 19:05:4787#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5888#include "content/public/browser/render_widget_host.h"
89#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1090#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3491#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1992#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3893#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1094#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:4795#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:4396#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:5997#include "media/base/mime_util.h"
[email protected]a23de8572009-06-03 02:16:3298#include "net/base/escape.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 Sakamoto260ee0a2021-10-15 01:44:08266 // Urn: and uuid-in-package: subframe from WebBundle has an opaque origin
267 // derived from the Bundle's origin.
268 // TODO(https://crbug.com/1257045): Remove urn: scheme support.
Wang Hui14cac7a2022-01-28 06:07:47269 if ((url_for_origin.SchemeIs(url::kUrnScheme) ||
270 url_for_origin.SchemeIs(url::kUuidInPackageScheme)) &&
Kunihiko Sakamoto260ee0a2021-10-15 01:44:08271 subresource_web_bundle_navigation_info) {
Kunihiko Sakamoto346a74e2021-03-10 08:57:48272 return origin->CanBeDerivedFrom(
273 subresource_web_bundle_navigation_info->bundle_url());
274 }
275
Wang Hui14cac7a2022-01-28 06:07:47276 return origin->CanBeDerivedFrom(url_for_origin);
Nasko Oskov03912102019-01-11 00:21:32277}
278
Anton Bikineevf62d1bf2021-05-15 17:56:07279absl::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12280 const mojom::DidCommitProvisionalLoadParams& params,
281 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32282 // Error pages commit in an opaque origin, yet have the real URL that resulted
283 // in an error as the |params.url|. Since successful reload of an error page
284 // should commit in the correct origin, setting the opaque origin on the
285 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17286 if (request && request->DidEncounterError())
Anton Bikineevf62d1bf2021-05-15 17:56:07287 return absl::nullopt;
Nasko Oskov03912102019-01-11 00:21:32288
Anton Bikineevf62d1bf2021-05-15 17:56:07289 return absl::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32290}
291
Camille Lamy5193caa2018-10-12 11:59:42292bool IsValidURLForNavigation(bool is_main_frame,
293 const GURL& virtual_url,
294 const GURL& dest_url) {
295 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
296 if (is_main_frame && !virtual_url.is_valid() && !virtual_url.is_empty()) {
297 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
298 << virtual_url.possibly_invalid_spec();
299 return false;
300 }
301
302 // Don't attempt to navigate to non-empty invalid URLs.
303 if (!dest_url.is_valid() && !dest_url.is_empty()) {
304 LOG(WARNING) << "Refusing to load invalid URL: "
305 << dest_url.possibly_invalid_spec();
306 return false;
307 }
308
309 // The renderer will reject IPC messages with URLs longer than
310 // this limit, so don't attempt to navigate with a longer URL.
311 if (dest_url.spec().size() > url::kMaxURLChars) {
312 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
313 << " characters.";
314 return false;
315 }
316
Aaron Colwell33109c592020-04-21 21:31:19317 // Reject renderer debug URLs because they should have been handled before
318 // we get to this point. This check handles renderer debug URLs
319 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
320 // provides defense-in-depth if a renderer debug URL manages to get here via
321 // some other path. We want to reject the navigation here so it doesn't
322 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30323 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19324 LOG(WARNING) << "Refusing to load renderer debug URL: "
325 << dest_url.possibly_invalid_spec();
326 return false;
327 }
328
Camille Lamy5193caa2018-10-12 11:59:42329 return true;
330}
331
Mikel Astizba9cf2fd2017-12-17 10:38:10332// See replaced_navigation_entry_data.h for details: this information is meant
333// to ensure |*output_entry| keeps track of its original URL (landing page in
334// case of server redirects) as it gets replaced (e.g. history.replaceState()),
335// without overwriting it later, for main frames.
336void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57337 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10338 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17339 if (output_entry->GetReplacedEntryData().has_value() ||
340 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10341 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17342 }
Mikel Astizba9cf2fd2017-12-17 10:38:10343
344 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57345 data.first_committed_url = replaced_entry->GetURL();
346 data.first_timestamp = replaced_entry->GetTimestamp();
347 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29348 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10349}
350
Minggang Wangb9f3fa92021-07-01 15:30:31351blink::mojom::NavigationType GetNavigationType(
352 const GURL& old_url,
353 const GURL& new_url,
354 ReloadType reload_type,
355 NavigationEntryImpl* entry,
356 const FrameNavigationEntry& frame_entry,
357 bool has_pending_cross_document_commit,
358 bool is_currently_error_page,
359 bool is_same_document_history_load) {
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).
386 !is_currently_error_page;
danakjd83d706d2020-11-25 22:11:12387
clamyea99ea12018-05-28 13:54:23388 // History navigations.
389 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12390 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31391 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
392 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23393 }
394 DCHECK(!is_same_document_history_load);
395
396 // A same-document fragment-navigation happens when the only part of the url
397 // that is modified is after the '#' character.
398 //
399 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12400 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23401 //
402 // Note: this check is only valid for navigations that are not history
403 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
404 // history navigation from 'A#foo' to 'A#bar' is not a same-document
405 // navigation, but a different-document one. This is why history navigation
406 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47407 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
408 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12409
410 // The one case where we do the wrong thing here and incorrectly choose
411 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
412 // the renderer is a frameset. All frameset navigations should be
413 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
414 // navigation would do the right thing, as it would send it to the browser and
415 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
416 // into this method). But since we can't tell that case here for browser-
417 // initiated navigations, we have to get the renderer involved. In that case
418 // the navigation would be restarted due to the renderer spending a reply of
419 // mojom::CommitResult::RestartCrossDocument.
420
421 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31422 ? blink::mojom::NavigationType::SAME_DOCUMENT
423 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23424}
425
Camille Lamy5193caa2018-10-12 11:59:42426// Adjusts the original input URL if needed, to get the URL to actually load and
427// the virtual URL, which may differ.
428void RewriteUrlForNavigation(const GURL& original_url,
429 BrowserContext* browser_context,
430 GURL* url_to_load,
431 GURL* virtual_url,
432 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42433 // Allow the browser URL handler to rewrite the URL. This will, for example,
434 // remove "view-source:" from the beginning of the URL to get the URL that
435 // will actually be loaded. This real URL won't be shown to the user, just
436 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31437 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42438 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
439 url_to_load, browser_context, reverse_on_redirect);
440}
441
442#if DCHECK_IS_ON()
443// Helper sanity check function used in debug mode.
444void ValidateRequestMatchesEntry(NavigationRequest* request,
445 NavigationEntryImpl* entry) {
446 if (request->frame_tree_node()->IsMainFrame()) {
447 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
448 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31449 ui::PageTransitionFromInt(request->common_params().transition),
450 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42451 }
Nasko Oskovc36327d2019-01-03 23:23:04452 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42453 entry->should_clear_history_list());
454 DCHECK_EQ(request->common_params().has_user_gesture,
455 entry->has_user_gesture());
456 DCHECK_EQ(request->common_params().base_url_for_data_url,
457 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04458 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42459 entry->GetCanLoadLocalResources());
460 DCHECK_EQ(request->common_params().started_from_context_menu,
461 entry->has_started_from_context_menu());
462
463 FrameNavigationEntry* frame_entry =
464 entry->GetFrameEntry(request->frame_tree_node());
465 if (!frame_entry) {
466 NOTREACHED();
467 return;
468 }
469
Camille Lamy5193caa2018-10-12 11:59:42470 DCHECK_EQ(request->common_params().method, frame_entry->method());
471
Nasko Oskovc36327d2019-01-03 23:23:04472 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42473 if (redirect_size == frame_entry->redirect_chain().size()) {
474 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04475 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42476 frame_entry->redirect_chain()[i]);
477 }
478 } else {
479 NOTREACHED();
480 }
481}
482#endif // DCHECK_IS_ON()
483
Dave Tapuska8bfd84c2019-03-26 20:47:16484// Returns whether the session history NavigationRequests in |navigations|
485// would stay within the subtree of the sandboxed iframe in
486// |sandbox_frame_tree_node_id|.
487bool DoesSandboxNavigationStayWithinSubtree(
488 int sandbox_frame_tree_node_id,
489 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
490 for (auto& item : navigations) {
491 bool within_subtree = false;
492 // Check whether this NavigationRequest affects a frame within the
493 // sandboxed frame's subtree by walking up the tree looking for the
494 // sandboxed frame.
495 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03496 frame = FrameTreeNode::From(frame->parent())) {
Dave Tapuska8bfd84c2019-03-26 20:47:16497 if (frame->frame_tree_node_id() == sandbox_frame_tree_node_id) {
498 within_subtree = true;
499 break;
500 }
501 }
502 if (!within_subtree)
503 return false;
504 }
505 return true;
506}
507
[email protected]e9ba4472008-09-14 15:42:43508} // namespace
509
arthursonzogni66f711c2019-10-08 14:40:36510// NavigationControllerImpl::PendingEntryRef------------------------------------
511
512NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
513 base::WeakPtr<NavigationControllerImpl> controller)
514 : controller_(controller) {}
515
516NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
517 if (!controller_) // Can be null with interstitials.
518 return;
519
520 controller_->PendingEntryRefDeleted(this);
521}
522
[email protected]d202a7c2012-01-04 07:53:47523// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29524
[email protected]23a918b2014-07-15 09:51:36525const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23526
[email protected]765b35502008-08-21 00:51:20527// static
[email protected]d202a7c2012-01-04 07:53:47528size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23529 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20530
[email protected]e6fec472013-05-14 05:29:02531// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20532// when testing.
533static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29534
[email protected]71fde352011-12-29 03:29:56535// static
dcheng9bfa5162016-04-09 01:00:57536std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
537 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10538 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07539 absl::optional<url::Origin> initiator_origin,
Lukasz Anforowicz641234d52019-11-07 21:07:10540 ui::PageTransition transition,
541 bool is_renderer_initiated,
542 const std::string& extra_headers,
543 BrowserContext* browser_context,
544 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
545 return NavigationControllerImpl::CreateNavigationEntry(
546 url, referrer, std::move(initiator_origin),
547 nullptr /* source_site_instance */, transition, is_renderer_initiated,
Hayato Ito303654c2021-06-30 09:07:54548 extra_headers, browser_context, std::move(blob_url_loader_factory));
Lukasz Anforowicz641234d52019-11-07 21:07:10549}
550
551// static
552std::unique_ptr<NavigationEntryImpl>
553NavigationControllerImpl::CreateNavigationEntry(
554 const GURL& url,
555 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07556 absl::optional<url::Origin> initiator_origin,
Lukasz Anforowicz641234d52019-11-07 21:07:10557 SiteInstance* source_site_instance,
dcheng9bfa5162016-04-09 01:00:57558 ui::PageTransition transition,
559 bool is_renderer_initiated,
560 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09561 BrowserContext* browser_context,
Hayato Ito303654c2021-06-30 09:07:54562 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
Camille Lamy5193caa2018-10-12 11:59:42563 GURL url_to_load;
564 GURL virtual_url;
[email protected]71fde352011-12-29 03:29:56565 bool reverse_on_redirect = false;
Camille Lamy5193caa2018-10-12 11:59:42566 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
567 &reverse_on_redirect);
[email protected]71fde352011-12-29 03:29:56568
Lukasz Anforowicz641234d52019-11-07 21:07:10569 // Let the NTP override the navigation params and pretend that this is a
570 // browser-initiated, bookmark-like navigation.
571 GetContentClient()->browser()->OverrideNavigationParams(
Scott Violetcf6ea7e2021-06-09 21:09:21572 source_site_instance, &transition, &is_renderer_initiated, &referrer,
573 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10574
Patrick Monettef507e982019-06-19 20:18:06575 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28576 nullptr, // The site instance for tabs is sent on navigation
577 // (WebContents::GetSiteInstance).
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:58578 url_to_load, referrer, initiator_origin, std::u16string(), transition,
Rakina Zata Amniafd3c6582021-11-30 06:19:17579 is_renderer_initiated, blob_url_loader_factory,
580 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42581 entry->SetVirtualURL(virtual_url);
582 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56583 entry->set_update_virtual_url_with_url(reverse_on_redirect);
584 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06585 return entry;
[email protected]71fde352011-12-29 03:29:56586}
587
[email protected]cdcb1dee2012-01-04 00:46:20588// static
589void NavigationController::DisablePromptOnRepost() {
590 g_check_for_repost = false;
591}
592
[email protected]c5b88d82012-10-06 17:03:33593base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
594 base::Time t) {
595 // If |t| is between the water marks, we're in a run of duplicates
596 // or just getting out of it, so increase the high-water mark to get
597 // a time that probably hasn't been used before and return it.
598 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35599 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33600 return high_water_mark_;
601 }
602
603 // Otherwise, we're clear of the last duplicate run, so reset the
604 // water marks.
605 low_water_mark_ = high_water_mark_ = t;
606 return t;
607}
608
ckitagawa0faa5e42020-06-17 17:30:54609NavigationControllerImpl::ScopedShowRepostDialogForTesting::
610 ScopedShowRepostDialogForTesting()
611 : was_disallowed_(g_check_for_repost) {
612 g_check_for_repost = true;
613}
614
615NavigationControllerImpl::ScopedShowRepostDialogForTesting::
616 ~ScopedShowRepostDialogForTesting() {
617 g_check_for_repost = was_disallowed_;
618}
619
[email protected]d202a7c2012-01-04 07:53:47620NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00621 BrowserContext* browser_context,
622 FrameTree& frame_tree,
623 NavigationControllerDelegate* delegate)
624 : frame_tree_(frame_tree),
625 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57626 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22627 ssl_manager_(this),
Lei Zhang96031532019-10-10 19:05:47628 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)) {
[email protected]3d7474ff2011-07-27 17:47:37629 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29630}
631
[email protected]d202a7c2012-01-04 07:53:47632NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00633 // The NavigationControllerImpl might be called inside its delegate
634 // destructor. Calling it is not valid anymore.
635 delegate_ = nullptr;
636 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29637}
638
Matt Falkenhagen548ed1562021-07-06 01:38:26639WebContents* NavigationControllerImpl::DeprecatedGetWebContents() {
640 return delegate_->DeprecatedGetWebContents();
[email protected]fbc5e5f92012-01-02 06:08:32641}
642
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57643BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55644 return browser_context_;
645}
646
[email protected]d202a7c2012-01-04 07:53:47647void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30648 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36649 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57650 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47651 // Note that it's possible for `entries_` to contain multiple entries at this
652 // point, as Restore() might be called on a NavigationController that is
653 // already used (e.g. due to WebView's restoreState() API), not only for fresh
654 // NavigationControllers. These entries are not cleared to preserve legacy
655 // behavior and also because `pending_entry_` might point to one of the
656 // pre-existing entries. An exception for this is when `entries_` contains
657 // only the initial NavigationEntry, which must be removed.
658
659 // Do not proceed if selected_navigation will be out of bounds for the updated
660 // entries_ list, since it will be assigned to last_committed_entry_index_ and
661 // used to index entries_.
662 // TODO(https://crbug.com/1287624): Consider also returning early if entries
663 // is empty, since there should be no work to do (rather than marking the
664 // existing entries as needing reload). Also consider returning early if the
665 // selected index is -1, which represents a no-committed-entry state.
666 if (selected_navigation < -1 ||
667 selected_navigation >=
668 base::checked_cast<int>(entries->size() + entries_.size())) {
669 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24670 }
Charlie Reis23c26da2022-01-29 00:57:47671
672 if (blink::features::IsInitialNavigationEntryEnabled()) {
673 // In InitialNavigationEntry mode, there will always be at least one entry.
674 if (selected_navigation == -1)
675 selected_navigation = 0;
676
677 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
678 // If we are on the initial NavigationEntry, it must be the only entry in
679 // the list. Since it's impossible to do a history navigation to the
680 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
681 // `pending_entry` might be set for a new non-history navigation).
682 // Note that we should not clear `entries_` if `entries` is empty (when
683 // InitialNavigationEntry mode is enabled), since that would leave us
684 // without any NavigationEntry.
685 CHECK_EQ(1, GetEntryCount());
686 CHECK_EQ(-1, pending_entry_index_);
687 entries_.clear();
688 }
689 }
[email protected]ce3fa3c2009-04-20 19:55:57690
[email protected]ce3fa3c2009-04-20 19:55:57691 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44692 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03693 entries_.reserve(entries->size());
Rakina Zata Amni627360d2022-02-24 00:53:40694 int index = 0;
Charlie Reis23c26da2022-01-29 00:57:47695 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43696 if (entry->GetURL().is_empty()) {
697 // We're trying to restore an entry with an empty URL (e.g. from
698 // persisting the initial NavigationEntry, which is no longer possible but
699 // some old persisted sessions might still contain it). Trying to restore
700 // and navigate to an entry with an empty URL will result in crashes, so
701 // change the URL to about:blank. See also https://crbug.com/1240138.
Rakina Zata Amni627360d2022-02-24 00:53:40702 if (entries->size() != 1) {
703 SCOPED_CRASH_KEY_NUMBER("EmptyURLRestore", "restored_entries_size",
704 entries->size());
705 SCOPED_CRASH_KEY_NUMBER("EmptyURLRestore", "current_entries_size",
706 entries_.size());
707 SCOPED_CRASH_KEY_NUMBER("EmptyURLRestore", "empty_url_entry_index",
708 index);
709 NavigationEntryImpl::TreeNode* root_node =
710 static_cast<NavigationEntryImpl*>(entry.get())->root_node();
711 SCOPED_CRASH_KEY_NUMBER("EmptyURLRestore", "root_children",
712 root_node->children.size());
713 SCOPED_CRASH_KEY_STRING256("EmptyURLRestore", "root_origin",
714 root_node->frame_entry->committed_origin()
715 .value()
716 .GetDebugString());
717 base::debug::DumpWithoutCrashing();
718 }
Rakina Zata Amni996ee412022-02-17 04:51:43719 entry->SetURL(GURL(url::kAboutBlankURL));
720 }
dcheng36b6aec92015-12-26 06:16:36721 entries_.push_back(
722 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Rakina Zata Amni627360d2022-02-24 00:53:40723 index++;
Charlie Reis23c26da2022-01-29 00:57:47724 }
avif16f85a72015-11-13 18:25:03725
726 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
727 // cleared out safely.
728 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57729
730 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36731 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57732}
733
toyoshim6142d96f2016-12-19 09:07:25734void NavigationControllerImpl::Reload(ReloadType reload_type,
735 bool check_for_repost) {
liaoyuke9168fba2017-03-10 19:20:28736 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28737 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32738 int current_index = -1;
739
Carlos IL42b416592019-10-07 23:10:36740 if (entry_replaced_by_post_commit_error_) {
741 // If there is an entry that was replaced by a currently active post-commit
742 // error navigation, this can't be the initial navigation.
743 DCHECK(!IsInitialNavigation());
744 // If the current entry is a post commit error, we reload the entry it
745 // replaced instead. We leave the error entry in place until a commit
746 // replaces it, but the pending entry points to the original entry in the
747 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
748 // case that pending_entry_ != entries_[pending_entry_index_].
749 entry = entry_replaced_by_post_commit_error_.get();
750 current_index = GetCurrentEntryIndex();
751 } else if (IsInitialNavigation() && pending_entry_) {
752 // If we are reloading the initial navigation, just use the current
753 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32754 entry = pending_entry_;
755 // The pending entry might be in entries_ (e.g., after a Clone), so we
756 // should also update the current_index.
757 current_index = pending_entry_index_;
758 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00759 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32760 current_index = GetCurrentEntryIndex();
761 if (current_index != -1) {
creis3da03872015-02-20 21:12:32762 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32763 }
[email protected]979a4bc2013-04-24 01:27:15764 }
[email protected]241db352013-04-22 18:04:05765
[email protected]59167c22013-06-03 18:07:32766 // If we are no where, then we can't reload. TODO(darin): We should add a
767 // CanReload method.
768 if (!entry)
769 return;
770
Rakina Zata Amnif297a802022-01-18 03:53:43771 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
772 // We should never navigate to an existing initial NavigationEntry that is
773 // the initial NavigationEntry for the initial empty document that hasn't
774 // been overridden by the synchronous about:blank commit, to preserve
775 // legacy behavior where trying to reload when the main frame is on the
776 // initial empty document won't result in a navigation. See also
777 // https://crbug.com/1277414.
778 return;
779 }
780
Takashi Toyoshimac7df3c22019-06-25 14:18:47781 // Set ReloadType for |entry|.
toyoshima63c2a62016-09-29 09:03:26782 entry->set_reload_type(reload_type);
783
Aran Gilman37d11632019-10-08 23:07:15784 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30785 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07786 // they really want to do this. If they do, the dialog will call us back
787 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57788 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02789
[email protected]106a0812010-03-18 00:15:12790 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57791 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47792 return;
initial.commit09911bf2008-07-26 23:55:29793 }
Lei Zhang96031532019-10-10 19:05:47794
795 if (!IsInitialNavigation())
796 DiscardNonCommittedEntries();
797
798 pending_entry_ = entry;
799 pending_entry_index_ = current_index;
800 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
801
Nate Chapin45f620582021-09-30 17:45:43802 // location.reload() goes through BeginNavigation, so all reloads triggered
803 // via this codepath are browser initiated.
Lei Zhang96031532019-10-10 19:05:47804 NavigateToExistingPendingEntry(reload_type,
Nate Chapin45f620582021-09-30 17:45:43805 FrameTreeNode::kFrameTreeNodeInvalidId,
806 true /* is_browser_initiated */);
initial.commit09911bf2008-07-26 23:55:29807}
808
[email protected]d202a7c2012-01-04 07:53:47809void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48810 DCHECK(pending_reload_ != ReloadType::NONE);
811 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12812}
813
[email protected]d202a7c2012-01-04 07:53:47814void NavigationControllerImpl::ContinuePendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48815 if (pending_reload_ == ReloadType::NONE) {
[email protected]106a0812010-03-18 00:15:12816 NOTREACHED();
817 } else {
toyoshim6142d96f2016-12-19 09:07:25818 Reload(pending_reload_, false);
toyoshim0df1d3a2016-09-09 09:52:48819 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12820 }
821}
822
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57823bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09824 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11825}
826
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57827bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni2322f4f82022-01-24 13:24:24828 if (blink::features::IsInitialNavigationEntryEnabled()) {
829 // Check that we're on the initial NavigationEntry and that this is not a
830 // cloned tab.
831 return IsInitialNavigation() && GetEntryCount() == 1 &&
832 GetLastCommittedEntry()->IsInitialEntry() &&
833 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
834 } else {
835 return IsInitialNavigation() && GetEntryCount() == 0;
836 }
creis10a4ab72015-10-13 17:22:40837}
838
Aran Gilman37d11632019-10-08 23:07:15839NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
840 int nav_entry_id) const {
avi254eff02015-07-01 08:27:58841 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:03842 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:58843}
844
Adithya Srinivasan9b0c99c2021-08-10 15:19:45845NavigationEntryImpl*
846NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
847 int nav_entry_id) const {
848 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
849 if (entry)
850 return entry;
851 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:52852 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:45853 : nullptr;
854}
855
W. James MacLean1c40862c2020-04-27 21:05:57856void NavigationControllerImpl::RegisterExistingOriginToPreventOptInIsolation(
857 const url::Origin& origin) {
858 for (int i = 0; i < GetEntryCount(); i++) {
859 auto* entry = GetEntryAtIndex(i);
860 entry->RegisterExistingOriginToPreventOptInIsolation(origin);
861 }
862 if (entry_replaced_by_post_commit_error_) {
863 // It's possible we could come back to this entry if the error
864 // page/interstitial goes away.
865 entry_replaced_by_post_commit_error_
866 ->RegisterExistingOriginToPreventOptInIsolation(origin);
867 }
868 // TODO(wjmaclean): Register pending commit NavigationRequests rather than
869 // visiting pending_entry_, which lacks a committed origin. This will be done
870 // in https://chromium-review.googlesource.com/c/chromium/src/+/2136703.
871}
872
avi25764702015-06-23 15:43:37873void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:57874 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:00875 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:37876 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:27877 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:20878}
879
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57880NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:47881 if (pending_entry_)
882 return pending_entry_;
883 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:20884}
885
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57886NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:32887 // The pending entry is safe to return for new (non-history), browser-
888 // initiated navigations. Most renderer-initiated navigations should not
889 // show the pending entry, to prevent URL spoof attacks.
890 //
891 // We make an exception for renderer-initiated navigations in new tabs, as
892 // long as no other page has tried to access the initial empty document in
893 // the new tab. If another page modifies this blank page, a URL spoof is
894 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:32895 bool safe_to_show_pending =
896 pending_entry_ &&
897 // Require a new navigation.
avi0dca04d2015-01-26 20:21:09898 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:32899 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:46900 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:32901
902 // Also allow showing the pending entry for history navigations in a new tab,
903 // such as Ctrl+Back. In this case, no existing page is visible and no one
904 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:15905 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
906 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:32907 safe_to_show_pending = true;
908
909 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:19910 return pending_entry_;
911 return GetLastCommittedEntry();
912}
913
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57914int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:20915 if (pending_entry_index_ != -1)
916 return pending_entry_index_;
917 return last_committed_entry_index_;
918}
919
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57920NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni2322f4f82022-01-24 13:24:24921 if (last_committed_entry_index_ == -1) {
922 // The last committed entry must always exist when InitialNavigationEntry
923 // is enabled. TODO(https://crbug.com/524208): Remove this case and all
924 // related nullchecks entirely.
925 DCHECK(!blink::features::IsInitialNavigationEntryEnabled());
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28926 return nullptr;
Rakina Zata Amni2322f4f82022-01-24 13:24:24927 }
avif16f85a72015-11-13 18:25:03928 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:20929}
930
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57931bool NavigationControllerImpl::CanViewSource() {
Jeremy Roman2d8dfe132021-07-06 20:51:26932 const std::string& mime_type =
933 frame_tree_.root()->current_frame_host()->GetPage().contents_mime_type();
Kinuko Yasuda74702f92017-07-31 03:27:53934 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
935 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:27936 NavigationEntry* visible_entry = GetVisibleEntry();
937 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:39938 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:16939}
940
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57941int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:27942 // The last committed entry index must always be less than the number of
Rakina Zata Amni2322f4f82022-01-24 13:24:24943 // entries. If there are no entries, it must be -1.
arthursonzogni5c4c202d2017-04-25 23:41:27944 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
Rakina Zata Amni2322f4f82022-01-24 13:24:24945 DCHECK(GetEntryCount() || last_committed_entry_index_ == -1);
[email protected]a26023822011-12-29 00:23:55946 return last_committed_entry_index_;
947}
948
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57949int NavigationControllerImpl::GetEntryCount() {
Carlos IL4dea8902020-05-26 15:14:29950 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:55951 return static_cast<int>(entries_.size());
952}
953
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57954NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:37955 if (index < 0 || index >= GetEntryCount())
956 return nullptr;
957
avif16f85a72015-11-13 18:25:03958 return entries_[index].get();
[email protected]022af742011-12-28 18:37:25959}
960
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57961NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:47962 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:20963}
964
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57965int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:46966 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:03967}
968
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57969bool NavigationControllerImpl::CanGoBack() {
Shivani Sharma298d12852019-01-22 20:04:03970 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
971 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
972 return true;
973 }
974 return false;
[email protected]765b35502008-08-21 00:51:20975}
976
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57977bool NavigationControllerImpl::CanGoForward() {
WangHui74286d52021-03-31 16:17:15978 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
979 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
980 return true;
981 }
982 return false;
[email protected]765b35502008-08-21 00:51:20983}
984
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57985bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:03986 int index = GetIndexForOffset(offset);
987 return index >= 0 && index < GetEntryCount();
988}
989
Xiaohan Wang7f8052e02022-01-14 18:44:28990#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:15991bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:15992 if (offset == 0)
993 return true;
994 int increment = offset > 0 ? 1 : -1;
995 int non_skippable_entries = 0;
996 for (int index = GetIndexForOffset(increment);
997 index >= 0 && index < GetEntryCount(); index += increment) {
998 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
999 non_skippable_entries++;
1000
1001 if (non_skippable_entries == std::abs(offset))
1002 return true;
1003 }
1004 return false;
1005}
1006#endif
1007
[email protected]d202a7c2012-01-04 07:53:471008void NavigationControllerImpl::GoBack() {
shivanisha55201872018-12-13 04:29:061009 int target_index = GetIndexForOffset(-1);
1010
Elly Fong-Jones40ee8112021-06-23 19:10:521011 // Move the target index past the skippable entries.
Shivani Sharma298d12852019-01-22 20:04:031012 bool all_skippable_entries = true;
Elly Fong-Jones40ee8112021-06-23 19:10:521013 while (target_index >= 0) {
1014 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui()) {
Shivani Sharma298d12852019-01-22 20:04:031015 all_skippable_entries = false;
shivanisha55201872018-12-13 04:29:061016 break;
Shivani Sharma2d5b4b6b2019-01-08 16:07:161017 }
Elly Fong-Jones40ee8112021-06-23 19:10:521018 target_index--;
shivanisha55201872018-12-13 04:29:061019 }
Miyoung Shin1c565c912021-03-17 12:11:211020
Shivani Sharma298d12852019-01-22 20:04:031021 // Do nothing if all entries are skippable. Normally this path would not
1022 // happen as consumers would have already checked it in CanGoBack but a lot of
1023 // tests do not do that.
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421024 if (all_skippable_entries)
Shivani Sharma298d12852019-01-22 20:04:031025 return;
shivanisha55201872018-12-13 04:29:061026
shivanisha55201872018-12-13 04:29:061027 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201028}
1029
[email protected]d202a7c2012-01-04 07:53:471030void NavigationControllerImpl::GoForward() {
shivanisha55201872018-12-13 04:29:061031 int target_index = GetIndexForOffset(1);
1032
Shivani Sharma2d5b4b6b2019-01-08 16:07:161033 // Note that at least one entry (the last one) will be non-skippable since
1034 // entries are marked skippable only when they add another entry because of
1035 // redirect or pushState.
Elly Fong-Jones40ee8112021-06-23 19:10:521036 while (target_index < static_cast<int>(entries_.size())) {
1037 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui())
shivanisha55201872018-12-13 04:29:061038 break;
Elly Fong-Jones40ee8112021-06-23 19:10:521039 target_index++;
shivanisha55201872018-12-13 04:29:061040 }
shivanisha55201872018-12-13 04:29:061041 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201042}
1043
[email protected]d202a7c2012-01-04 07:53:471044void NavigationControllerImpl::GoToIndex(int index) {
Nate Chapin45f620582021-09-30 17:45:431045 GoToIndex(index, FrameTreeNode::kFrameTreeNodeInvalidId,
1046 true /* is_browser_initiated */);
Dave Tapuska8bfd84c2019-03-26 20:47:161047}
1048
1049void NavigationControllerImpl::GoToIndex(int index,
Nate Chapin45f620582021-09-30 17:45:431050 int sandbox_frame_tree_node_id,
1051 bool is_browser_initiated) {
1052 DCHECK(sandbox_frame_tree_node_id == FrameTreeNode::kFrameTreeNodeInvalidId ||
1053 !is_browser_initiated);
sunjian30574a62017-03-21 21:39:441054 TRACE_EVENT0("browser,navigation,benchmark",
1055 "NavigationControllerImpl::GoToIndex");
[email protected]765b35502008-08-21 00:51:201056 if (index < 0 || index >= static_cast<int>(entries_.size())) {
1057 NOTREACHED();
1058 return;
1059 }
1060
Rakina Zata Amnif297a802022-01-18 03:53:431061 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1062 // We should never navigate to an existing initial NavigationEntry that is
1063 // the initial NavigationEntry for the initial empty document that hasn't
1064 // been overridden by the synchronous about:blank commit, to preserve
1065 // legacy behavior where trying to reload when the main frame is on the
1066 // initial empty document won't result in a navigation. See also
1067 // https://crbug.com/1277414.
1068 return;
1069 }
1070
[email protected]cbab76d2008-10-13 22:42:471071 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201072
arthursonzogni5c4c202d2017-04-25 23:41:271073 DCHECK_EQ(nullptr, pending_entry_);
1074 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431075
arthursonzogni5c4c202d2017-04-25 23:41:271076 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201077 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271078 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1079 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapin45f620582021-09-30 17:45:431080 NavigateToExistingPendingEntry(ReloadType::NONE, sandbox_frame_tree_node_id,
1081 is_browser_initiated);
[email protected]765b35502008-08-21 00:51:201082}
1083
[email protected]d202a7c2012-01-04 07:53:471084void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121085 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031086 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201087 return;
1088
[email protected]9ba14052012-06-22 23:50:031089 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201090}
1091
Nate Chapin45f620582021-09-30 17:45:431092void NavigationControllerImpl::GoToOffsetFromRenderer(int offset) {
1093 // Note: This is actually reached in unit tests.
1094 if (!CanGoToOffset(offset))
1095 return;
1096
1097 GoToIndex(GetIndexForOffset(offset), FrameTreeNode::kFrameTreeNodeInvalidId,
1098 false /* is_browser_initiated */);
1099}
1100
Xiaohan Wang7f8052e02022-01-14 18:44:281101#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151102void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1103 // Note: This is actually reached in unit tests.
1104 if (!CanGoToOffsetWithSkipping(offset))
1105 return;
1106
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421107 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151108 GoToIndex(GetIndexForOffset(offset));
1109 return;
1110 }
1111 int increment = offset > 0 ? 1 : -1;
1112 // Find the offset without counting skippable entries.
1113 int target_index = GetIndexForOffset(increment);
1114 int non_skippable_entries = 0;
1115 for (int index = target_index; index >= 0 && index < GetEntryCount();
1116 index += increment) {
1117 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1118 non_skippable_entries++;
1119
1120 if (non_skippable_entries == std::abs(offset)) {
1121 target_index = index;
1122 break;
1123 }
1124 }
1125
1126 GoToIndex(target_index);
1127}
1128#endif
1129
[email protected]41374f12013-07-24 02:49:281130bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151131 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281132 return false;
[email protected]6a13a6c2011-12-20 21:47:121133
[email protected]43032342011-03-21 14:10:311134 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281135 return true;
[email protected]cbab76d2008-10-13 22:42:471136}
1137
Michael Thiessen9b14d512019-09-23 21:19:471138void NavigationControllerImpl::PruneForwardEntries() {
1139 DiscardNonCommittedEntries();
1140 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471141 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471142 if (num_removed <= 0)
1143 return;
1144 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1145 NotifyPrunedEntries(this, remove_start_index /* start index */,
1146 num_removed /* count */);
1147}
1148
Aran Gilman37d11632019-10-08 23:07:151149void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1150 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321151 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311152 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511153 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1154 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321155 }
1156}
1157
Harkiran Bolariaba823e42021-05-21 18:30:361158base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1159 const GURL& url,
1160 const Referrer& referrer,
1161 ui::PageTransition transition,
1162 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471163 LoadURLParams params(url);
1164 params.referrer = referrer;
1165 params.transition_type = transition;
1166 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361167 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471168}
1169
Harkiran Bolariaba823e42021-05-21 18:30:361170base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1171 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061172 if (params.is_renderer_initiated)
1173 DCHECK(params.initiator_origin.has_value());
1174
naskob8744d22014-08-28 17:07:431175 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151176 "NavigationControllerImpl::LoadURLWithParams", "url",
1177 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291178 bool is_explicit_navigation =
1179 GetContentClient()->browser()->IsExplicitNavigation(
1180 params.transition_type);
1181 if (HandleDebugURL(params.url, params.transition_type,
1182 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431183 // If Telemetry is running, allow the URL load to proceed as if it's
1184 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491185 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431186 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361187 return nullptr;
[email protected]47752982014-07-29 08:01:431188 }
[email protected]8bf1048012012-02-08 01:22:181189
[email protected]cf002332012-08-14 19:17:471190 // Checks based on params.load_type.
1191 switch (params.load_type) {
1192 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431193 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471194 break;
1195 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261196 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471197 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361198 return nullptr;
[email protected]cf002332012-08-14 19:17:471199 }
1200 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461201 }
[email protected]e47ae9472011-10-13 19:48:341202
[email protected]e47ae9472011-10-13 19:48:341203 // The user initiated a load, we don't need to reload anymore.
1204 needs_reload_ = false;
1205
Harkiran Bolariaba823e42021-05-21 18:30:361206 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441207}
1208
Mohamed Abdelhalim833de902019-09-16 17:41:451209bool NavigationControllerImpl::PendingEntryMatchesRequest(
1210 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191211 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451212 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191213}
1214
[email protected]d202a7c2012-01-04 07:53:471215bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321216 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071217 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331218 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441219 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251220 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471221 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131222 NavigationRequest* navigation_request) {
1223 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331224
1225 // Note: validation checks and renderer kills due to invalid commit messages
1226 // must happen before getting here, in
1227 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1228 // effects of the navigation have already occurred.
1229
shivanigithubf405bf0d2021-11-05 17:58:331230 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node()) &&
1231 GetLastCommittedEntry()) {
Takashi Toyoshimaa9f66802021-08-18 02:40:171232 // Ensure that this navigation does not add a navigation entry, since
1233 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1234 // beyond the last committed one. Therefore, `should_replace_current_entry`
1235 // should be set, which replaces the current entry, or this should be a
1236 // reload, which does not create a new entry.
1237 DCHECK(params.should_replace_current_entry ||
1238 navigation_request->GetReloadType() != ReloadType::NONE);
1239 }
[email protected]cd2e15742013-03-08 04:08:311240 is_initial_navigation_ = false;
1241
[email protected]0e8db942008-09-24 21:21:481242 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431243 bool overriding_user_agent_changed = false;
[email protected]0e8db942008-09-24 21:21:481244 if (GetLastCommittedEntry()) {
Carlos IL42b416592019-10-07 23:10:361245 if (entry_replaced_by_post_commit_error_) {
Chris Bookholt27faf8d2022-01-20 01:03:331246 // Same document navigation events with a post-commit error should already
1247 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1248 // reaching here.
1249 CHECK(!is_same_document_navigation);
1250
Carlos IL42b416592019-10-07 23:10:361251 // Any commit while a post-commit error page is showing should put the
1252 // original entry back, replacing the error page's entry. This includes
1253 // reloads, where the original entry was used as the pending entry and
1254 // should now be at the correct index at commit time.
1255 entries_[last_committed_entry_index_] =
1256 std::move(entry_replaced_by_post_commit_error_);
1257 }
Fergal Daly8e33cf62020-12-12 01:06:071258 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
[email protected]a26023822011-12-29 00:23:551259 details->previous_entry_index = GetLastCommittedEntryIndex();
aelias100c9192017-01-13 00:01:431260 if (pending_entry_ &&
1261 pending_entry_->GetIsOverridingUserAgent() !=
1262 GetLastCommittedEntry()->GetIsOverridingUserAgent())
1263 overriding_user_agent_changed = true;
Xiaohan Wang7f8052e02022-01-14 18:44:281264#if BUILDFLAG(IS_ANDROID)
Shu Yang5756fa422021-11-05 23:02:541265 // TODO(crbug.com/1266277): Clean up the logic of setting
1266 // |overriding_user_agent_changed| post-launch.
Shu Yang9eabbb902021-11-17 00:45:031267 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions)) {
Shu Yang5756fa422021-11-05 23:02:541268 // Must honor user agent overrides in the |navigation_request|, such as
1269 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1270 // result, besides comparing |pending_entry_|'s user agent against
1271 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1272 // agent against LastCommittedEntry's.
1273 if (navigation_request->is_overriding_user_agent() !=
1274 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1275 overriding_user_agent_changed = true;
1276 }
1277 }
Xiaohan Wang7f8052e02022-01-14 18:44:281278#endif // BUILDFLAG(IS_ANDROID)
[email protected]0e8db942008-09-24 21:21:481279 } else {
Gang Wu325f03f42021-02-25 20:00:461280 // GetLastCommittedEntry() is null, so this is the first entry.
Fergal Daly8e33cf62020-12-12 01:06:071281 details->previous_main_frame_url = GURL();
[email protected]0e8db942008-09-24 21:21:481282 details->previous_entry_index = -1;
Gang Wu325f03f42021-02-25 20:00:461283 if (pending_entry_ && pending_entry_->GetIsOverridingUserAgent()) {
1284 // Default setting is NOT override the user agent, so overriding the user
1285 // agent in first entry should be considered as user agent changed as
1286 // well.
1287 overriding_user_agent_changed = true;
1288 }
Xiaohan Wang7f8052e02022-01-14 18:44:281289#if BUILDFLAG(IS_ANDROID)
Shu Yang5756fa422021-11-05 23:02:541290 // TODO(crbug.com/1266277): Clean up the logic of setting
1291 // |overriding_user_agent_changed| post-launch.
Shu Yang9eabbb902021-11-17 00:45:031292 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions)) {
Shu Yang5756fa422021-11-05 23:02:541293 // Must honor user agent overrides in the |navigation_request|, such as
1294 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1295 // result, besides checking |pending_entry_|'s user agent, also need to
1296 // check |navigation_request|'s.
1297 if (navigation_request->is_overriding_user_agent()) {
1298 overriding_user_agent_changed = true;
1299 }
1300 }
Xiaohan Wang7f8052e02022-01-14 18:44:281301#endif // BUILDFLAG(IS_ANDROID)
[email protected]0e8db942008-09-24 21:21:481302 }
[email protected]ecd9d8702008-08-28 22:10:171303
Dave Tapuskaa2ab4f252021-07-08 21:31:281304 bool is_main_frame_navigation = !rfh->GetParent();
1305
Alexander Timind2f2e4f22019-04-02 20:04:531306 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1307 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281308 // For primary frame tree navigations, choose an appropriate
1309 // BackForwardCacheMetrics to be associated with the NavigationEntry, by
1310 // either creating a new object or reusing the previous one depending on
1311 // whether it's a main frame navigation or not.
1312 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
1313 if (navigation_request->frame_tree_node()->frame_tree()->type() ==
1314 FrameTree::Type::kPrimary) {
1315 back_forward_cache_metrics =
1316 BackForwardCacheMetrics::CreateOrReuseBackForwardCacheMetrics(
1317 GetLastCommittedEntry(), is_main_frame_navigation,
1318 params.document_sequence_number);
1319 }
Alexander Timind2f2e4f22019-04-02 20:04:531320 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281321 if (is_main_frame_navigation && !is_same_document_navigation) {
Alexander Timind2f2e4f22019-04-02 20:04:531322 if (NavigationEntryImpl* navigation_entry = GetLastCommittedEntry()) {
1323 if (auto* metrics = navigation_entry->back_forward_cache_metrics()) {
Hajime Hoshic7606502021-04-14 02:42:161324 metrics->MainFrameDidNavigateAwayFromDocument(rfh, navigation_request);
Alexander Timind2f2e4f22019-04-02 20:04:531325 }
1326 }
1327 }
1328
fdegans9caf66a2015-07-30 21:10:421329 // If there is a pending entry at this point, it should have a SiteInstance,
1330 // except for restored entries.
jam48cea9082017-02-15 06:13:291331 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481332 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081333 pending_entry_->IsRestored());
1334 if (pending_entry_ && pending_entry_->IsRestored()) {
Lukasz Anforowicz0de0f452020-12-02 19:57:151335 pending_entry_->set_restore_type(RestoreType::kNotRestored);
jam48cea9082017-02-15 06:13:291336 was_restored = true;
toyoshim0df1d3a2016-09-09 09:52:481337 }
[email protected]e9ba4472008-09-14 15:42:431338
Nasko Oskovaee2f862018-06-15 00:05:521339 // If this is a navigation to a matching pending_entry_ and the SiteInstance
1340 // has changed, this must be treated as a new navigation with replacement.
1341 // Set the replacement bit here and ClassifyNavigation will identify this
Charlie Reisc0f17d2d2021-01-12 18:52:491342 // case and return NEW_ENTRY.
Nasko Oskovaee2f862018-06-15 00:05:521343 if (!rfh->GetParent() && pending_entry_ &&
Rakina Zata Amnif6950d552020-11-24 03:26:101344 pending_entry_->GetUniqueID() ==
1345 navigation_request->commit_params().nav_entry_id &&
Nasko Oskovaee2f862018-06-15 00:05:521346 pending_entry_->site_instance() &&
1347 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1348 DCHECK_NE(-1, pending_entry_index_);
1349 // TODO(nasko,creis): Instead of setting this value here, set
1350 // should_replace_current_entry on the parameters we send to the
1351 // renderer process as part of CommitNavigation. The renderer should
1352 // in turn send it back here as part of |params| and it can be just
1353 // enforced and renderer process terminated on mismatch.
1354 details->did_replace_entry = true;
1355 } else {
1356 // The renderer tells us whether the navigation replaces the current entry.
1357 details->did_replace_entry = params.should_replace_current_entry;
1358 }
[email protected]bcd904482012-02-01 01:54:221359
[email protected]e9ba4472008-09-14 15:42:431360 // Do navigation-type specific actions. These will make and commit an entry.
Rakina Zata Amni2322f4f82022-01-24 13:24:241361 details->type = ClassifyNavigation(rfh, params, navigation_request);
1362 if (GetLastCommittedEntry() && GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551363 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241364 // This is a subframe navigation on the initial empty document, which used
1365 // to not have a NavigationEntry to attach to. Now it can attach to the
1366 // initial NavigationEntry, and we must ensure that its NavigationEntry
1367 // will keep the "initial NavigationEntry" status and won't append a new
1368 // NavigationEntry (it should always do replacement instead).
1369 // See also https://crbug.com/1277414.
1370 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551371 // Subframe navigation on initial NavigationEntry must not append a new
1372 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1373 // means every subframe navigation that happens while we're on the initial
1374 // NavigationEntry will always reuse the existing NavigationEntry and
1375 // just update the corresponding FrameNavigationEntry.
1376 DCHECK_EQ(details->type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1377 } else if (details->type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
1378 // This is a navigation that modifies the initial NavigationEntry, either
1379 // for a replacement or a reload. The initial NavigationEntry should
1380 // retain its "initial NavigationEntry" status in this case.
1381 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241382 } else if (navigation_request->is_synchronous_renderer_commit() &&
1383 !navigation_request->IsSameDocument() && !rfh->GetParent() &&
1384 params.should_replace_current_entry) {
1385 // This is a synchronous about:blank navigation on the main frame, which
1386 // used to not create a NavigationEntry when we have no NavigationEntry on
1387 // FrameTree creation. We now have the initial NavigationEntry and are on
1388 // the initial NavigationEntry. To preserve old behavior, we should still
1389 // keep the "initial" status for the new NavigationEntry that we will
1390 // create for this navigation, so that subframe navigations under the
1391 // synchronously committed about:blank document will never append new
1392 // NavigationEntry, and instead will just reuse the initial
1393 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1394 // See also https://crbug.com/1277414.
1395 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551396 }
1397 }
1398 DCHECK(!details->should_stay_as_initial_entry ||
1399 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201400
eugenebutee08663a2017-04-27 17:43:121401 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441402 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121403
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071404 details->is_prerender_activation =
1405 navigation_request->IsPrerenderedPageActivation();
1406
Peter Boströmd7592132019-01-30 04:50:311407 // Make sure we do not discard the pending entry for a different ongoing
1408 // navigation when a same document commit comes in unexpectedly from the
1409 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1410 // other navigation types. See https://crbug.com/900036.
1411 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061412 bool keep_pending_entry =
1413 is_same_document_navigation &&
1414 details->type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
1415 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311416
[email protected]0e8db942008-09-24 21:21:481417 switch (details->type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061418 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491419 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051420 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001421 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431422 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061423 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491424 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1425 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001426 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431427 break;
[email protected]8ff00d72012-10-23 19:12:211428 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471429 RendererDidNavigateNewSubframe(
1430 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001431 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431432 break;
[email protected]8ff00d72012-10-23 19:12:211433 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391434 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251435 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001436 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081437 // We don't send a notification about auto-subframe PageState during
1438 // UpdateStateForFrame, since it looks like nothing has changed. Send
1439 // it here at commit time instead.
1440 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431441 return false;
creis59d5a47cb2016-08-24 23:57:191442 }
[email protected]e9ba4472008-09-14 15:42:431443 break;
Rakina Zata Amni2322f4f82022-01-24 13:24:241444 case NAVIGATION_TYPE_NAV_IGNORE:
1445 // If a pending navigation was in progress, this canceled it. We should
1446 // discard it and make sure it is removed from the URL bar. After that,
1447 // there is nothing we can do with this navigation, so we just return to
1448 // the caller that nothing has happened.
1449 if (pending_entry_)
1450 DiscardNonCommittedEntries();
1451 return false;
Aran Gilman37d11632019-10-08 23:07:151452 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431453 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151454 break;
[email protected]765b35502008-08-21 00:51:201455 }
1456
[email protected]688aa65c62012-09-28 04:32:221457 // At this point, we know that the navigation has just completed, so
1458 // record the time.
1459 //
1460 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261461 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331462 base::Time timestamp =
1463 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1464 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131465 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221466
Peter Boströmd7592132019-01-30 04:50:311467 // If we aren't keeping the pending entry, there shouldn't be one at this
1468 // point. Clear it again in case any error cases above forgot to do so.
1469 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1470 // been cleared instead of protecting against it.
1471 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551472 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141473
[email protected]e9ba4472008-09-14 15:42:431474 // All committed entries should have nonempty content state so WebKit doesn't
1475 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471476 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321477 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221478 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441479 active_entry->SetHttpStatusCode(params.http_status_code);
Alexander Timind2f2e4f22019-04-02 20:04:531480 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1481 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281482 if (back_forward_cache_metrics &&
1483 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531484 active_entry->set_back_forward_cache_metrics(
1485 std::move(back_forward_cache_metrics));
1486 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281487
1488 // `back_forward_cache_metrics()` may return null as we do not record
1489 // back-forward cache metrics for navigations in non-primary frame trees.
1490 if (active_entry->back_forward_cache_metrics()) {
1491 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1492 navigation_request,
1493 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1494 }
naskoc7533512016-05-06 17:01:121495
Charles Reisc0507202017-09-21 00:40:021496 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1497 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1498 // A mismatch can occur if the renderer lies or due to a unique name collision
1499 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121500 FrameNavigationEntry* frame_entry =
1501 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021502 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1503 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031504 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081505 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1506 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031507 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201508
1509 // Remember the bindings the renderer process has at this point, so that
1510 // we do not grant this entry additional bindings if we come back to it.
1511 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301512 }
[email protected]132e281a2012-07-31 18:32:441513
[email protected]97d8f0d2013-10-29 16:49:211514 // Once it is committed, we no longer need to track several pieces of state on
1515 // the entry.
naskoc7533512016-05-06 17:01:121516 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131517
[email protected]49bd30e62011-03-22 20:12:591518 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221519 // TODO(creis): This check won't pass for subframes until we create entries
1520 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001521 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421522 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591523
[email protected]e9ba4472008-09-14 15:42:431524 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001525 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001526 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311527 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531528
arthursonzogni7ddc6542021-04-09 09:16:501529 active_entry->SetIsOverridingUserAgent(
1530 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031531
[email protected]93f230e02011-06-01 14:40:001532 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291533
aelias100c9192017-01-13 00:01:431534 if (overriding_user_agent_changed)
1535 delegate_->UpdateOverridingUserAgent();
1536
creis03b48002015-11-04 00:54:561537 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1538 // one knows the latest NavigationEntry it is showing (whether it has
1539 // committed anything in this navigation or not). This allows things like
1540 // state and title updates from RenderFrames to apply to the latest relevant
1541 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381542 int nav_entry_id = active_entry->GetUniqueID();
Carlos Caballero40b0efd2021-01-26 11:55:001543 for (FrameTreeNode* node : frame_tree_.Nodes())
dcheng57e39e22016-01-21 00:25:381544 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431545
1546 if (navigation_request->IsPrerenderedPageActivation()) {
1547 BroadcastHistoryOffsetAndLength();
1548 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1549 // is activated. As a result, a "prerenderingchange" event listener sees the
1550 // history.length which is not updated yet. We should guarantee that
1551 // history's length and offset should be updated before a
1552 // "prerenderingchange" event listener runs. One possible approach is to use
1553 // the same IPC which "prerenderingchange" uses, and propagate history's
1554 // length and offset together with that.
1555 }
1556
[email protected]e9ba4472008-09-14 15:42:431557 return true;
initial.commit09911bf2008-07-26 23:55:291558}
1559
[email protected]8ff00d72012-10-23 19:12:211560NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321561 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101562 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241563 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591564 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511565 "ClassifyNavigation");
1566
avi7c6f35e2015-05-08 17:52:381567 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241568 // A new entry. We may or may not have a corresponding pending entry, and
1569 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001570 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491571 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061572 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381573 }
1574
Rakina Zata Amni2322f4f82022-01-24 13:24:241575 // When this is a new subframe navigation, we should have a committed page
1576 // in which it's a subframe. This may not be the case when an iframe is
1577 // navigated on a popup navigated to about:blank (the iframe would be
1578 // written into the popup by script on the main page). For these cases,
1579 // there isn't any navigation stuff we can do, so just ignore it.
1580 if (!GetLastCommittedEntry()) {
1581 trace_return.set_return_reason("new entry, no last committed, ignore");
1582 return NAVIGATION_TYPE_NAV_IGNORE;
1583 }
1584
1585 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511586 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381587 return NAVIGATION_TYPE_NEW_SUBFRAME;
1588 }
1589
Charlie Reisc0f17d2d2021-01-12 18:52:491590 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381591 DCHECK(!params.history_list_was_cleared);
1592
avi39c1edd32015-06-04 20:06:001593 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381594 // All manual subframes would be did_create_new_entry and handled above, so
1595 // we know this is auto.
Rakina Zata Amni2322f4f82022-01-24 13:24:241596 if (GetLastCommittedEntry()) {
1597 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1598 return NAVIGATION_TYPE_AUTO_SUBFRAME;
1599 }
1600
1601 // We ignore subframes created in non-committed pages; we'd appreciate if
1602 // people stopped doing that.
1603 trace_return.set_return_reason("subframe, no last commmited, ignore");
1604 return NAVIGATION_TYPE_NAV_IGNORE;
avi7c6f35e2015-05-08 17:52:381605 }
1606
Rakina Zata Amnif6950d552020-11-24 03:26:101607 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1608 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381609 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1610 // create a new page.
1611
Rakina Zata Amni2322f4f82022-01-24 13:24:241612 // Just like above in the did_create_new_entry case, it's possible to
1613 // scribble onto an uncommitted page. Again, there isn't any navigation
1614 // stuff that we can do, so ignore it here as well.
1615 NavigationEntry* last_committed = GetLastCommittedEntry();
1616 if (!last_committed) {
1617 trace_return.set_return_reason("nav entry 0, no last committed, ignore");
1618 return NAVIGATION_TYPE_NAV_IGNORE;
1619 }
1620
Hayato Ito2ae49442021-07-02 02:59:251621 // This main frame navigation is not a history navigation (since
1622 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1623 // reload or a replacement navigation, which will modify the existing entry.
1624 //
Nasko Oskov332593c2018-08-16 17:21:341625 // TODO(nasko): With error page isolation, reloading an existing session
1626 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491627 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341628 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511629 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491630 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061631 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381632 }
1633
Rakina Zata Amnif6950d552020-11-24 03:26:101634 if (pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id) {
Nasko Oskovaee2f862018-06-15 00:05:521635 // If the SiteInstance of the |pending_entry_| does not match the
1636 // SiteInstance that got committed, treat this as a new navigation with
1637 // replacement. This can happen if back/forward/reload encounters a server
1638 // redirect to a different site or an isolated error page gets successfully
1639 // reloaded into a different SiteInstance.
1640 if (pending_entry_->site_instance() &&
1641 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491642 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061643 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521644 }
creis77c9aa32015-09-25 19:59:421645
Nasko Oskovaee2f862018-06-15 00:05:521646 if (pending_entry_index_ == -1) {
1647 // In this case, we have a pending entry for a load of a new URL but Blink
1648 // didn't do a new navigation (params.did_create_new_entry). First check
1649 // to make sure Blink didn't treat a new cross-process navigation as
1650 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161651 // we must treat it as NEW rather than the converted reload case below,
1652 // since the new SiteInstance doesn't match the last committed entry.
Nasko Oskovaee2f862018-06-15 00:05:521653 if (!GetLastCommittedEntry() ||
1654 GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161655 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061656 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521657 }
1658
1659 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161660 // We will create a pending entry, but NavigateWithoutEntry will convert
1661 // it to a reload since it's the same page and not create a new entry for
1662 // it. (The user doesn't want to have a new back/forward entry when they
1663 // do this.) Therefore we want to just ignore the pending entry and go
1664 // back to where we were (the "existing entry").
1665 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061666 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521667 }
avi7c6f35e2015-05-08 17:52:381668 }
1669
creis26d22632017-04-21 20:23:561670 // Everything below here is assumed to be an existing entry, but if there is
1671 // no last committed entry, we must consider it a new navigation instead.
Nasko Oskovae49e292020-08-13 02:08:511672 if (!GetLastCommittedEntry()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491673 trace_return.set_return_reason("no last committed, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061674 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovae49e292020-08-13 02:08:511675 }
creis26d22632017-04-21 20:23:561676
Rakina Zata Amni153d5702021-09-13 22:48:001677 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381678 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491679 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1680 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161681 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061682 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381683 }
1684
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121685 if (navigation_request->DidEncounterError() &&
1686 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101687 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381688 // If the renderer was going to a new pending entry that got cleared because
1689 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491690 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381691 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511692 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491693 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061694 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381695 }
1696
Charlie Reisc0f17d2d2021-01-12 18:52:491697 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101698 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511699 trace_return.traced_value()->SetInteger("existing_entry_index",
1700 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381701 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441702 // The renderer has committed a navigation to an entry that no longer
1703 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491704 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061705 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381706 }
1707
avi7c6f35e2015-05-08 17:52:381708 // Since we weeded out "new" navigations above, we know this is an existing
1709 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491710 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061711 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381712}
1713
Rakina Zata Amni3460d382021-10-29 00:43:371714void NavigationControllerImpl::UpdateNavigationEntryDetails(
1715 NavigationEntryImpl* entry,
1716 RenderFrameHostImpl* rfh,
1717 const mojom::DidCommitProvisionalLoadParams& params,
1718 NavigationRequest* request,
1719 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001720 bool is_new_entry,
1721 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371722 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171723 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371724 entry->AddOrUpdateFrameEntry(
1725 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
1726 params.document_sequence_number, params.app_history_key,
1727 rfh->GetSiteInstance(), nullptr, params.url,
1728 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171729 Referrer(*params.referrer),
1730 request ? request->common_params().initiator_origin : params.origin,
1731 request ? request->GetRedirectChain() : redirects, params.page_state,
1732 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
1733 (request && request->web_bundle_navigation_info())
Rakina Zata Amni3460d382021-10-29 00:43:371734 ? request->web_bundle_navigation_info()->Clone()
1735 : nullptr,
Rakina Zata Amniafd3c6582021-11-30 06:19:171736 (request ? request->GetSubresourceWebBundleNavigationInfo() : nullptr),
Rakina Zata Amni3460d382021-10-29 00:43:371737 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171738 rfh, request && request->IsSameDocument(),
1739 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371740
1741 if (rfh->GetParent()) {
1742 // Only modify the NavigationEntry for main frame navigations.
1743 return;
1744 }
1745 if (entry->update_virtual_url_with_url())
1746 UpdateVirtualURLToURL(entry, params.url);
1747 // Don't use the page type from the pending entry. Some interstitial page
1748 // may have set the type to interstitial. Once we commit, however, the page
1749 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171750 entry->set_page_type((request && request->DidEncounterError())
1751 ? PAGE_TYPE_ERROR
1752 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431753 if (commit_details && commit_details->should_stay_as_initial_entry) {
1754 // Retain the "initial NavigationEntry" status.
1755 if (request->IsSameDocument()) {
1756 // If this is for a same-document navigation, the NavigationEntry must be
1757 // reused and should already be marked as the initial NavigationEntry.
1758 DCHECK(entry->IsInitialEntry());
1759 } else {
1760 // If this is for a cross-document navigation, it can be caused by a
1761 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1762 // "for synchronous about:blank" in the latter case, and also when it is
1763 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1764 // is not for a synchronous about:blank commit.
1765 NavigationEntryImpl::InitialNavigationEntryState new_state =
1766 NavigationEntryImpl::InitialNavigationEntryState::
1767 kInitialNotForSynchronousAboutBlank;
1768 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1769 request->is_synchronous_renderer_commit()) {
1770 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1771 kInitialForSynchronousAboutBlank;
1772 }
1773 entry->set_initial_navigation_entry_state(new_state);
1774 }
1775 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1776 // Remove the "initial NavigationEntry" status.
1777 entry->set_initial_navigation_entry_state(
1778 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001779 }
Rakina Zata Amniddf10502022-01-15 02:56:551780
Rakina Zata Amni3460d382021-10-29 00:43:371781 if (is_new_entry) {
1782 // Some properties of the NavigationEntry are only set when the entry is
1783 // new (we aren't reusing it).
1784 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171785 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1786 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371787 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1788 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1789 } else {
1790 // We are reusing the NavigationEntry. The site instance will normally be
1791 // the same except for a few cases:
1792 // 1) session restore, when no site instance will be assigned or
1793 // 2) redirect, when the site instance is reset.
1794 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1795 entry->site_instance() == rfh->GetSiteInstance());
1796 }
1797}
1798
Rakina Zata Amniafd3c6582021-11-30 06:19:171799void NavigationControllerImpl::CreateInitialEntry() {
1800 DCHECK_EQ(entries_.size(), 0u);
1801 RenderFrameHostImpl* rfh = frame_tree_.root()->current_frame_host();
1802 auto params = mojom::DidCommitProvisionalLoadParams::New();
1803 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1804 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1805 // before we have initial NavigationEntries.
1806 params->url = GURL::EmptyGURL();
1807 params->http_status_code = 0;
1808 params->url_is_unreachable = false;
1809 params->method = "GET";
1810 params->should_replace_current_entry = false;
1811 params->post_id = -1;
1812 params->embedding_token = base::UnguessableToken::Create();
1813 params->navigation_token = base::UnguessableToken::Create();
1814 params->did_create_new_entry = true;
1815 params->origin = rfh->GetLastCommittedOrigin();
1816 params->should_update_history = true;
1817 params->item_sequence_number = 0;
1818 params->document_sequence_number = 0;
1819 bool is_in_fenced_frame_tree = rfh->frame_tree_node()->IsInFencedFrameTree();
1820 params->transition = is_in_fenced_frame_tree
1821 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1822 : ui::PAGE_TRANSITION_LINK;
1823 params->referrer = blink::mojom::Referrer::New();
1824
1825 // Create and insert the initial NavigationEntry.
1826 auto new_entry = std::make_unique<NavigationEntryImpl>(
1827 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
1828 rfh->GetLastCommittedOrigin(), std::u16string() /* title */,
1829 ui::PAGE_TRANSITION_TYPED, false /* renderer_initiated */,
1830 nullptr /* blob_url_loader_factory */, true /* is_initial_entry */);
1831 UpdateNavigationEntryDetails(
1832 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001833 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1834 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171835
1836 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1837 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001838 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171839}
1840
Charlie Reisc0f17d2d2021-01-12 18:52:491841void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321842 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071843 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361844 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441845 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471846 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001847 NavigationRequest* request,
1848 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571849 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071850 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451851 request->common_params().initiator_origin;
Lukasz Anforowicz435bcb582019-07-12 20:50:061852
creisf49dfc92016-07-26 17:05:181853 // First check if this is an in-page navigation. If so, clone the current
1854 // entry instead of looking at the pending entry, because the pending entry
1855 // does not have any subframe history items.
eugenebut604866f2017-05-10 21:35:361856 if (is_same_document && GetLastCommittedEntry()) {
Nate Chapin63db0d12022-01-20 22:03:301857 FrameNavigationEntry* previous_frame_entry =
1858 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451859 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481860 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Nate Chapinfbfe5af2021-06-10 17:22:081861 params.document_sequence_number, params.app_history_key,
1862 rfh->GetSiteInstance(), nullptr, params.url,
1863 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amni82fafba2021-03-11 07:07:091864 Referrer(*params.referrer), initiator_origin,
1865 request->GetRedirectChain(), params.page_state, params.method,
1866 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:391867 nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:481868 request->GetSubresourceWebBundleNavigationInfo(),
Antonio Sartori78a749f2020-11-30 12:03:391869 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301870 nullptr /* policy_container_policies */,
1871 // Try to preserve protect_url_in_app_history from the previous
1872 // FrameNavigationEntry.
1873 previous_frame_entry &&
1874 previous_frame_entry->protect_url_in_app_history());
Charles Reisf44482022017-10-13 21:15:031875
creisf49dfc92016-07-26 17:05:181876 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Harkiran Bolaria081c5c22021-09-13 08:44:531877 frame_entry, true, request->frame_tree_node(), frame_tree_.root());
Mike West800532c2021-10-14 09:26:521878 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1879 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571880 // TODO(jam): we had one report of this with a URL that was redirecting to
1881 // only tildes. Until we understand that better, don't copy the cert in
1882 // this case.
1883 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571884 }
creisf49dfc92016-07-26 17:05:181885
Patrick Monette50e8bd82019-06-13 22:40:451886 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1887 // that |frame_entry| should now have a reference count of exactly 2: one
1888 // due to the local variable |frame_entry|, and another due to |new_entry|
1889 // also retaining one. This should never fail, because it's the main frame.
1890 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181891 }
1892
Harkiran Bolaria59290d62021-03-17 01:53:011893 // If this is an activation navigation from a prerendered page, transfer the
1894 // new entry from an entry already created and stored in the
1895 // NavigationRequest. |new_entry| will not have been set prior to this as
1896 // |is_same_document| is mutually exclusive with
1897 // |IsPrerenderedPageActivation|.
1898 if (request->IsPrerenderedPageActivation()) {
1899 DCHECK(!is_same_document);
1900 DCHECK(!new_entry);
1901 new_entry = request->TakePrerenderNavigationEntry();
1902 DCHECK(new_entry);
1903 }
1904
Charlie Reisc0f17d2d2021-01-12 18:52:491905 // Only make a copy of the pending entry if it is appropriate for the new
1906 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451907 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041908 // 1. The SiteInstance hasn't been assigned to something else.
1909 // 2. The pending entry was intended as a new entry, rather than being a
1910 // history navigation that was interrupted by an unrelated,
1911 // renderer-initiated navigation.
1912 // TODO(csharrison): Investigate whether we can remove some of the coarser
1913 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451914 if (!new_entry && PendingEntryMatchesRequest(request) &&
1915 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:341916 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:431917 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:351918 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:431919
Camille Lamy62b826012019-02-26 09:15:471920 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451921 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:181922 }
1923
Charlie Reisc0f17d2d2021-01-12 18:52:491924 // For cross-document commits with no matching pending entry, create a new
1925 // entry.
creisf49dfc92016-07-26 17:05:181926 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061927 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:071928 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
1929 initiator_origin,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:581930 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:451931 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:171932 nullptr, // blob_url_loader_factory
1933 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:241934
1935 // Find out whether the new entry needs to update its virtual URL on URL
1936 // change and set up the entry accordingly. This is needed to correctly
1937 // update the virtual URL when replaceState is called after a pushState.
1938 GURL url = params.url;
1939 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:491940 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:411941 // update the virtual URL based on the new URL. For example, this is needed
1942 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1943 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:371944 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1945 &url, browser_context_, &needs_update);
1946 new_entry->set_update_virtual_url_with_url(needs_update);
1947
Camille Lamy62b826012019-02-26 09:15:471948 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451949 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:431950 }
1951
Harkiran Bolaria59290d62021-03-17 01:53:011952 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
1953 // for prerendered contents, if any. This is because prerendering/activation
1954 // technically won't be creating a new document. Unlike BFCache, prerendering
1955 // creates a new NavigationEntry rather than using an existing one.
1956 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:371957 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
1958 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:001959 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:081960
Harkiran Bolaria59290d62021-03-17 01:53:011961 // history.pushState() is classified as a navigation to a new page, but sets
1962 // is_same_document to true. In this case, we already have the title and
1963 // favicon available, so set them immediately.
1964 if (is_same_document && GetLastCommittedEntry()) {
1965 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
1966 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
1967 }
[email protected]3a868f212014-08-09 10:41:191968 }
[email protected]ff64b3e2014-05-31 04:07:331969
[email protected]60d6cca2013-04-30 08:47:131970 DCHECK(!params.history_list_was_cleared || !replace_entry);
1971 // The browser requested to clear the session history when it initiated the
1972 // navigation. Now we know that the renderer has updated its state accordingly
1973 // and it is safe to also clear the browser side history.
1974 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:551975 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:131976 entries_.clear();
1977 last_committed_entry_index_ = -1;
1978 }
1979
Nasko Oskovaee2f862018-06-15 00:05:521980 // If this is a new navigation with replacement and there is a
1981 // pending_entry_ which matches the navigation reported by the renderer
1982 // process, then it should be the one replaced, so update the
1983 // last_committed_entry_index_ to use it.
1984 if (replace_entry && pending_entry_index_ != -1 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101985 pending_entry_->GetUniqueID() == request->commit_params().nav_entry_id) {
Nasko Oskovaee2f862018-06-15 00:05:521986 last_committed_entry_index_ = pending_entry_index_;
1987 }
1988
Alexander Timine3ec4192020-04-20 16:39:401989 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:411990 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:401991 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:051992
Carlos IL42b416592019-10-07 23:10:361993 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:311994 !request->post_commit_error_page_html().empty(),
Rakina Zata Amnia4e27222021-12-22 01:05:001995 rfh->frame_tree_node()->IsInFencedFrameTree(),
1996 commit_details);
[email protected]e9ba4472008-09-14 15:42:431997}
1998
Charlie Reisc0f17d2d2021-01-12 18:52:491999void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322000 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072001 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362002 bool is_same_document,
jam48cea9082017-02-15 06:13:292003 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452004 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002005 bool keep_pending_entry,
2006 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562007 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2008 << "that a last committed entry exists.";
2009
[email protected]e9ba4472008-09-14 15:42:432010 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002011 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432012
Charlie Reis7e2cb6d2021-01-26 01:27:162013 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002014 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162015 // We're guaranteed to have a last committed entry if intended_as_new_entry
2016 // is true.
avicbdc4c12015-07-01 16:07:112017 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162018 DCHECK(entry);
2019
2020 // If the NavigationRequest matches a new pending entry and is classified as
2021 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2022 // converted to a reload, such as a user pressing enter in the omnibox.
2023 if (pending_entry_ && pending_entry_index_ == -1 &&
2024 pending_entry_->GetUniqueID() ==
2025 request->commit_params().nav_entry_id) {
2026 // Note: The pending entry will usually have a real ReloadType here, but
2027 // it can still be ReloadType::NONE in cases that
2028 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2029
2030 // If we classified this correctly, the SiteInstance should not have
2031 // changed.
2032 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2033
2034 // For converted reloads, we assign the entry's unique ID to be that of
2035 // the new one. Since this is always the result of a user action, we want
2036 // to dismiss infobars, etc. like a regular user-initiated navigation.
2037 entry->set_unique_id(pending_entry_->GetUniqueID());
2038
2039 // The extra headers may have changed due to reloading with different
2040 // headers.
2041 entry->set_extra_headers(pending_entry_->extra_headers());
2042 }
2043 // Otherwise, this was intended as a new entry but the pending entry was
2044 // lost in the meantime and no new entry was created. We are stuck at the
2045 // last committed entry.
2046
2047 // Even if this is a converted reload from pressing enter in the omnibox,
2048 // the server could redirect, requiring an update to the SSL status. If this
2049 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452050 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162051 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472052 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452053 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162054 }
Rakina Zata Amnif6950d552020-11-24 03:26:102055 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112056 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102057 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162058
eugenebut604866f2017-05-10 21:35:362059 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452060 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362061 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2062 // this was a restored same document navigation entry, then it won't have
2063 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2064 // navigated it.
jam48cea9082017-02-15 06:13:292065 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522066 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2067 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292068 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2069 was_restored) {
2070 entry->GetSSL() = last_entry->GetSSL();
2071 }
2072 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452073 // In rapid back/forward navigations |request| sometimes won't have a cert
2074 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192075 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452076 if (request->GetSSLInfo().has_value() &&
2077 request->GetSSLInfo()->is_valid()) {
2078 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522079 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2080 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192081 entry->GetSSL() = SSLStatus();
2082 }
jam48cea9082017-02-15 06:13:292083 }
avicbdc4c12015-07-01 16:07:112084 } else {
2085 // This is renderer-initiated. The only kinds of renderer-initated
Rakina Zata Amni557afb92021-07-17 04:39:572086 // navigations that are EXISTING_ENTRY are same-document navigations that
2087 // result in replacement (e.g. history.replaceState(), location.replace(),
2088 // forced replacements for trivial session history contexts). For these
2089 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112090 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102091
Mikel Astizba9cf2fd2017-12-17 10:38:102092 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2093 // to avoid misleading interpretations (e.g. URLs paired with
2094 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2095 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2096 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2097
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572098 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102099
eugenebut604866f2017-05-10 21:35:362100 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452101 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362102 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472103 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452104 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112105 }
2106 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432107
Rakina Zata Amni3460d382021-10-29 00:43:372108 UpdateNavigationEntryDetails(entry, rfh, params, request,
2109 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002110 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302111
[email protected]5ccd4dc2012-10-24 02:28:142112 // The redirected to page should not inherit the favicon from the previous
2113 // page.
eugenebut604866f2017-05-10 21:35:362114 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482115 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142116
Peter Boströmd7592132019-01-30 04:50:312117 // We should also usually discard the pending entry if it corresponds to a
2118 // different navigation, since that one is now likely canceled. In rare
2119 // cases, we leave the pending entry for another navigation in place when we
2120 // know it is still ongoing, to avoid a flicker in the omnibox (see
2121 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432122 //
2123 // Note that we need to use the "internal" version since we don't want to
2124 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312125 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002126 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392127
Carlos IL4dea8902020-05-26 15:14:292128 // Update the last committed index to reflect the committed entry.
avicbdc4c12015-07-01 16:07:112129 last_committed_entry_index_ = GetIndexOfEntry(entry);
[email protected]e9ba4472008-09-14 15:42:432130}
2131
[email protected]d202a7c2012-01-04 07:53:472132void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322133 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072134 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362135 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472136 bool replace_entry,
2137 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002138 NavigationRequest* request,
2139 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262140 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2141 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552142 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2143 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112144
[email protected]e9ba4472008-09-14 15:42:432145 // Manual subframe navigations just get the current entry cloned so the user
2146 // can go back or forward to it. The actual subframe information will be
2147 // stored in the page state for each of those entries. This happens out of
2148 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092149 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2150 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382151
Mikel Astizba9cf2fd2017-12-17 10:38:102152 // The DCHECK below documents the fact that we don't know of any situation
2153 // where |replace_entry| is true for subframe navigations. This simplifies
2154 // reasoning about the replacement struct for subframes (see
2155 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2156 DCHECK(!replace_entry);
2157
Patrick Monette50e8bd82019-06-13 22:40:452158 // This FrameNavigationEntry might not end up being used in the
2159 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072160 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452161 request->common_params().initiator_origin;
Nate Chapin63db0d12022-01-20 22:03:302162 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2163 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2164 request->GetURL());
2165 bool protect_url_in_app_history = false;
2166 if (is_same_document) {
2167 FrameNavigationEntry* previous_frame_entry =
2168 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
2169 // Try to preserve protect_url_in_app_history from the previous
2170 // FrameNavigationEntry.
2171 protect_url_in_app_history =
2172 previous_frame_entry &&
2173 previous_frame_entry->protect_url_in_app_history();
2174 } else {
2175 protect_url_in_app_history =
2176 policy_container_policies &&
2177 ShouldProtectUrlInAppHistory(
2178 policy_container_policies->referrer_policy);
2179 }
2180
Patrick Monette50e8bd82019-06-13 22:40:452181 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482182 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Nate Chapinfbfe5af2021-06-10 17:22:082183 params.document_sequence_number, params.app_history_key,
2184 rfh->GetSiteInstance(), nullptr, params.url,
2185 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amni82fafba2021-03-11 07:07:092186 Referrer(*params.referrer), initiator_origin, request->GetRedirectChain(),
arthursonzogni73fe3212020-11-17 13:24:072187 params.page_state, params.method, params.post_id,
2188 nullptr /* blob_url_loader_factory */,
Tsuyoshi Horo0c605782020-05-27 00:21:032189 request->web_bundle_navigation_info()
2190 ? request->web_bundle_navigation_info()->Clone()
Antonio Sartori78a749f2020-11-30 12:03:392191 : nullptr,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482192 request->GetSubresourceWebBundleNavigationInfo(),
Nate Chapin63db0d12022-01-20 22:03:302193 std::move(policy_container_policies), protect_url_in_app_history);
Charles Reisf44482022017-10-13 21:15:032194
creisce0ef3572017-01-26 17:53:082195 std::unique_ptr<NavigationEntryImpl> new_entry =
2196 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452197 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Carlos Caballero40b0efd2021-01-26 11:55:002198 frame_tree_.root());
creise062d542015-08-25 02:01:552199
Alexander Timine3ec4192020-04-20 16:39:402200 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412201 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402202 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472203
creisce0ef3572017-01-26 17:53:082204 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452205 // to replace, which can happen due to a unique name change. See
2206 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2207 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382208
Dave Tapuska87696ae2021-11-18 18:48:312209 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Rakina Zata Amnia4e27222021-12-22 01:05:002210 rfh->frame_tree_node()->IsInFencedFrameTree(),
2211 commit_details);
[email protected]e9ba4472008-09-14 15:42:432212}
2213
[email protected]d202a7c2012-01-04 07:53:472214bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322215 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072216 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392217 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252218 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002219 NavigationRequest* request,
2220 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292221 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2222 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2223
[email protected]e9ba4472008-09-14 15:42:432224 // We're guaranteed to have a previously committed entry, and we now need to
2225 // handle navigation inside of a subframe in it without creating a new entry.
2226 DCHECK(GetLastCommittedEntry());
2227
creis913c63ce2016-07-16 19:52:522228 // For newly created subframes, we don't need to send a commit notification.
2229 // This is only necessary for history navigations in subframes.
2230 bool send_commit_notification = false;
2231
Rakina Zata Amnif6950d552020-11-24 03:26:102232 // If |nav_entry_id| is non-zero and matches an existing entry, this
2233 // is a history navigation. Update the last committed index accordingly. If
2234 // we don't recognize the |nav_entry_id|, it might be a recently
2235 // pruned entry. We'll handle it below.
2236 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2237 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472238 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062239 // Make sure that a subframe commit isn't changing the main frame's
2240 // origin. Otherwise the renderer process may be confused, leading to a
2241 // URL spoof. We can't check the path since that may change
2242 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572243 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2244 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242245 // We should use checks similar to RenderFrameHostImpl's
2246 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2247 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572248 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2249 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2250 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2251 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522252 current_top_url.DeprecatedGetOriginAsURL() !=
2253 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442254 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512255 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062256 }
creis3cdc3b02015-05-29 23:00:472257
creis913c63ce2016-07-16 19:52:522258 // We only need to discard the pending entry in this history navigation
2259 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062260 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002261 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522262
2263 // History navigations should send a commit notification.
2264 send_commit_notification = true;
avi98405c22015-05-21 20:47:062265 }
[email protected]e9ba4472008-09-14 15:42:432266 }
[email protected]f233e4232013-02-23 00:55:142267
creisce0ef3572017-01-26 17:53:082268 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2269 // it may be a "history auto" case where we update an existing one.
2270 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372271
2272 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2273 // exists), or we may want to clobber it and create a new one. We update in
2274 // cases where the corresponding FrameNavigationEntry is conceptually similar
2275 // to the document described by the commit params: same-document
2276 // navigations, history traversal to an existing entry, and reloads (including
2277 // a "soft reload" where we navigate to the same url without flagging it as a
2278 // reload). But in the case of a different document that is not logically
2279 // related to the committed FrameNavigationEntry's document (cross-document,
2280 // not same url, not a reload, not a history traversal), we replace rather
2281 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252282 //
Nate Chapin9f169072021-06-09 19:32:372283 // In the case where we update, the FrameNavigationEntry will potentially be
2284 // shared across multiple NavigationEntries, and any updates will be reflected
2285 // in all of those NavigationEntries. In the replace case, any existing
2286 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252287 //
2288 // When navigating away from the initial empty document, we also update rather
2289 // than replace. Either update or replace will overwrite the initial empty
2290 // document state for |last_committed|, but if the FrameNavigationEntry for
2291 // the initial empty document is shared across multiple NavigationEntries (due
2292 // to a navigation in another frame), we want to make sure we overwrite the
2293 // initial empty document state everywhere this FrameNavigationEntry is used,
2294 // which is accompished by updating the existing FrameNavigationEntry.
Nate Chapin9f169072021-06-09 19:32:372295 FrameNavigationEntry* last_committed_frame_entry =
2296 last_committed->GetFrameEntry(rfh->frame_tree_node());
2297 NavigationEntryImpl::UpdatePolicy update_policy =
2298 NavigationEntryImpl::UpdatePolicy::kUpdate;
2299 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312300 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372301 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252302 last_committed_frame_entry->url() != params.url &&
2303 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372304 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2305 }
2306
Rakina Zata Amni3460d382021-10-29 00:43:372307 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002308 update_policy, false /* is_new_entry */,
2309 commit_details);
creis625a0c7d2015-03-24 23:17:122310
creis913c63ce2016-07-16 19:52:522311 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432312}
2313
[email protected]d202a7c2012-01-04 07:53:472314int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232315 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032316 for (size_t i = 0; i < entries_.size(); ++i) {
2317 if (entries_[i].get() == entry)
2318 return i;
2319 }
2320 return -1;
[email protected]765b35502008-08-21 00:51:202321}
2322
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572323void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242324 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572325 NavigationControllerImpl* source =
2326 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572327 // Verify that we look new.
Rakina Zata Amni2322f4f82022-01-24 13:24:242328 if (blink::features::IsInitialNavigationEntryEnabled()) {
2329 DCHECK_EQ(1, GetEntryCount());
2330 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
2331 } else {
2332 DCHECK_EQ(0, GetEntryCount());
2333 }
Lei Zhang96031532019-10-10 19:05:472334 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172335 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572336
Rakina Zata Amniafd3c6582021-11-30 06:19:172337 if (source->GetEntryCount() == 0) {
Rakina Zata Amniafd3c6582021-11-30 06:19:172338 return;
2339 }
[email protected]ce3fa3c2009-04-20 19:55:572340
Francois Dorayeaace782017-06-21 16:37:242341 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442342 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572343 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572344
Fergal Dalya1d569972021-03-16 03:24:532345 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302346 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532347 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2348 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302349 }
[email protected]4e6419c2010-01-15 04:50:342350
Lukasz Anforowicz0de0f452020-12-02 19:57:152351 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572352}
2353
Aran Gilman37d11632019-10-08 23:07:152354void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2355 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162356 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012357 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162358
[email protected]d202a7c2012-01-04 07:53:472359 NavigationControllerImpl* source =
2360 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252361
avi2b177592014-12-10 02:08:022362 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012363 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252364
[email protected]474f8512013-05-31 22:31:162365 // We now have one entry, possibly with a new pending entry. Ensure that
2366 // adding the entries from source won't put us over the limit.
2367 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572368 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572369 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252370
Carlos IL4dea8902020-05-26 15:14:292371 // Insert the entries from source. Ignore any pending entry, since it has not
2372 // committed in source.
[email protected]474f8512013-05-31 22:31:162373 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172374 DCHECK_NE(max_source_index, -1);
2375 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572376
2377 // Ignore the source's current entry if merging with replacement.
2378 // TODO(davidben): This should preserve entries forward of the current
2379 // too. http://crbug.com/317872
2380 if (replace_entry && max_source_index > 0)
2381 max_source_index--;
2382
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572383 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252384
2385 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552386 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142387
Hayato Ito2c8c08d02021-06-23 03:38:432388 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252389}
2390
[email protected]79368982013-11-13 01:11:012391bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162392 // If there is no last committed entry, we cannot prune. Even if there is a
2393 // pending entry, it may not commit, leaving this WebContents blank, despite
2394 // possibly giving it new entries via CopyStateFromAndPrune.
2395 if (last_committed_entry_index_ == -1)
2396 return false;
[email protected]9350602e2013-02-26 23:27:442397
[email protected]474f8512013-05-31 22:31:162398 // We cannot prune if there is a pending entry at an existing entry index.
2399 // It may not commit, so we have to keep the last committed entry, and thus
2400 // there is no sensible place to keep the pending entry. It is ok to have
2401 // a new pending entry, which can optionally commit as a new navigation.
2402 if (pending_entry_index_ != -1)
2403 return false;
2404
[email protected]474f8512013-05-31 22:31:162405 return true;
2406}
2407
[email protected]79368982013-11-13 01:11:012408void NavigationControllerImpl::PruneAllButLastCommitted() {
2409 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162410
avi2b177592014-12-10 02:08:022411 DCHECK_EQ(0, last_committed_entry_index_);
2412 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442413
Hayato Ito2c8c08d02021-06-23 03:38:432414 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442415}
2416
[email protected]79368982013-11-13 01:11:012417void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162418 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012419 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262420
[email protected]474f8512013-05-31 22:31:162421 // Erase all entries but the last committed entry. There may still be a
2422 // new pending entry after this.
2423 entries_.erase(entries_.begin(),
2424 entries_.begin() + last_committed_entry_index_);
2425 entries_.erase(entries_.begin() + 1, entries_.end());
2426 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262427}
2428
Christian Dullweber1af31e62018-02-22 11:49:482429void NavigationControllerImpl::DeleteNavigationEntries(
2430 const DeletionPredicate& deletionPredicate) {
2431 // It is up to callers to check the invariants before calling this.
2432 CHECK(CanPruneAllButLastCommitted());
2433 std::vector<int> delete_indices;
2434 for (size_t i = 0; i < entries_.size(); i++) {
2435 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572436 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482437 delete_indices.push_back(i);
2438 }
2439 }
2440 if (delete_indices.empty())
2441 return;
2442
2443 if (delete_indices.size() == GetEntryCount() - 1U) {
2444 PruneAllButLastCommitted();
2445 } else {
2446 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382447 for (const auto& index : base::Reversed(delete_indices)) {
2448 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482449 }
Hayato Ito2c8c08d02021-06-23 03:38:432450 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482451 }
2452 delegate()->NotifyNavigationEntriesDeleted();
2453}
2454
Shivani Sharma883f5f32019-02-12 18:20:012455bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2456 auto* entry = GetEntryAtIndex(index);
2457 return entry && entry->should_skip_on_back_forward_ui();
2458}
2459
Carlos Caballero35ce710c2019-09-19 10:59:452460BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2461 return back_forward_cache_;
2462}
2463
clamy987a3752018-05-03 17:36:262464void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2465 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2466 // progress, since this will cause a use-after-free. (We only allow this
2467 // when the tab is being destroyed for shutdown, since it won't return to
2468 // NavigateToEntry in that case.) http://crbug.com/347742.
Takashi Toyoshimaea534ef22021-07-21 03:27:592469 CHECK(!in_navigate_to_pending_entry_ || frame_tree_.IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262470
2471 if (was_failure && pending_entry_) {
2472 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2473 } else {
2474 failed_pending_entry_id_ = 0;
2475 }
2476
2477 if (pending_entry_) {
2478 if (pending_entry_index_ == -1)
2479 delete pending_entry_;
2480 pending_entry_index_ = -1;
2481 pending_entry_ = nullptr;
2482 }
arthursonzogni66f711c2019-10-08 14:40:362483
2484 // Ensure any refs to the current pending entry are ignored if they get
2485 // deleted, by clearing the set of known refs. All future pending entries will
2486 // only be affected by new refs.
2487 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262488}
2489
2490void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2491 if (pending_entry_)
2492 pending_entry_->set_ssl_error(error);
2493}
2494
Xiaohan Wang7f8052e02022-01-14 18:44:282495#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422496// static
2497bool NavigationControllerImpl::ValidateDataURLAsString(
2498 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2499 if (!data_url_as_string)
2500 return false;
2501
2502 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2503 return false;
2504
2505 // The number of characters that is enough for validating a data: URI.
2506 // From the GURL's POV, the only important part here is scheme, it doesn't
2507 // check the actual content. Thus we can take only the prefix of the url, to
2508 // avoid unneeded copying of a potentially long string.
2509 const size_t kDataUriPrefixMaxLen = 64;
2510 GURL data_url(
2511 std::string(data_url_as_string->front_as<char>(),
2512 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2513 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2514 return false;
2515
2516 return true;
2517}
2518#endif
2519
Shivani Sharma194877032019-03-07 17:52:472520void NavigationControllerImpl::NotifyUserActivation() {
2521 // When a user activation occurs, ensure that all adjacent entries for the
2522 // same document clear their skippable bit, so that the history manipulation
2523 // intervention does not apply to them.
2524 auto* last_committed_entry = GetLastCommittedEntry();
2525 if (!last_committed_entry)
2526 return;
Shivani Sharma194877032019-03-07 17:52:472527
shivanigithub99368382021-06-16 18:33:372528 if (base::FeatureList::IsEnabled(
2529 features::kDebugHistoryInterventionNoUserActivation)) {
2530 return;
2531 }
2532
Shivani Sharmac4cc8922019-04-18 03:11:172533 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472534}
2535
clamy987a3752018-05-03 17:36:262536bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2537 RenderFrameHostImpl* render_frame_host,
Julie Jeongeun Kimed2e5ba72019-09-12 10:14:172538 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client) {
clamy987a3752018-05-03 17:36:262539 NavigationEntryImpl* entry =
2540 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2541 if (!entry)
2542 return false;
2543
2544 FrameNavigationEntry* frame_entry =
2545 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2546 if (!frame_entry)
2547 return false;
2548
Nate Chapin45f620582021-09-30 17:45:432549 // |is_browser_initiated| is false here because a navigation in a new subframe
2550 // always begins with renderer action (i.e., an HTML element being inserted
2551 // into the DOM), so it is always renderer-initiated.
Camille Lamy5193caa2018-10-12 11:59:422552 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572553 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232554 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432555 true /* is_history_navigation_in_new_child */,
2556 false /* is_browser_initiated */);
clamyea99ea12018-05-28 13:54:232557
2558 if (!request)
2559 return false;
2560
arthursonzognif046d4a2019-12-12 19:08:102561 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412562
Lukasz Anforowicz9ee83c272020-12-01 20:14:052563 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2564 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232565
2566 return true;
clamy987a3752018-05-03 17:36:262567}
2568
Tsuyoshi Horo52fd08e2020-07-07 07:03:452569bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2570 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2571 if (!entry)
2572 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432573
2574 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2575 // We should never navigate to an existing initial NavigationEntry that is
2576 // the initial NavigationEntry for the initial empty document that hasn't
2577 // been overridden by the synchronous about:blank commit, to preserve
2578 // legacy behavior where trying to reload when the main frame is on the
2579 // initial empty document won't result in a navigation. See also
2580 // https://crbug.com/1277414.
2581 return false;
2582 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452583 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2584 if (!frame_entry)
2585 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142586 ReloadType reload_type = ReloadType::NORMAL;
2587 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452588 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142589 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452590 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432591 false /* is_history_navigation_in_new_child */,
2592 true /* is_browser_initiated */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452593 if (!request)
2594 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052595 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452596 return true;
2597}
2598
Dave Tapuska8bfd84c2019-03-26 20:47:162599void NavigationControllerImpl::GoToOffsetInSandboxedFrame(
2600 int offset,
2601 int sandbox_frame_tree_node_id) {
2602 if (!CanGoToOffset(offset))
2603 return;
Nate Chapin45f620582021-09-30 17:45:432604 GoToIndex(GetIndexForOffset(offset), sandbox_frame_tree_node_id,
2605 false /* is_browser_initiated */);
Dave Tapuska8bfd84c2019-03-26 20:47:162606}
2607
clamy987a3752018-05-03 17:36:262608void NavigationControllerImpl::NavigateFromFrameProxy(
2609 RenderFrameHostImpl* render_frame_host,
2610 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022611 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452612 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072613 const absl::optional<url::Origin>& initiator_origin,
clamy987a3752018-05-03 17:36:262614 bool is_renderer_initiated,
2615 SiteInstance* source_site_instance,
2616 const Referrer& referrer,
2617 ui::PageTransition page_transition,
2618 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252619 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262620 const std::string& method,
2621 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092622 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142623 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212624 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
Anton Bikineevf62d1bf2021-05-15 17:56:072625 const absl::optional<blink::Impression>& impression) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582626 if (is_renderer_initiated)
2627 DCHECK(initiator_origin.has_value());
2628
clamy987a3752018-05-03 17:36:262629 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582630
Rakina Zata Amni2322f4f82022-01-24 13:24:242631 // Don't allow an entry replacement if there is no entry to replace.
2632 // http://crbug.com/457149
2633 if (GetEntryCount() == 0)
2634 should_replace_current_entry = false;
2635
clamy987a3752018-05-03 17:36:262636 // Create a NavigationEntry for the transfer, without making it the pending
2637 // entry. Subframe transfers should have a clone of the last committed entry
2638 // with a FrameNavigationEntry for the target frame. Main frame transfers
2639 // should have a new NavigationEntry.
2640 // TODO(creis): Make this unnecessary by creating (and validating) the params
2641 // directly, passing them to the destination RenderFrameHost. See
2642 // https://crbug.com/536906.
2643 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262644 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262645 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amni2322f4f82022-01-24 13:24:242646 if (GetLastCommittedEntry()) {
2647 entry = GetLastCommittedEntry()->Clone();
2648 entry->set_extra_headers(extra_headers);
2649 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2650 // Renderer-initiated navigation that target a remote frame are currently
2651 // classified as browser-initiated when this one has already navigated.
2652 // See https://crbug.com/722251.
2653 } else {
2654 // If there's no last committed entry, create an entry for about:blank
2655 // with a subframe entry for our destination.
2656 // TODO(creis): Ensure this case can't exist in https://crbug.com/524208.
2657 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
2658 GURL(url::kAboutBlankURL), referrer, initiator_origin,
2659 source_site_instance, page_transition, is_renderer_initiated,
2660 extra_headers, browser_context_,
2661 nullptr /* blob_url_loader_factory */));
2662 }
Rakina Zata Amniafd3c6582021-11-30 06:19:172663 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2664 // Renderer-initiated navigation that target a remote frame are currently
2665 // classified as browser-initiated when this one has already navigated.
2666 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372667 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2668 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2669 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2670 // same-document navigation), they will still be present in the
2671 // committed NavigationEntry that will be referenced to construct the new
2672 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262673 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082674 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582675 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072676 absl::nullopt /* commit_origin */, referrer, initiator_origin,
Miyoung Shin5d77f72072020-10-09 15:14:202677 std::vector<GURL>(), blink::PageState(), method, -1,
Antonio Sartori78a749f2020-11-30 12:03:392678 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482679 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori79d549d2021-02-18 12:59:542680 nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262681 } else {
2682 // Main frame case.
2683 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz641234d52019-11-07 21:07:102684 url, referrer, initiator_origin, source_site_instance, page_transition,
2685 is_renderer_initiated, extra_headers, browser_context_,
Hayato Ito303654c2021-06-30 09:07:542686 blob_url_loader_factory));
clamy987a3752018-05-03 17:36:262687 entry->root_node()->frame_entry->set_source_site_instance(
2688 static_cast<SiteInstanceImpl*>(source_site_instance));
2689 entry->root_node()->frame_entry->set_method(method);
2690 }
clamy987a3752018-05-03 17:36:262691
Camille Lamy5193caa2018-10-12 11:59:422692 bool override_user_agent = false;
clamy987a3752018-05-03 17:36:262693 if (GetLastCommittedEntry() &&
2694 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
2695 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422696 override_user_agent = true;
clamy987a3752018-05-03 17:36:262697 }
2698 // TODO(creis): Set user gesture and intent received timestamp on Android.
2699
2700 // We may not have successfully added the FrameNavigationEntry to |entry|
2701 // above (per https://crbug.com/608402), in which case we create it from
2702 // scratch. This works because we do not depend on |frame_entry| being inside
2703 // |entry| during NavigateToEntry. This will go away when we shortcut this
2704 // further in https://crbug.com/536906.
2705 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2706 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452707 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082708 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582709 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072710 absl::nullopt /* origin */, referrer, initiator_origin,
Rakina Zata Amni3a1c0ec2021-04-15 03:35:122711 std::vector<GURL>(), blink::PageState(), method, -1,
2712 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482713 nullptr /* subresource_web_bundle_navigation_info */,
Nate Chapin63db0d12022-01-20 22:03:302714 nullptr /* policy_container_policies */,
2715 false /* protect_url_in_app_history */);
clamy987a3752018-05-03 17:36:262716 }
2717
Camille Lamy5193caa2018-10-12 11:59:422718 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022719 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452720 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292721 params.initiator_origin = initiator_origin;
Camille Lamy5193caa2018-10-12 11:59:422722 params.source_site_instance = source_site_instance;
2723 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2724 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032725 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422726 params.referrer = referrer;
2727 /* params.redirect_chain: skip */
2728 params.extra_headers = extra_headers;
2729 params.is_renderer_initiated = is_renderer_initiated;
2730 params.override_user_agent = UA_OVERRIDE_INHERIT;
2731 /* params.base_url_for_data_url: skip */
2732 /* params.virtual_url_for_data_url: skip */
2733 /* params.data_url_as_string: skip */
2734 params.post_data = post_body;
2735 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582736 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422737 /* params.frame_name: skip */
2738 // TODO(clamy): See if user gesture should be propagated to this function.
2739 params.has_user_gesture = false;
2740 params.should_clear_history_list = false;
2741 params.started_from_context_menu = false;
2742 /* params.navigation_ui_data: skip */
2743 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222744 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542745 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212746 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412747 params.download_policy = std::move(download_policy);
Camille Lamy5193caa2018-10-12 11:59:422748
2749 std::unique_ptr<NavigationRequest> request =
2750 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032751 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142752 false /* has_user_gesture */, std::move(source_location),
Antonio Sartori6984c742021-08-26 08:03:412753 ReloadType::NONE, entry.get(), frame_entry.get());
clamyea99ea12018-05-28 13:54:232754
2755 if (!request)
2756 return;
2757
Arthur Hemery948742762019-09-18 10:06:242758 // At this stage we are proceeding with this navigation. If this was renderer
2759 // initiated with user gesture, we need to make sure we clear up potential
2760 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2761 DiscardNonCommittedEntries();
2762
Lukasz Anforowicz9ee83c272020-12-01 20:14:052763 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262764}
2765
[email protected]d1198fd2012-08-13 22:50:192766void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252767 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212768 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192769 if (!session_storage_namespace)
2770 return;
2771
2772 // We can't overwrite an existing SessionStorage without violating spec.
2773 // Attempts to do so may give a tab access to another tab's session storage
2774 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152775 bool successful_insert =
2776 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252777 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052778 static_cast<SessionStorageNamespaceImpl*>(
2779 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302780 .second;
2781 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192782}
2783
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572784bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amni2322f4f82022-01-24 13:24:242785 return IsInitialNavigation() &&
2786 (!GetLastCommittedEntry() ||
2787 GetLastCommittedEntry()->IsInitialEntry()) &&
Carlos Caballeroede6f8c2021-01-28 11:01:502788 !frame_tree_.has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462789}
2790
Aran Gilman37d11632019-10-08 23:07:152791SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252792 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302793 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252794 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032795 DOMStorageContextWrapper* context_wrapper =
2796 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2797
2798 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252799 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032800 if (it != session_storage_namespace_map_.end()) {
2801 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152802 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2803 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472804
michaelnbacbcbd2016-02-09 00:32:032805 return it->second.get();
2806 }
2807
2808 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102809 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2810 SessionStorageNamespaceImpl::Create(context_wrapper);
2811 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2812 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252813 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102814 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302815
Daniel Murphy31bbb8b12018-02-07 21:44:102816 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302817}
2818
2819SessionStorageNamespace*
2820NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252821 return GetSessionStorageNamespace(
2822 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302823}
2824
2825const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572826NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302827 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552828}
[email protected]d202a7c2012-01-04 07:53:472829
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572830bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562831 return needs_reload_;
2832}
[email protected]a26023822011-12-29 00:23:552833
[email protected]46bb5e9c2013-10-03 22:16:472834void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412835 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2836}
2837
2838void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472839 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412840 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542841
2842 if (last_committed_entry_index_ != -1) {
2843 entries_[last_committed_entry_index_]->SetTransitionType(
2844 ui::PAGE_TRANSITION_RELOAD);
2845 }
[email protected]46bb5e9c2013-10-03 22:16:472846}
2847
[email protected]d202a7c2012-01-04 07:53:472848void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572849 DCHECK_LT(index, GetEntryCount());
2850 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312851 DiscardNonCommittedEntries();
2852
2853 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122854 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312855 last_committed_entry_index_--;
2856}
2857
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572858NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272859 // If there is no pending_entry_, there should be no pending_entry_index_.
2860 DCHECK(pending_entry_ || pending_entry_index_ == -1);
2861
2862 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:362863 // at that index. An exception is while a reload of a post commit error page
2864 // is ongoing; in that case pending entry will point to the entry replaced
2865 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:272866 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:362867 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
2868 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:272869
[email protected]022af742011-12-28 18:37:252870 return pending_entry_;
2871}
2872
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572873int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:272874 // The pending entry index must always be less than the number of entries.
Rakina Zata Amni2322f4f82022-01-24 13:24:242875 // If there are no entries, it must be exactly -1.
arthursonzogni5c4c202d2017-04-25 23:41:272876 DCHECK_LT(pending_entry_index_, GetEntryCount());
Rakina Zata Amni2322f4f82022-01-24 13:24:242877 DCHECK(GetEntryCount() != 0 || pending_entry_index_ == -1);
[email protected]a26023822011-12-29 00:23:552878 return pending_entry_index_;
2879}
2880
avi25764702015-06-23 15:43:372881void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:572882 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:362883 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:312884 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:002885 bool in_fenced_frame_tree,
2886 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:312887 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
2888 // set because:
2889 // 1) They don't influence the history of the outer page.
2890 // 2) They are always replace only navigation (there is always only one entry
2891 // in their history stack).
2892 // 3) Are not top level navigations and appear similar to iframes.
2893 // Navigations of the fenced frame might create a new NavigationEntry, which
2894 // will call this function. Non fenced frame navigations will never have
2895 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
2896 // InsertOrReplaceEntry.
2897 DCHECK_EQ(in_fenced_frame_tree,
2898 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
2899 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:202900
avi5cad4912015-06-19 05:25:442901 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
2902 // need to keep continuity with the pending entry, so copy the pending entry's
2903 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
2904 // then the renderer navigated on its own, independent of the pending entry,
2905 // so don't copy anything.
2906 if (pending_entry_ && pending_entry_index_ == -1)
2907 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:202908
Rakina Zata Amnia4e27222021-12-22 01:05:002909 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:202910
creisee17e932015-07-17 17:56:222911 // When replacing, don't prune the forward history.
Carlos IL42b416592019-10-07 23:10:362912 if ((replace || was_post_commit_error) && entries_.size() > 0) {
Mikel Astizba9cf2fd2017-12-17 10:38:102913 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572914 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:362915 // If the new entry is a post-commit error page, we store the current last
2916 // committed entry to the side so that we can put it back when navigating
2917 // away from the error.
2918 if (was_post_commit_error) {
2919 DCHECK(!entry_replaced_by_post_commit_error_);
2920 entry_replaced_by_post_commit_error_ =
2921 std::move(entries_[last_committed_entry_index_]);
2922 }
dcheng36b6aec92015-12-26 06:16:362923 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:222924 return;
2925 }
[email protected]765b35502008-08-21 00:51:202926
creis37979a62015-08-04 19:48:182927 // We shouldn't see replace == true when there's no committed entries.
2928 DCHECK(!replace);
2929
Michael Thiessen9b14d512019-09-23 21:19:472930 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:202931
Shivani Sharmad8c8d652019-02-13 17:27:572932 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:202933
dcheng36b6aec92015-12-26 06:16:362934 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:202935 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:292936}
2937
Shivani Sharmad8c8d652019-02-13 17:27:572938void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:162939 if (entries_.size() < max_entry_count())
2940 return;
2941
2942 DCHECK_EQ(max_entry_count(), entries_.size());
2943 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:572944 CHECK_EQ(pending_entry_index_, -1);
2945
2946 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:422947 // Retrieve the oldest skippable entry.
2948 for (; index < GetEntryCount(); index++) {
2949 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
2950 break;
Shivani Sharmad8c8d652019-02-13 17:27:572951 }
2952
2953 // If there is no skippable entry or if it is the last committed entry then
2954 // fall back to pruning the oldest entry. It is not safe to prune the last
2955 // committed entry.
2956 if (index == GetEntryCount() || index == last_committed_entry_index_)
2957 index = 0;
2958
2959 bool should_succeed = RemoveEntryAtIndex(index);
2960 DCHECK_EQ(true, should_succeed);
2961
2962 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:252963}
2964
clamy3cb9bea92018-07-10 12:42:022965void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:162966 ReloadType reload_type,
Nate Chapin45f620582021-09-30 17:45:432967 int sandboxed_source_frame_tree_node_id,
2968 bool is_browser_initiated) {
Alexander Timin3a92df72019-09-20 11:59:502969 TRACE_EVENT0("navigation",
2970 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:272971 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:022972 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:362973 if (pending_entry_index_ != -1) {
2974 // The pending entry may not be in entries_ if a post-commit error page is
2975 // showing.
2976 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
2977 pending_entry_ == entry_replaced_by_post_commit_error_.get());
2978 }
Gyuyoung Kim107c2a02021-04-13 01:49:302979 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:572980 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:012981 needs_reload_ = false;
Carlos Caballero40b0efd2021-01-26 11:55:002982 FrameTreeNode* root = frame_tree_.root();
Arthur Sonzogni620cec62018-12-13 13:08:572983 int nav_entry_id = pending_entry_->GetUniqueID();
2984
[email protected]83c2e232011-10-07 21:36:462985 // If we were navigating to a slow-to-commit page, and the user performs
2986 // a session history navigation to the last committed page, RenderViewHost
2987 // will force the throbber to start, but WebKit will essentially ignore the
2988 // navigation, and won't send a message to stop the throbber. To prevent this
2989 // from happening, we drop the navigation here and stop the slow-to-commit
2990 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:022991 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:082992 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:272993 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Takashi Toyoshimabf549472021-07-01 07:47:202994 frame_tree_.StopLoading();
[email protected]6a13a6c2011-12-20 21:47:122995
[email protected]83c2e232011-10-07 21:36:462996 DiscardNonCommittedEntries();
2997 return;
2998 }
2999
creisce0ef3572017-01-26 17:53:083000 // Compare FrameNavigationEntries to see which frames in the tree need to be
3001 // navigated.
clamy3cb9bea92018-07-10 12:42:023002 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3003 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Nate Chapin45f620582021-09-30 17:45:433004 FindFramesToNavigate(root, reload_type, is_browser_initiated,
3005 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303006
3007 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573008 // We were unable to match any frames to navigate. This can happen if a
3009 // history navigation targets a subframe that no longer exists
3010 // (https://crbug.com/705550). In this case, we need to update the current
3011 // history entry to the pending one but keep the main document loaded. We
3012 // also need to ensure that observers are informed about the updated
3013 // current history entry (e.g., for greying out back/forward buttons), and
3014 // that renderer processes update their history offsets. The easiest way
3015 // to do all that is to schedule a "redundant" same-document navigation in
3016 // the main frame.
3017 //
3018 // Note that we don't want to remove this history entry, as it might still
3019 // be valid later, since a frame that it's targeting may be recreated.
3020 //
3021 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3022 // need to repeat history navigations until finding the one that works.
3023 // Consider changing this behavior to keep looking for the first valid
3024 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023025 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423026 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573027 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573028 ReloadType::NONE /* reload_type */,
3029 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433030 false /* is_history_navigation_in_new_child */,
3031 is_browser_initiated);
clamy3cb9bea92018-07-10 12:42:023032 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573033 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023034 DiscardPendingEntry(false);
3035 return;
3036 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573037 same_document_loads.push_back(std::move(navigation_request));
3038
3039 // Sanity check that we never take this branch for any kinds of reloads,
3040 // as those should've queued a different-document load in the main frame.
3041 DCHECK(!is_forced_reload);
3042 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303043 }
3044
Dave Tapuska8bfd84c2019-03-26 20:47:163045 // If |sandboxed_source_frame_node_id| is valid, then track whether this
3046 // navigation affects any frame outside the frame's subtree.
3047 if (sandboxed_source_frame_tree_node_id !=
3048 FrameTreeNode::kFrameTreeNodeInvalidId) {
3049 bool navigates_inside_tree =
3050 DoesSandboxNavigationStayWithinSubtree(
3051 sandboxed_source_frame_tree_node_id, same_document_loads) &&
3052 DoesSandboxNavigationStayWithinSubtree(
3053 sandboxed_source_frame_tree_node_id, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503054 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163055 // the number of pages that trigger this.
3056 FrameTreeNode* sandbox_source_frame_tree_node =
3057 FrameTreeNode::GloballyFindByID(sandboxed_source_frame_tree_node_id);
3058 if (sandbox_source_frame_tree_node) {
3059 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3060 sandbox_source_frame_tree_node->current_frame_host(),
3061 navigates_inside_tree
3062 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3063 : blink::mojom::WebFeature::
3064 kSandboxBackForwardAffectsFramesOutsideSubtree);
3065 }
Dave Tapuska855c1e12019-08-23 20:45:523066
3067 // If the navigation occurred outside the tree discard it because
3068 // the sandboxed frame didn't have permission to navigate outside
3069 // its tree. If it is possible that the navigation is both inside and
3070 // outside the frame tree and we discard it entirely because we don't
3071 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143072 if (!navigates_inside_tree) {
Dave Tapuska855c1e12019-08-23 20:45:523073 DiscardPendingEntry(false);
3074 return;
3075 }
Dave Tapuska8bfd84c2019-03-26 20:47:163076 }
3077
Carlos Caballero539a421c2020-07-06 10:25:573078 // BackForwardCache:
3079 // Navigate immediately if the document is in the BackForwardCache.
3080 if (back_forward_cache_.GetEntry(nav_entry_id)) {
3081 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3082 DCHECK_EQ(reload_type, ReloadType::NONE);
3083 auto navigation_request = CreateNavigationRequestFromEntry(
3084 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3085 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433086 false /* is_history_navigation_in_new_child */, is_browser_initiated);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053087 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573088
3089 return;
3090 }
3091
3092 // History navigation might try to reuse a specific BrowsingInstance, already
3093 // used by a page in the cache. To avoid having two different main frames that
3094 // live in the same BrowsingInstance, evict the all pages with this
3095 // BrowsingInstance from the cache.
3096 //
3097 // For example, take the following scenario:
3098 //
3099 // A1 = Some page on a.com
3100 // A2 = Some other page on a.com
3101 // B3 = An uncacheable page on b.com
3102 //
3103 // Then the following navigations occur:
3104 // A1->A2->B3->A1
3105 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3106 // take its place) and A1 will be created in the same BrowsingInstance (and
3107 // SiteInstance), as A2.
3108 //
3109 // If we didn't do anything, both A1 and A2 would remain alive in the same
3110 // BrowsingInstance/SiteInstance, which is unsupported by
3111 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3112 // A2 from the cache.
3113 if (pending_entry_->site_instance()) {
3114 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3115 pending_entry_->site_instance());
3116 }
3117
clamy3cb9bea92018-07-10 12:42:023118 // This call does not support re-entrancy. See http://crbug.com/347742.
3119 CHECK(!in_navigate_to_pending_entry_);
3120 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303121
arthursonzogni66f711c2019-10-08 14:40:363122 // It is not possible to delete the pending NavigationEntry while navigating
3123 // to it. Grab a reference to delay potential deletion until the end of this
3124 // function.
3125 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3126
creis4e2ecb72015-06-20 00:46:303127 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023128 for (auto& item : same_document_loads) {
3129 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053130 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303131 }
clamy3cb9bea92018-07-10 12:42:023132 for (auto& item : different_document_loads) {
3133 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053134 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303135 }
clamy3cb9bea92018-07-10 12:42:023136
3137 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303138}
3139
Alex Moshchuk3a4e77a2020-05-29 21:32:573140NavigationControllerImpl::HistoryNavigationAction
3141NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303142 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573143 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423144 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583145 // Only active and prerendered documents are allowed to navigate in their
3146 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423147 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013148 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583149 // - If the document is in pending deletion, the browser already committed
3150 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3151 // - If the document is in back-forward cache, it's not allowed to navigate
3152 // as it should remain frozen. Ignore the request and evict the document
3153 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423154 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583155 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423156 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113157 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3158 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423159 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113160 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423161 }
arthursonzogni03f76152019-02-12 10:35:203162
Alex Moshchuk3a4e77a2020-05-29 21:32:573163 // If there's no last committed entry, there is no previous history entry to
3164 // compare against, so fall back to a different-document load. Note that we
3165 // should only reach this case for the root frame and not descend further
3166 // into subframes.
3167 if (!GetLastCommittedEntry()) {
3168 DCHECK(frame->IsMainFrame());
3169 return HistoryNavigationAction::kDifferentDocument;
3170 }
3171
3172 // Reloads should result in a different-document load. Note that reloads may
3173 // also happen via the |needs_reload_| mechanism where the reload_type is
3174 // NONE, so detect this by comparing whether we're going to the same
3175 // entry that we're currently on. Similarly to above, only main frames
3176 // should reach this. Note that subframes support reloads, but that's done
3177 // via a different path that doesn't involve FindFramesToNavigate (see
3178 // RenderFrameHost::Reload()).
3179 if (reload_type != ReloadType::NONE ||
3180 pending_entry_index_ == last_committed_entry_index_) {
3181 DCHECK(frame->IsMainFrame());
3182 return HistoryNavigationAction::kDifferentDocument;
3183 }
3184
Alex Moshchuk47d1a4bd2020-06-01 22:15:343185 // If there is no new FrameNavigationEntry for the frame, ignore the
3186 // load. For example, this may happen when going back to an entry before a
3187 // frame was created. Suppose we commit a same-document navigation that also
3188 // results in adding a new subframe somewhere in the tree. If we go back,
3189 // the new subframe will be missing a FrameNavigationEntry in the previous
3190 // NavigationEntry, but we shouldn't delete or change what's loaded in
3191 // it.
3192 //
Alex Moshchuke65c39272020-06-03 17:55:373193 // Note that in this case, there is no need to keep looking for navigations
3194 // in subframes, which would be missing FrameNavigationEntries as well.
3195 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343196 // It's important to check this before checking |old_item| below, since both
3197 // might be null, and in that case we still shouldn't change what's loaded in
3198 // this frame. Note that scheduling any loads assumes that |new_item| is
3199 // non-null. See https://crbug.com/1088354.
3200 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3201 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373202 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343203
Alex Moshchuk3a4e77a2020-05-29 21:32:573204 // If there is no old FrameNavigationEntry, schedule a different-document
3205 // load.
3206 //
creis225a7432016-06-03 22:56:273207 // TODO(creis): Store the last committed FrameNavigationEntry to use here,
3208 // rather than assuming the NavigationEntry has up to date info on subframes.
creis4e2ecb72015-06-20 00:46:303209 FrameNavigationEntry* old_item =
3210 GetLastCommittedEntry()->GetFrameEntry(frame);
Alex Moshchuk3a4e77a2020-05-29 21:32:573211 if (!old_item)
3212 return HistoryNavigationAction::kDifferentDocument;
3213
Alex Moshchuk3a4e77a2020-05-29 21:32:573214 // If the new item is not in the same SiteInstance, schedule a
3215 // different-document load. Newly restored items may not have a SiteInstance
3216 // yet, in which case it will be assigned on first commit.
3217 if (new_item->site_instance() &&
3218 new_item->site_instance() != old_item->site_instance())
3219 return HistoryNavigationAction::kDifferentDocument;
3220
3221 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313222 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3223 // that we do this even if the history navigation would not be modifying this
3224 // frame were it live.
3225 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573226 return HistoryNavigationAction::kDifferentDocument;
3227
3228 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313229 // Starting a navigation after a crash early-promotes the speculative
3230 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3231 // committed yet, so we can not possibly perform a same-document history
3232 // navigation. The frame would need to be reloaded with a cross-document
3233 // navigation.
3234 if (!frame->current_frame_host()->has_committed_any_navigation())
3235 return HistoryNavigationAction::kDifferentDocument;
3236
creis54131692016-08-12 18:32:253237 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493238 // sequence number but different item sequence number.
3239 if (new_item->document_sequence_number() ==
3240 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573241 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493242 }
avib48cb312016-05-05 21:35:003243
Alex Moshchuk3a4e77a2020-05-29 21:32:573244 // Otherwise, if both item and document sequence numbers differ, this
3245 // should be a different document load.
3246 return HistoryNavigationAction::kDifferentDocument;
3247 }
3248
3249 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373250 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573251 DCHECK_EQ(new_item->document_sequence_number(),
3252 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373253 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573254}
3255
3256void NavigationControllerImpl::FindFramesToNavigate(
3257 FrameTreeNode* frame,
3258 ReloadType reload_type,
Nate Chapin45f620582021-09-30 17:45:433259 bool is_browser_initiated,
Alex Moshchuk3a4e77a2020-05-29 21:32:573260 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3261 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3262 DCHECK(pending_entry_);
3263 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3264
3265 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3266
3267 if (action == HistoryNavigationAction::kSameDocument) {
3268 std::unique_ptr<NavigationRequest> navigation_request =
3269 CreateNavigationRequestFromEntry(
3270 frame, pending_entry_, new_item, reload_type,
3271 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433272 false /* is_history_navigation_in_new_child */,
3273 is_browser_initiated);
Alex Moshchuk3a4e77a2020-05-29 21:32:573274 if (navigation_request) {
3275 // Only add the request if was properly created. It's possible for the
3276 // creation to fail in certain cases, e.g. when the URL is invalid.
3277 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303278 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573279 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473280 std::unique_ptr<NavigationRequest> navigation_request =
3281 CreateNavigationRequestFromEntry(
3282 frame, pending_entry_, new_item, reload_type,
3283 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433284 false /* is_history_navigation_in_new_child */,
3285 is_browser_initiated);
Lei Zhang96031532019-10-10 19:05:473286 if (navigation_request) {
3287 // Only add the request if was properly created. It's possible for the
3288 // creation to fail in certain cases, e.g. when the URL is invalid.
3289 different_document_loads->push_back(std::move(navigation_request));
3290 }
3291 // For a different document, the subframes will be destroyed, so there's
3292 // no need to consider them.
3293 return;
Alex Moshchuke65c39272020-06-03 17:55:373294 } else if (action == HistoryNavigationAction::kStopLooking) {
3295 return;
creis4e2ecb72015-06-20 00:46:303296 }
3297
3298 for (size_t i = 0; i < frame->child_count(); i++) {
Nate Chapin45f620582021-09-30 17:45:433299 FindFramesToNavigate(frame->child_at(i), reload_type, is_browser_initiated,
3300 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303301 }
3302}
3303
Harkiran Bolariaba823e42021-05-21 18:30:363304base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243305 const LoadURLParams& params) {
3306 // Find the appropriate FrameTreeNode.
3307 FrameTreeNode* node = nullptr;
3308 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3309 !params.frame_name.empty()) {
3310 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Carlos Caballero40b0efd2021-01-26 11:55:003311 ? frame_tree_.FindByID(params.frame_tree_node_id)
3312 : frame_tree_.FindByName(params.frame_name);
Hayato Ito7a80db42021-07-05 06:18:543313 DCHECK(!node || node->frame_tree() == &frame_tree_);
clamy21718cc22018-06-13 13:34:243314 }
3315
3316 // If no FrameTreeNode was specified, navigate the main frame.
3317 if (!node)
Carlos Caballero40b0efd2021-01-26 11:55:003318 node = frame_tree_.root();
clamy21718cc22018-06-13 13:34:243319
Camille Lamy5193caa2018-10-12 11:59:423320 // Compute overrides to the LoadURLParams for |override_user_agent|,
3321 // |should_replace_current_entry| and |has_user_gesture| that will be used
3322 // both in the creation of the NavigationEntry and the NavigationRequest.
3323 // Ideally, the LoadURLParams themselves would be updated, but since they are
3324 // passed as a const reference, this is not possible.
3325 // TODO(clamy): When we only create a NavigationRequest, move this to
3326 // CreateNavigationRequestFromLoadURLParams.
3327 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3328 GetLastCommittedEntry());
3329
3330 // Don't allow an entry replacement if there is no entry to replace.
3331 // http://crbug.com/457149
Hayato Ito7a80db42021-07-05 06:18:543332 //
3333 // If there is an entry, an entry replacement must happen if the current
3334 // browsing context should maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333335 bool should_replace_current_entry =
3336 (params.should_replace_current_entry ||
3337 ShouldMaintainTrivialSessionHistory(node)) &&
3338 entries_.size();
Camille Lamy5193caa2018-10-12 11:59:423339
clamy21718cc22018-06-13 13:34:243340 // Javascript URLs should not create NavigationEntries. All other navigations
3341 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243342 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373343 std::unique_ptr<NavigationEntryImpl> entry =
3344 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3345 should_replace_current_entry,
3346 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243347 DiscardPendingEntry(false);
3348 SetPendingEntry(std::move(entry));
3349 }
3350
3351 // Renderer-debug URLs are sent to the renderer process immediately for
3352 // processing and don't need to create a NavigationRequest.
3353 // Note: this includes navigations to JavaScript URLs, which are considered
3354 // renderer-debug URLs.
3355 // Note: we intentionally leave the pending entry in place for renderer debug
3356 // URLs, unlike the cases below where we clear it if the navigation doesn't
3357 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303358 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483359 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3360 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153361 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Oleg Davydov2cc0167b2019-02-05 14:32:483362 params.url, browser_context_)) {
3363 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363364 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483365 }
3366
clamy21718cc22018-06-13 13:34:243367 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363368 return nullptr;
clamy21718cc22018-06-13 13:34:243369 }
3370
Antonio Sartori78a749f2020-11-30 12:03:393371 DCHECK(pending_entry_);
3372
clamy21718cc22018-06-13 13:34:243373 // Convert navigations to the current URL to a reload.
3374 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3375 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3376 // DevTools sometimes issues navigations to main frames that they do not
3377 // expect to see treated as reload, and it only works because they pass a
3378 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3379 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543380 ReloadType reload_type = params.reload_type;
3381 if (reload_type == ReloadType::NONE &&
3382 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043383 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243384 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243385 params.load_type ==
3386 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543387 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243388 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473389 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393390
3391 // If this is a reload of an existing FrameNavigationEntry and we had a
3392 // policy container for it, then we should copy it into the pending entry,
3393 // so that it is copied to the navigation request in
3394 // CreateNavigationRequestFromLoadParams later.
3395 if (GetLastCommittedEntry()) {
3396 FrameNavigationEntry* previous_frame_entry =
3397 GetLastCommittedEntry()->GetFrameEntry(node);
Titouan Rigoudy6ec70402021-02-02 15:42:193398 if (previous_frame_entry &&
3399 previous_frame_entry->policy_container_policies()) {
3400 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163401 previous_frame_entry->policy_container_policies()->Clone());
Antonio Sartori78a749f2020-11-30 12:03:393402 }
3403 }
3404 }
3405
3406 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173407 // document, then we should copy the document polices from RenderFrameHost's
3408 // PolicyContainerHost. The NavigationRequest will create a new
3409 // PolicyContainerHost with the document policies from the |pending_entry_|,
3410 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3411 // the navigation. This way, we ensure that we keep enforcing the right
3412 // policies on the initial empty document after the reload.
Rakina Zata Amni2322f4f82022-01-24 13:24:243413 if ((!GetLastCommittedEntry() || GetLastCommittedEntry()->IsInitialEntry()) &&
3414 params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393415 if (node->current_frame_host() &&
3416 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193417 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163418 node->current_frame_host()
3419 ->policy_container_host()
3420 ->policies()
3421 .Clone());
Antonio Sartori78a749f2020-11-30 12:03:393422 }
clamy21718cc22018-06-13 13:34:243423 }
3424
3425 // navigation_ui_data should only be present for main frame navigations.
3426 DCHECK(node->IsMainFrame() || !params.navigation_ui_data);
3427
Camille Lamy5193caa2018-10-12 11:59:423428 std::unique_ptr<NavigationRequest> request =
3429 CreateNavigationRequestFromLoadParams(
3430 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143431 params.has_user_gesture, network::mojom::SourceLocation::New(),
Antonio Sartori6984c742021-08-26 08:03:413432 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node));
clamy21718cc22018-06-13 13:34:243433
3434 // If the navigation couldn't start, return immediately and discard the
3435 // pending NavigationEntry.
3436 if (!request) {
3437 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363438 return nullptr;
clamy21718cc22018-06-13 13:34:243439 }
3440
Camille Lamy5193caa2018-10-12 11:59:423441#if DCHECK_IS_ON()
3442 // Safety check that NavigationRequest and NavigationEntry match.
3443 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3444#endif
3445
clamy21718cc22018-06-13 13:34:243446 // This call does not support re-entrancy. See http://crbug.com/347742.
3447 CHECK(!in_navigate_to_pending_entry_);
3448 in_navigate_to_pending_entry_ = true;
3449
arthursonzogni66f711c2019-10-08 14:40:363450 // It is not possible to delete the pending NavigationEntry while navigating
3451 // to it. Grab a reference to delay potential deletion until the end of this
3452 // function.
3453 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3454
Harkiran Bolariaba823e42021-05-21 18:30:363455 base::WeakPtr<NavigationHandle> created_navigation_handle(
3456 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053457 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243458
3459 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363460 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243461}
3462
clamyea99ea12018-05-28 13:54:233463void NavigationControllerImpl::HandleRendererDebugURL(
3464 FrameTreeNode* frame_tree_node,
3465 const GURL& url) {
3466 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243467 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3468 // the renderer process is not live, unless it is the initial navigation
3469 // of the tab.
clamyea99ea12018-05-28 13:54:233470 if (!IsInitialNavigation()) {
3471 DiscardNonCommittedEntries();
3472 return;
3473 }
Fergal Dalyecd3b0202020-06-25 01:57:373474 // The current frame is always a main frame. If IsInitialNavigation() is
3475 // true then there have been no navigations and any frames of this tab must
3476 // be in the same renderer process. If that has crashed then the only frame
3477 // that can be revived is the main frame.
3478 frame_tree_node->render_manager()
3479 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233480 }
3481 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3482}
3483
clamy21718cc22018-06-13 13:34:243484std::unique_ptr<NavigationEntryImpl>
3485NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3486 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423487 const LoadURLParams& params,
3488 bool override_user_agent,
3489 bool should_replace_current_entry,
3490 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393491 // Browser initiated navigations might not have a blob_url_loader_factory set
3492 // in params even if the navigation is to a blob URL. If that happens, lookup
3493 // the correct url loader factory to use here.
3494 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483495 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473496 // Resolve the blob URL in the storage partition associated with the target
3497 // frame. This is the storage partition the URL will be loaded in, and only
3498 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393499 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473500 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393501 }
3502
clamy21718cc22018-06-13 13:34:243503 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443504 // extra_headers in params are \n separated; navigation entries want \r\n.
3505 std::string extra_headers_crlf;
3506 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243507
3508 // For subframes, create a pending entry with a corresponding frame entry.
3509 if (!node->IsMainFrame()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:243510 if (GetLastCommittedEntry()) {
3511 entry = GetLastCommittedEntry()->Clone();
3512 } else {
3513 // If there's no last committed entry, create an entry for about:blank
3514 // with a subframe entry for our destination.
3515 // TODO(creis): Ensure this case can't exist in https://crbug.com/524208.
3516 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
3517 GURL(url::kAboutBlankURL), params.referrer, params.initiator_origin,
3518 params.source_site_instance.get(), params.transition_type,
3519 params.is_renderer_initiated, extra_headers_crlf, browser_context_,
3520 blob_url_loader_factory));
3521 }
clamy21718cc22018-06-13 13:34:243522 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083523 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243524 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073525 params.url, absl::nullopt, params.referrer, params.initiator_origin,
Miyoung Shin5d77f72072020-10-09 15:14:203526 params.redirect_chain, blink::PageState(), "GET", -1,
Antonio Sartori78a749f2020-11-30 12:03:393527 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:483528 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori78a749f2020-11-30 12:03:393529 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163530 // a conversion of a new navigation into a reload, we will set the right
3531 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193532 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243533 } else {
3534 // Otherwise, create a pending entry for the main frame.
clamy21718cc22018-06-13 13:34:243535 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063536 params.url, params.referrer, params.initiator_origin,
Lukasz Anforowicz641234d52019-11-07 21:07:103537 params.source_site_instance.get(), params.transition_type,
3538 params.is_renderer_initiated, extra_headers_crlf, browser_context_,
Hayato Ito303654c2021-06-30 09:07:543539 blob_url_loader_factory));
clamy21718cc22018-06-13 13:34:243540 entry->set_source_site_instance(
3541 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3542 entry->SetRedirectChain(params.redirect_chain);
3543 }
3544
3545 // Set the FTN ID (only used in non-site-per-process, for tests).
3546 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243547 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423548 entry->SetIsOverridingUserAgent(override_user_agent);
3549 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543550 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243551
clamy21718cc22018-06-13 13:34:243552 switch (params.load_type) {
3553 case LOAD_TYPE_DEFAULT:
3554 break;
3555 case LOAD_TYPE_HTTP_POST:
3556 entry->SetHasPostData(true);
3557 entry->SetPostData(params.post_data);
3558 break;
3559 case LOAD_TYPE_DATA:
3560 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3561 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283562#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243563 entry->SetDataURLAsString(params.data_url_as_string);
3564#endif
3565 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3566 break;
clamy21718cc22018-06-13 13:34:243567 }
3568
3569 // TODO(clamy): NavigationEntry is meant for information that will be kept
3570 // after the navigation ended and therefore is not appropriate for
3571 // started_from_context_menu. Move started_from_context_menu to
3572 // NavigationUIData.
3573 entry->set_started_from_context_menu(params.started_from_context_menu);
3574
3575 return entry;
3576}
3577
clamyea99ea12018-05-28 13:54:233578std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423579NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3580 FrameTreeNode* node,
3581 const LoadURLParams& params,
3582 bool override_user_agent,
3583 bool should_replace_current_entry,
3584 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143585 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423586 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573587 NavigationEntryImpl* entry,
Scott Violetcf6ea7e2021-06-09 21:09:213588 FrameNavigationEntry* frame_entry) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573589 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283590 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533591 // All renderer-initiated navigations must have an initiator_origin.
3592 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513593
Camille Lamy5193caa2018-10-12 11:59:423594 GURL url_to_load;
3595 GURL virtual_url;
Anton Bikineevf62d1bf2021-05-15 17:56:073596 absl::optional<url::Origin> origin_to_commit =
3597 frame_entry ? frame_entry->committed_origin() : absl::nullopt;
Nasko Oskov03912102019-01-11 00:21:323598
Camille Lamy2baa8022018-10-19 16:43:173599 // For main frames, rewrite the URL if necessary and compute the virtual URL
3600 // that should be shown in the address bar.
3601 if (node->IsMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423602 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173603 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423604 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423605
Camille Lamy2baa8022018-10-19 16:43:173606 // For DATA loads, override the virtual URL.
3607 if (params.load_type == LOAD_TYPE_DATA)
3608 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423609
Camille Lamy2baa8022018-10-19 16:43:173610 if (virtual_url.is_empty())
3611 virtual_url = url_to_load;
3612
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573613 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283614
Aran Gilman249eb122019-12-02 23:32:463615 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3616 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3617 // return different results, leading to a different URL in the
3618 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3619 // pending NavigationEntry, as we'll only make one call to
3620 // RewriteUrlForNavigation.
3621 VLOG_IF(1, (url_to_load != frame_entry->url()))
3622 << "NavigationRequest and FrameEntry have different URLs: "
3623 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283624
Camille Lamy2baa8022018-10-19 16:43:173625 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423626 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173627 // NavigationRequest.
3628 } else {
3629 url_to_load = params.url;
3630 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243631 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173632 }
Camille Lamy5193caa2018-10-12 11:59:423633
Ehsan Karamad44fc72112019-02-26 18:15:473634 if (node->render_manager()->is_attaching_inner_delegate()) {
3635 // Avoid starting any new navigations since this node is now preparing for
3636 // attaching an inner delegate.
3637 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203638 }
Camille Lamy5193caa2018-10-12 11:59:423639
Camille Lamy5193caa2018-10-12 11:59:423640 if (!IsValidURLForNavigation(node->IsMainFrame(), virtual_url, url_to_load))
3641 return nullptr;
3642
Kunihiko Sakamoto346a74e2021-03-10 08:57:483643 if (!DoesURLMatchOriginForNavigation(
3644 url_to_load, origin_to_commit,
Wang Hui14cac7a2022-01-28 06:07:473645 frame_entry->subresource_web_bundle_navigation_info(), entry,
3646 node->IsMainFrame())) {
Nasko Oskov03912102019-01-11 00:21:323647 DCHECK(false) << " url:" << url_to_load
3648 << " origin:" << origin_to_commit.value();
3649 return nullptr;
3650 }
3651
Camille Lamy5193caa2018-10-12 11:59:423652 // This will be used to set the Navigation Timing API navigationStart
3653 // parameter for browser navigations in new tabs (intents, tabs opened through
3654 // "Open link in new tab"). If the navigation must wait on the current
3655 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3656 // will be updated when the BeforeUnload ack is received.
3657 base::TimeTicks navigation_start = base::TimeTicks::Now();
3658
danakjd83d706d2020-11-25 22:11:123659 // Look for a pending commit that is to another document in this
3660 // FrameTreeNode. If one exists, then the last committed URL will not be the
3661 // current URL by the time this navigation commits.
3662 bool has_pending_cross_document_commit =
3663 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213664 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123665
Minggang Wangb9f3fa92021-07-01 15:30:313666 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493667 /*old_url=*/node->current_url(),
3668 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3669 has_pending_cross_document_commit, is_currently_error_page,
3670 /*is_same_document_history_load=*/false);
Camille Lamy5193caa2018-10-12 11:59:423671
3672 // Create the NavigationParams based on |params|.
3673
Hiroki Nakagawa4ed61282021-06-18 05:37:233674 bool is_view_source_mode = entry->IsViewSourceMode();
3675 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293676
Antonio Sartori6984c742021-08-26 08:03:413677 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Hiroki Nakagawa4ed61282021-06-18 05:37:233678 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293679 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253680 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293681
Minggang Wangb9f3fa92021-07-01 15:30:313682 blink::mojom::CommonNavigationParamsPtr common_params =
3683 blink::mojom::CommonNavigationParams::New(
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513684 url_to_load, params.initiator_origin,
3685 blink::mojom::Referrer::New(params.referrer.url,
3686 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213687 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513688 should_replace_current_entry, params.base_url_for_data_url,
Tarun Bansalbcd62c82022-01-18 17:27:383689 navigation_start,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513690 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143691 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413692 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273693 false /* has_text_fragment_token */,
3694 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3695 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513696 false /* is_history_navigation_in_new_child_frame */,
Nan Lind91c8152021-10-21 16:22:373697 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423698
Minggang Wangb9f3fa92021-07-01 15:30:313699 blink::mojom::CommitNavigationParamsPtr commit_params =
3700 blink::mojom::CommitNavigationParams::New(
Antonio Sartori3e8de6d2021-07-26 10:28:413701 frame_entry->committed_origin(),
3702 // The correct storage key will be computed before committing the
3703 // navigation.
3704 blink::StorageKey(), network::mojom::WebSandboxFlags(),
arthursonzognid5a8d0b2021-03-11 17:36:433705 override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323706 std::vector<network::mojom::URLResponseHeadPtr>(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143707 std::vector<net::RedirectInfo>(),
3708 std::string() /* post_content_type */, common_params->url,
3709 common_params->method, params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313710 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143711 entry->GetSubframeUniqueNames(node), true /* intended_as_new_entry */,
3712 -1 /* pending_history_list_offset */,
3713 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3714 params.should_clear_history_list ? 0 : GetEntryCount(),
3715 false /* was_discarded */, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313716 params.should_clear_history_list,
3717 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223718 blink::mojom::WasActivatedOption::kUnknown,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143719 base::UnguessableToken::Create() /* navigation_token */,
Minggang Wang7ee0c742021-06-16 16:16:513720 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283721#if BUILDFLAG(IS_ANDROID)
Lucas Furukawa Gadania9c45682019-07-31 22:05:143722 std::string(), /* data_url_as_string */
3723#endif
arthursonzogni14379782020-05-15 09:09:273724 !params.is_renderer_initiated, /* is_browser_initiated */
Tsuyoshi Horoe86d7702019-11-29 01:52:473725 GURL() /* web_bundle_physical_url */,
Charlie Hu5ffc0152019-12-06 15:59:533726 GURL() /* base_url_override_for_web_bundle */,
Yue Ru Sun128804932020-09-30 22:19:173727 ukm::kInvalidSourceId /* document_ukm_source_id */,
Jiewei Qian0406fc02020-03-09 06:02:073728 node->pending_frame_policy(),
Domenic Denicola4778c35392020-06-25 21:25:163729 std::vector<std::string>() /* force_enabled_origin_trials */,
Domenic Denicola55701ee2021-01-14 00:18:333730 false /* origin_agent_cluster */,
Daniel Vogelheim243df9f2022-02-22 10:32:033731 true /* origin_agent_cluster_left_as_default */,
Maks Orlovichc66745a2020-06-30 17:40:023732 std::vector<
Shuran Huanga055ce72020-07-23 14:13:213733 network::mojom::WebClientHintsType>() /* enabled_client_hints */,
Nate Chapind1fe3612021-04-16 20:45:573734 false /* is_cross_browsing_instance */, nullptr /* old_page_info */,
3735 -1 /* http_response_code */,
Nate Chapin4e657a472022-02-06 03:38:373736 blink::mojom::AppHistoryEntryArrays::New(),
Matt Menke4e209082021-11-09 04:59:313737 std::vector<GURL>() /* early_hints_preloaded_resources */,
Clark DuVall8ee487a22021-11-10 02:25:583738 absl::nullopt /* ad_auction_components */,
3739 // This timestamp will be populated when the commit IPC is sent.
W. James MacLean81b8d01f2022-01-25 20:50:593740 base::TimeTicks() /* commit_sent */, false /* anonymous */,
3741 std::string() /* srcdoc_value */);
Xiaohan Wang7f8052e02022-01-14 18:44:283742#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423743 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143744 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423745 }
3746#endif
3747
Lucas Furukawa Gadania9c45682019-07-31 22:05:143748 commit_params->was_activated = params.was_activated;
Camille Lamy5193caa2018-10-12 11:59:423749
3750 // A form submission may happen here if the navigation is a renderer-initiated
3751 // form submission that took the OpenURL path.
3752 scoped_refptr<network::ResourceRequestBody> request_body = params.post_data;
3753
3754 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3755 std::string extra_headers_crlf;
3756 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:093757
3758 auto navigation_request = NavigationRequest::CreateBrowserInitiated(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143759 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:083760 !params.is_renderer_initiated, params.was_opener_suppressed,
Antonio Sartori9a82f6f32020-12-14 09:22:453761 params.initiator_frame_token.has_value()
3762 ? &(params.initiator_frame_token.value())
3763 : nullptr,
3764 params.initiator_process_id, extra_headers_crlf, frame_entry, entry,
3765 request_body,
John Delaney50425f82020-04-07 16:26:213766 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Daniel Hosseinianf0fbfb42021-09-08 02:20:473767 params.impression, params.is_pdf);
Yao Xiaodc5ed102019-06-04 19:19:093768 navigation_request->set_from_download_cross_origin_redirect(
3769 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:553770 navigation_request->set_force_new_browsing_instance(
3771 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:093772 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:423773}
3774
3775std::unique_ptr<NavigationRequest>
3776NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:233777 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573778 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:233779 FrameNavigationEntry* frame_entry,
3780 ReloadType reload_type,
3781 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:433782 bool is_history_navigation_in_new_child_frame,
3783 bool is_browser_initiated) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:343784 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:233785 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:433786 // We should never navigate to an existing initial NavigationEntry that is the
3787 // initial NavigationEntry for the initial empty document that hasn't been
3788 // overridden by the synchronous about:blank commit, to preserve previous
3789 // behavior where trying to reload when the main frame is on the initial empty
3790 // document won't result in a navigation.
3791 // See also https://crbug.com/1277414.
3792 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Anton Bikineevf62d1bf2021-05-15 17:56:073793 absl::optional<url::Origin> origin_to_commit =
Nasko Oskov03912102019-01-11 00:21:323794 frame_entry->committed_origin();
3795
clamyea99ea12018-05-28 13:54:233796 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:013797 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573798 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:233799 // We may have been redirected when navigating to the current URL.
3800 // Use the URL the user originally intended to visit as signaled by the
3801 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:013802 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573803 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:233804 dest_referrer = Referrer();
Nasko Oskov03912102019-01-11 00:21:323805 origin_to_commit.reset();
clamyea99ea12018-05-28 13:54:233806 }
3807
Ehsan Karamad44fc72112019-02-26 18:15:473808 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
3809 // Avoid starting any new navigations since this node is now preparing for
3810 // attaching an inner delegate.
3811 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203812 }
3813
Camille Lamy5193caa2018-10-12 11:59:423814 if (!IsValidURLForNavigation(frame_tree_node->IsMainFrame(),
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573815 entry->GetVirtualURL(), dest_url)) {
clamyea99ea12018-05-28 13:54:233816 return nullptr;
3817 }
3818
Kunihiko Sakamoto346a74e2021-03-10 08:57:483819 if (!DoesURLMatchOriginForNavigation(
3820 dest_url, origin_to_commit,
Wang Hui14cac7a2022-01-28 06:07:473821 frame_entry->subresource_web_bundle_navigation_info(), entry,
3822 frame_tree_node->IsMainFrame())) {
Kunihiko Sakamoto346a74e2021-03-10 08:57:483823 DCHECK(false) << " url:" << dest_url
Wang Hui14cac7a2022-01-28 06:07:473824 << " base_url_for_data_url: " << entry->GetBaseURLForDataURL()
Kunihiko Sakamoto346a74e2021-03-10 08:57:483825 << " origin:" << origin_to_commit.value();
Nasko Oskov03912102019-01-11 00:21:323826 return nullptr;
3827 }
3828
clamyea99ea12018-05-28 13:54:233829 // This will be used to set the Navigation Timing API navigationStart
3830 // parameter for browser navigations in new tabs (intents, tabs opened through
3831 // "Open link in new tab"). If the navigation must wait on the current
3832 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3833 // will be updated when the BeforeUnload ack is received.
3834 base::TimeTicks navigation_start = base::TimeTicks::Now();
clamyea99ea12018-05-28 13:54:233835
danakjd83d706d2020-11-25 22:11:123836 // Look for a pending commit that is to another document in this
3837 // FrameTreeNode. If one exists, then the last committed URL will not be the
3838 // current URL by the time this navigation commits.
3839 bool has_pending_cross_document_commit =
3840 frame_tree_node->render_manager()
3841 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:493842 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:213843 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123844
Minggang Wangb9f3fa92021-07-01 15:30:313845 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:123846 /*old_url=*/frame_tree_node->current_url(),
3847 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:493848 has_pending_cross_document_commit, is_currently_error_page,
3849 is_same_document_history_load);
Camille Lamy5193caa2018-10-12 11:59:423850
3851 // A form submission may happen here if the navigation is a
3852 // back/forward/reload navigation that does a form resubmission.
3853 scoped_refptr<network::ResourceRequestBody> request_body;
3854 std::string post_content_type;
3855 if (frame_entry->method() == "POST") {
3856 request_body = frame_entry->GetPostData(&post_content_type);
3857 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:303858 post_content_type = std::string(
3859 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
Camille Lamy5193caa2018-10-12 11:59:423860 }
3861
3862 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:313863 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513864 entry->ConstructCommonNavigationParams(
3865 *frame_entry, request_body, dest_url,
3866 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:383867 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:533868 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513869 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:553870 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:423871
3872 // TODO(clamy): |intended_as_new_entry| below should always be false once
3873 // Reload no longer leads to this being called for a pending NavigationEntry
3874 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:313875 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:143876 entry->ConstructCommitNavigationParams(
3877 *frame_entry, common_params->url, origin_to_commit,
3878 common_params->method, entry->GetSubframeUniqueNames(frame_tree_node),
3879 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:533880 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
3881 frame_tree_node->pending_frame_policy());
Lucas Furukawa Gadania9c45682019-07-31 22:05:143882 commit_params->post_content_type = post_content_type;
Camille Lamy5193caa2018-10-12 11:59:423883
W. James MacLean81b8d01f2022-01-25 20:50:593884 if (common_params->url.IsAboutSrcdoc())
3885 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
clamyea99ea12018-05-28 13:54:233886 return NavigationRequest::CreateBrowserInitiated(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143887 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:433888 is_browser_initiated, false /* was_opener_suppressed */,
Takashi Toyoshimae87b7be2021-01-22 11:51:083889 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:453890 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
3891 entry->extra_headers(), frame_entry, entry, request_body,
Daniel Hosseinianf0fbfb42021-09-08 02:20:473892 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
3893 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:233894}
3895
[email protected]d202a7c2012-01-04 07:53:473896void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:213897 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:273898 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:403899
Takashi Toyoshimaea534ef22021-07-21 03:27:593900 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:403901 // location bar will have up-to-date information about the security style
3902 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:133903 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:403904
Rakina Zata Amnidaa84f62022-02-17 00:55:313905 bool should_fire_navigation_state_changed = true;
3906#if BUILDFLAG(IS_ANDROID)
3907 if (details && details->should_stay_as_initial_entry) {
3908 // For initial NavigationEntries, only fire NavigationStateChanged() if the
3909 // embedder wants to hear about it.
3910 should_fire_navigation_state_changed =
3911 !GetContentClient()
3912 ->browser()
3913 ->ShouldIgnoreInitialNavigationEntryNavigationStateChangedForLegacySupport();
3914 }
3915#endif
3916 if (should_fire_navigation_state_changed)
3917 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
3918
[email protected]ec6c05f2013-10-23 18:41:573919 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:463920
[email protected]b0f724c2013-09-05 04:21:133921 // TODO(avi): Remove. http://crbug.com/170921
3922 NotificationDetails notification_details =
3923 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:153924 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
3925 Source<NavigationController>(this),
3926 notification_details);
initial.commit09911bf2008-07-26 23:55:293927}
3928
initial.commit09911bf2008-07-26 23:55:293929// static
[email protected]d202a7c2012-01-04 07:53:473930size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:233931 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:153932 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:213933 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:233934}
3935
[email protected]d202a7c2012-01-04 07:53:473936void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:223937 if (is_active && needs_reload_)
3938 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:293939}
3940
[email protected]d202a7c2012-01-04 07:53:473941void NavigationControllerImpl::LoadIfNecessary() {
initial.commit09911bf2008-07-26 23:55:293942 if (!needs_reload_)
3943 return;
3944
Bo Liucdfa4b12018-11-06 00:21:443945 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
3946 needs_reload_type_);
3947
initial.commit09911bf2008-07-26 23:55:293948 // Calling Reload() results in ignoring state, and not loading.
3949 // Explicitly use NavigateToPendingEntry so that the renderer uses the
3950 // cached state.
avicc872d7242015-08-19 21:26:343951 if (pending_entry_) {
Dave Tapuska8bfd84c2019-03-26 20:47:163952 NavigateToExistingPendingEntry(ReloadType::NONE,
Nate Chapin45f620582021-09-30 17:45:433953 FrameTreeNode::kFrameTreeNodeInvalidId,
3954 true /* is_browser_initiated */);
Rakina Zata Amni2322f4f82022-01-24 13:24:243955 } else if (last_committed_entry_index_ != -1 &&
3956 !GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:433957 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:273958 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:343959 pending_entry_index_ = last_committed_entry_index_;
Dave Tapuska8bfd84c2019-03-26 20:47:163960 NavigateToExistingPendingEntry(ReloadType::NONE,
Nate Chapin45f620582021-09-30 17:45:433961 FrameTreeNode::kFrameTreeNodeInvalidId,
3962 true /* is_browser_initiated */);
avicc872d7242015-08-19 21:26:343963 } else {
Rakina Zata Amnif297a802022-01-18 03:53:433964 // We should never navigate to an existing initial NavigationEntry that is
3965 // the initial NavigationEntry for the initial empty document that hasn't
3966 // been overridden by the synchronous about:blank commit, to preserve
3967 // legacy behavior where trying to reload when the main frame is on the
3968 // initial empty document won't result in a navigation. See also
3969 // https://crbug.com/1277414. If there is something to reload, the
3970 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
3971 // it here.
avicc872d7242015-08-19 21:26:343972 needs_reload_ = false;
3973 }
initial.commit09911bf2008-07-26 23:55:293974}
3975
Kevin McNeeccca6172021-10-19 17:11:143976base::WeakPtr<NavigationHandle>
3977NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:363978 RenderFrameHost* render_frame_host,
3979 const GURL& url,
3980 const std::string& error_page_html,
3981 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:133982 RenderFrameHostImpl* rfhi =
3983 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:583984
3985 // Only active documents can load post-commit error pages:
3986 // - If the document is in pending deletion, the browser already committed to
3987 // destroying this RenderFrameHost so ignore loading the error page.
3988 // - If the document is in back-forward cache, it's not allowed to navigate as
3989 // it should remain frozen. Ignore the request and evict the document from
3990 // back-forward cache.
3991 // - If the document is prerendering, it can navigate but when loading error
3992 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:113993 if (rfhi->IsInactiveAndDisallowActivation(
3994 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:143995 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:113996 }
Sreeja Kamishettydb8e2892021-03-10 09:30:583997
Rakina Zata Amni919b7922020-12-11 09:03:133998 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:413999
Minggang Wangb9f3fa92021-07-01 15:30:314000 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434001 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594002 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4003 // the frame actually committed (e.g. iframe with "src" set to a
4004 // slow-responding URL). We should rewrite the URL to about:blank in this
4005 // case, as the renderer will only think a page is an error page if it has a
4006 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134007 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314008 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434009 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334010 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414011
arthursonzogni70ac7302020-05-28 08:49:054012 // Error pages have a fully permissive FramePolicy.
4013 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4014 // error pages.
4015 commit_params->frame_policy = blink::FramePolicy();
4016
John Delaney131ad362019-08-08 21:57:414017 std::unique_ptr<NavigationRequest> navigation_request =
4018 NavigationRequest::CreateBrowserInitiated(
4019 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084020 true /* browser_initiated */, false /* was_opener_suppressed */,
Lingqi Chi82efa95e2020-12-29 05:31:194021 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:454022 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
John Delaneyf43556d2020-05-04 23:19:064023 "" /* extra_headers */, nullptr /* frame_entry */,
4024 nullptr /* entry */, nullptr /* post_body */,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474025 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
4026 false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364027 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414028 navigation_request->set_net_error(error);
4029 node->CreatedNavigationRequest(std::move(navigation_request));
4030 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144031
4032 // Calling BeginNavigation may destroy the NavigationRequest.
4033 base::WeakPtr<NavigationRequest> created_navigation_request(
4034 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414035 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144036 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414037}
4038
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574039void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214040 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094041 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154042 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144043 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294044}
4045
[email protected]d202a7c2012-01-04 07:53:474046void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364047 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474048 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4049 // represent a no-committed-entry state.
4050 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364051 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474052 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4053 // if `entries_` contains pre-existing entries from the NavigationController
4054 // before restore, which would not be removed and will be at the front of the
4055 // entries list, causing the index to be off by the amount of pre-existing
4056 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294057 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294058}
[email protected]765b35502008-08-21 00:51:204059
arthursonzogni69a6a1b2019-09-17 09:23:004060void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004061 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4062}
4063
4064void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4065 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474066 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104067 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4068 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294069 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474070 return;
Michael Thiessenc5676d22019-09-25 22:32:104071 }
avi45a72532015-04-07 21:01:454072 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314073
4074 if (!delegate_)
4075 return;
4076
4077 bool should_fire_navigation_state_changed = true;
4078#if BUILDFLAG(IS_ANDROID)
4079 if (commit_details && commit_details->should_stay_as_initial_entry) {
4080 // For initial NavigationEntries, only fire NavigationStateChanged() if the
4081 // embedder wants to hear about it.
4082 should_fire_navigation_state_changed =
4083 !GetContentClient()
4084 ->browser()
4085 ->ShouldIgnoreInitialNavigationEntryNavigationStateChangedForLegacySupport();
Rakina Zata Amniddf10502022-01-15 02:56:554086 }
Rakina Zata Amnidaa84f62022-02-17 00:55:314087#endif
4088 if (should_fire_navigation_state_changed)
4089 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484090}
4091
avi7c6f35e2015-05-08 17:52:384092int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4093 int nav_entry_id) const {
4094 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4095 if (entries_[i]->GetUniqueID() == nav_entry_id)
4096 return i;
4097 }
4098 return -1;
4099}
4100
[email protected]d202a7c2012-01-04 07:53:474101void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574102 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254103 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574104 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574105 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4106 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254107 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374108 // Normally, cloning a NavigationEntryImpl results in sharing
4109 // FrameNavigationEntries between the original and the clone. However, when
4110 // cloning from a different NavigationControllerImpl, we want to fork the
4111 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374112 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574113 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254114 }
arthursonzogni5c4c202d2017-04-25 23:41:274115 DCHECK(pending_entry_index_ == -1 ||
4116 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254117}
[email protected]c5b88d82012-10-06 17:03:334118
4119void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184120 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334121 get_timestamp_callback_ = get_timestamp_callback;
4122}
[email protected]8ff00d72012-10-23 19:12:214123
Shivani Sharmaffb32b82019-04-09 16:58:474124// History manipulation intervention:
4125void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474126 bool replace_entry,
4127 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404128 bool is_renderer_initiated,
4129 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454130 // Note that for a subframe, previous_document_was_activated is true if the
4131 // gesture happened in any subframe (propagated to main frame) or in the main
4132 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474133 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274134 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474135 return;
4136 }
4137 if (last_committed_entry_index_ == -1)
4138 return;
4139
Shivani Sharmac4cc8922019-04-18 03:11:174140 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474141
Alexander Timine3ec4192020-04-20 16:39:404142 // Log UKM with the URL we are navigating away from.
4143 ukm::builders::HistoryManipulationIntervention(
4144 previous_page_load_ukm_source_id)
4145 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474146}
4147
Shivani Sharmac4cc8922019-04-18 03:11:174148void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4149 int reference_index,
4150 bool skippable) {
4151 auto* reference_entry = GetEntryAtIndex(reference_index);
4152 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4153
4154 int64_t document_sequence_number =
4155 reference_entry->root_node()->frame_entry->document_sequence_number();
4156 for (int index = 0; index < GetEntryCount(); index++) {
4157 auto* entry = GetEntryAtIndex(index);
4158 if (entry->root_node()->frame_entry->document_sequence_number() ==
4159 document_sequence_number) {
4160 entry->set_should_skip_on_back_forward_ui(skippable);
4161 }
4162 }
4163}
4164
arthursonzogni66f711c2019-10-08 14:40:364165std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4166NavigationControllerImpl::ReferencePendingEntry() {
4167 DCHECK(pending_entry_);
4168 auto pending_entry_ref =
4169 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4170 pending_entry_refs_.insert(pending_entry_ref.get());
4171 return pending_entry_ref;
4172}
4173
4174void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4175 // Ignore refs that don't correspond to the current pending entry.
4176 auto it = pending_entry_refs_.find(ref);
4177 if (it == pending_entry_refs_.end())
4178 return;
4179 pending_entry_refs_.erase(it);
4180
4181 if (!pending_entry_refs_.empty())
4182 return;
4183
4184 // The pending entry may be deleted before the last PendingEntryRef.
4185 if (!pending_entry_)
4186 return;
4187
4188 // We usually clear the pending entry when the matching NavigationRequest
4189 // fails, so that an arbitrary URL isn't left visible above a committed page.
4190 //
4191 // However, we do preserve the pending entry in some cases, such as on the
4192 // initial navigation of an unmodified blank tab. We also allow the delegate
4193 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4194 // user edit the URL and try again. This may be useful in cases that the
4195 // committed page cannot be attacker-controlled. In these cases, we still
4196 // allow the view to clear the pending entry and typed URL if the user
4197 // requests (e.g., hitting Escape with focus in the address bar).
4198 //
4199 // Do not leave the pending entry visible if it has an invalid URL, since this
4200 // might be formatted in an unexpected or unsafe way.
4201 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364202 bool should_preserve_entry =
4203 (pending_entry_ == GetVisibleEntry()) &&
4204 pending_entry_->GetURL().is_valid() &&
4205 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4206 if (should_preserve_entry)
4207 return;
4208
4209 DiscardPendingEntry(true);
4210 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
4211}
4212
Titouan Rigoudy6ec70402021-02-02 15:42:194213std::unique_ptr<PolicyContainerPolicies>
4214NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394215 RenderFrameHostImpl* rfh,
4216 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174217 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394218 if (is_same_document) {
Rakina Zata Amni2322f4f82022-01-24 13:24:244219 // TODO(https://crbug.com/524208): Remove this nullptr check when we can
4220 // ensure we always have a FrameNavigationEntry here.
4221 if (!GetLastCommittedEntry())
4222 return nullptr;
Charlie Reis73e356242021-04-02 17:10:314223
Antonio Sartori78a749f2020-11-30 12:03:394224 FrameNavigationEntry* previous_frame_entry =
4225 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4226
4227 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4228 // ensure we always have a FrameNavigationEntry here.
4229 if (!previous_frame_entry)
4230 return nullptr;
4231
Titouan Rigoudy6ec70402021-02-02 15:42:194232 const PolicyContainerPolicies* previous_policies =
4233 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394234
Titouan Rigoudy6ec70402021-02-02 15:42:194235 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394236 return nullptr;
4237
4238 // Make a copy of the policy container for the new FrameNavigationEntry.
Antonio Sartori5d09b30f2021-03-02 09:27:164239 return previous_policies->Clone();
Antonio Sartori78a749f2020-11-30 12:03:394240 }
4241
Antonio Sartori4f5373792021-05-31 10:56:474242 return rfh->policy_container_host()->policies().Clone();
Antonio Sartori78a749f2020-11-30 12:03:394243}
4244
Hayato Ito2c8c08d02021-06-23 03:38:434245void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504246 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434247 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4248 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4249 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504250
4251 auto callback = base::BindRepeating(
4252 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4253 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4254 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4255 }
4256 },
Hayato Ito2c8c08d02021-06-23 03:38:434257 GetLastCommittedEntryIndex(), GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504258 frame_tree_.root()->render_manager()->ExecutePageBroadcastMethod(callback);
4259}
4260
4261void NavigationControllerImpl::DidAccessInitialMainDocument() {
4262 // We may have left a failed browser-initiated navigation in the address bar
4263 // to let the user edit it and try again. Clear it now that content might
4264 // show up underneath it.
4265 if (!frame_tree_.IsLoading() && GetPendingEntry())
4266 DiscardPendingEntry(false);
4267
4268 // Update the URL display.
4269 delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
4270}
4271
4272void NavigationControllerImpl::UpdateStateForFrame(
4273 RenderFrameHostImpl* rfhi,
4274 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564275 OPTIONAL_TRACE_EVENT1("content",
4276 "NavigationControllerImpl::UpdateStateForFrame",
4277 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504278 // The state update affects the last NavigationEntry associated with the given
4279 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4280 // in the case of an UpdateState from a frame being swapped out). We track
4281 // which entry this is in the RenderFrameHost's nav_entry_id.
4282 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4283 if (!entry)
4284 return;
4285
4286 FrameNavigationEntry* frame_entry =
4287 entry->GetFrameEntry(rfhi->frame_tree_node());
4288 if (!frame_entry)
4289 return;
4290
4291 // The SiteInstance might not match if we do a cross-process navigation with
4292 // replacement (e.g., auto-subframe), in which case the swap out of the old
4293 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4294 // has already been replaced and destroyed.
4295 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4296 return;
4297
4298 if (page_state == frame_entry->page_state())
4299 return; // Nothing to update.
4300
4301 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4302
4303 // The document_sequence_number and item_sequence_number recorded in the
4304 // FrameNavigationEntry should not differ from the one coming with the update,
4305 // since it must come from the same document. Do not update it if a difference
4306 // is detected, as this indicates that |frame_entry| is not the correct one.
4307 blink::ExplodedPageState exploded_state;
4308 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4309 return;
4310
4311 if (exploded_state.top.document_sequence_number !=
4312 frame_entry->document_sequence_number() ||
4313 exploded_state.top.item_sequence_number !=
4314 frame_entry->item_sequence_number()) {
4315 return;
4316 }
4317
4318 frame_entry->SetPageState(page_state);
4319 NotifyEntryChanged(entry);
4320}
4321
Minggang Wangb9f3fa92021-07-01 15:30:314322std::vector<blink::mojom::AppHistoryEntryPtr>
Nate Chapind1fe3612021-04-16 20:45:574323NavigationControllerImpl::PopulateSingleAppHistoryEntryVector(
4324 Direction direction,
4325 int entry_index,
4326 const url::Origin& pending_origin,
4327 FrameTreeNode* node,
4328 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304329 int64_t pending_item_sequence_number,
4330 int64_t pending_document_sequence_number) {
Minggang Wangb9f3fa92021-07-01 15:30:314331 std::vector<blink::mojom::AppHistoryEntryPtr> entries;
Rakina Zata Amni2322f4f82022-01-24 13:24:244332 if (GetLastCommittedEntry() && GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174333 // Don't process the initial entry.
4334 DCHECK_EQ(GetEntryCount(), 1);
4335 return entries;
4336 }
Nate Chapind1fe3612021-04-16 20:45:574337 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304338 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574339 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4340 i += offset) {
4341 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414342 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574343 break;
Nate Chapindedfa642022-01-28 23:59:414344 // An entry should only appear in appHistory entries if it is for the same
4345 // origin as the document being committed. Check the committed origin, or if
4346 // that is not available (during restore), check against the FNE's url.
4347 url::Origin frame_entry_origin =
4348 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4349 frame_entry->url(),
4350 frame_entry->initiator_origin().value_or(url::Origin())));
4351 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574352 break;
4353 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4354 continue;
4355 blink::ExplodedPageState exploded_page_state;
4356 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4357 &exploded_page_state)) {
4358 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304359
4360 // If the document represented by this FNE hid its full url from appearing
4361 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
4362 // the url in appHistory as well (unless we're navigating to that
4363 // document).
4364 std::u16string url;
4365 if (pending_document_sequence_number ==
4366 frame_entry->document_sequence_number() ||
4367 !frame_entry->protect_url_in_app_history()) {
4368 url = frame_state.url_string.value_or(std::u16string());
4369 }
4370
Minggang Wangb9f3fa92021-07-01 15:30:314371 blink::mojom::AppHistoryEntryPtr entry =
4372 blink::mojom::AppHistoryEntry::New(
4373 frame_state.app_history_key.value_or(std::u16string()),
Nate Chapin63db0d12022-01-20 22:03:304374 frame_state.app_history_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094375 frame_state.item_sequence_number,
4376 frame_state.document_sequence_number,
4377 frame_state.app_history_state.value_or(std::u16string()));
Rakina Zata Amniafd3c6582021-11-30 06:19:174378
Nate Chapin63db0d12022-01-20 22:03:304379 DCHECK(entry->url.empty() ||
4380 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574381 entries.push_back(std::move(entry));
4382 previous_item_sequence_number = frame_entry->item_sequence_number();
4383 }
4384 }
4385 // If |entries| was constructed by iterating backwards from
4386 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4387 // earliest-at-the-front. Reverse it.
4388 if (direction == Direction::kBack)
4389 std::reverse(entries.begin(), entries.end());
4390 return entries;
4391}
4392
Nate Chapin4e657a472022-02-06 03:38:374393blink::mojom::AppHistoryEntryArraysPtr
4394NavigationControllerImpl::GetAppHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554395 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574396 NavigationRequest* request) {
4397 url::Origin pending_origin =
Nate Chapin97d2f542022-02-18 01:34:554398 request ? request->commit_params().origin_to_commit
4399 ? *request->commit_params().origin_to_commit
4400 : url::Origin::Create(request->common_params().url)
4401 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574402
Nate Chapind1fe3612021-04-16 20:45:574403 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554404 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574405
4406 // NOTE: |entry_index| is an estimate of the index where this entry will
4407 // commit, but it may be wrong in corner cases (e.g., if we are at the max
4408 // entry limit, the earliest entry will be dropped). This is ok because this
4409 // algorithm only uses |entry_index| to walk the entry list as it stands right
4410 // now, and it isn't saved for anything post-commit.
4411 int entry_index = GetPendingEntryIndex();
4412 bool will_create_new_entry = false;
Nate Chapin97d2f542022-02-18 01:34:554413 if (!request ||
4414 NavigationTypeUtils::IsReload(request->common_params().navigation_type) ||
Nate Chapind1fe3612021-04-16 20:45:574415 request->common_params().should_replace_current_entry) {
4416 entry_index = GetLastCommittedEntryIndex();
4417 } else if (entry_index == -1) {
4418 will_create_new_entry = true;
4419 entry_index = GetLastCommittedEntryIndex() + 1;
4420 }
4421
4422 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304423 int64_t pending_document_sequence_number = 0;
Nate Chapind1fe3612021-04-16 20:45:574424 if (auto* pending_entry = GetPendingEntry()) {
Nate Chapin63db0d12022-01-20 22:03:304425 if (auto* frame_entry = pending_entry->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574426 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304427 pending_document_sequence_number =
4428 frame_entry->document_sequence_number();
4429 }
Nate Chapind1fe3612021-04-16 20:45:574430 }
4431
Nate Chapin4e657a472022-02-06 03:38:374432 auto entry_arrays = blink::mojom::AppHistoryEntryArrays::New();
4433 entry_arrays->back_entries = PopulateSingleAppHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574434 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374435 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574436
4437 // Don't populate forward entries if they will be truncated by a new entry.
4438 if (!will_create_new_entry) {
Nate Chapin4e657a472022-02-06 03:38:374439 entry_arrays->forward_entries = PopulateSingleAppHistoryEntryVector(
4440 Direction::kForward, entry_index, pending_origin, node,
4441 site_instance.get(), pending_item_sequence_number,
4442 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574443 }
Nate Chapin4e657a472022-02-06 03:38:374444 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574445}
4446
Nate Chapinfbfe5af2021-06-10 17:22:084447NavigationControllerImpl::HistoryNavigationAction
4448NavigationControllerImpl::ShouldNavigateToEntryForAppHistoryKey(
4449 FrameNavigationEntry* current_entry,
4450 FrameNavigationEntry* target_entry,
4451 const std::string& app_history_key) {
4452 if (!target_entry || !target_entry->committed_origin())
4453 return HistoryNavigationAction::kStopLooking;
4454 if (current_entry->site_instance() != target_entry->site_instance())
4455 return HistoryNavigationAction::kStopLooking;
4456 if (!current_entry->committed_origin()->IsSameOriginWith(
4457 *target_entry->committed_origin())) {
4458 return HistoryNavigationAction::kStopLooking;
4459 }
4460
4461 // NOTE: We don't actually care between kSameDocument and
4462 // kDifferentDocument, so always use kDifferentDocument by convention.
4463 if (target_entry->app_history_key() == app_history_key)
4464 return HistoryNavigationAction::kDifferentDocument;
4465 return HistoryNavigationAction::kKeepLooking;
4466}
4467
4468void NavigationControllerImpl::NavigateToAppHistoryKey(FrameTreeNode* node,
4469 const std::string& key) {
4470 FrameNavigationEntry* current_entry =
4471 GetLastCommittedEntry()->GetFrameEntry(node);
4472 if (!current_entry)
4473 return;
4474
4475 // We want to find the nearest matching entry that is contiguously
4476 // same-instance and same-origin. Check back first, then forward.
4477 // TODO(japhet): Link spec here once it exists.
4478 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
4479 auto result = ShouldNavigateToEntryForAppHistoryKey(
4480 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4481 if (result == HistoryNavigationAction::kStopLooking)
4482 break;
4483 if (result != HistoryNavigationAction::kKeepLooking) {
Nate Chapin2892b37c2021-10-08 17:33:114484 GoToIndex(i, FrameTreeNode::kFrameTreeNodeInvalidId,
4485 false /* is_browser_initiated*/);
Nate Chapinfbfe5af2021-06-10 17:22:084486 return;
4487 }
4488 }
4489 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
4490 auto result = ShouldNavigateToEntryForAppHistoryKey(
4491 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4492 if (result == HistoryNavigationAction::kStopLooking)
4493 break;
4494 if (result != HistoryNavigationAction::kKeepLooking) {
Nate Chapin2892b37c2021-10-08 17:33:114495 GoToIndex(i, FrameTreeNode::kFrameTreeNodeInvalidId,
4496 false /* is_browser_initiated*/);
Nate Chapinfbfe5af2021-06-10 17:22:084497 return;
4498 }
4499 }
4500}
4501
Nate Chapin63db0d12022-01-20 22:03:304502bool NavigationControllerImpl::ShouldProtectUrlInAppHistory(
4503 network::mojom::ReferrerPolicy referrer_policy) {
4504 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4505 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4506}
4507
shivanigithubf405bf0d2021-11-05 17:58:334508bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4509 const FrameTreeNode* frame_tree_node) const {
4510 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4511 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544512 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
shivanigithubf405bf0d2021-11-05 17:58:334513 return frame_tree_.is_prerendering() ||
4514 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544515}
4516
[email protected]8ff00d72012-10-23 19:12:214517} // namespace content