1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
|
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/preloading/prefetch/prefetch_url_loader_helper.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_macros.h"
#include "base/time/time.h"
#include "content/browser/preloading/prefetch/prefetch_features.h"
#include "content/browser/preloading/prefetch/prefetch_origin_prober.h"
#include "content/browser/preloading/prefetch/prefetch_params.h"
#include "content/browser/preloading/prefetch/prefetch_probe_result.h"
#include "content/browser/preloading/prefetch/prefetch_service.h"
#include "content/browser/preloading/prefetch/prefetch_serving_page_metrics_container.h"
#include "content/browser/preloading/prefetch/prefetch_status.h"
#include "content/browser/renderer_host/frame_tree_node.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/public/browser/prefetch_metrics.h"
#include "content/public/browser/web_contents.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_partition_key_collection.h"
#include "services/network/public/cpp/resource_request.h"
#include "url/gurl.h"
#include "url/scheme_host_port.h"
namespace content {
namespace {
PrefetchServingPageMetricsContainer*
PrefetchServingPageMetricsContainerFromFrameTreeNodeId(
FrameTreeNodeId frame_tree_node_id) {
FrameTreeNode* frame_tree_node =
FrameTreeNode::GloballyFindByID(frame_tree_node_id);
if (!frame_tree_node || !frame_tree_node->navigation_request()) {
return nullptr;
}
return PrefetchServingPageMetricsContainer::GetForNavigationHandle(
*frame_tree_node->navigation_request());
}
void RecordCookieWaitTime(base::TimeDelta wait_time) {
UMA_HISTOGRAM_CUSTOM_TIMES(
"PrefetchProxy.AfterClick.Mainframe.CookieWaitTime", wait_time,
base::TimeDelta(), base::Seconds(5), 50);
}
// Stores state for the asynchronous work required to prepare a prefetch to
// serve.
struct OnGotPrefetchToServeState {
// Inputs.
const FrameTreeNodeId frame_tree_node_id;
const GURL tentative_url;
base::OnceCallback<void(PrefetchContainer::Reader)> callback;
PrefetchContainer::Reader reader;
// True if we've validated that cookies match (to the extent required).
// False if they don't. Absent if we don't know yet.
// Unused if `features::kPrefetchCookieIndices` is disabled.
std::optional<bool> cookies_matched;
// The probe result, once it has been determined.
// If it is empty, then this will be the next thing
// ContinueOnGotPrefetchToServe does.
std::optional<PrefetchProbeResult> probe_result;
// True if copying isolated cookies is either done or has been determined
// unnecessary.
bool cookie_copy_complete_if_required = false;
};
// Forward declarations are required for these to call each other while
// appearing in the order they occur.
void ContinueOnGotPrefetchToServe(
std::unique_ptr<OnGotPrefetchToServeState> state);
void StartCookieValidation(std::unique_ptr<OnGotPrefetchToServeState>& state);
void OnGotCookiesForValidation(
std::unique_ptr<OnGotPrefetchToServeState> state,
const std::vector<net::CookieWithAccessResult>& cookies,
const std::vector<net::CookieWithAccessResult>& excluded_cookies);
void StartProbe(std::unique_ptr<OnGotPrefetchToServeState>& state);
void OnProbeComplete(std::unique_ptr<OnGotPrefetchToServeState> state,
base::TimeTicks probe_start_time,
PrefetchProbeResult probe_result);
void EnsureCookiesCopied(std::unique_ptr<OnGotPrefetchToServeState>& state);
void OnCookieCopyComplete(std::unique_ptr<OnGotPrefetchToServeState> state,
base::TimeTicks cookie_copy_start_time);
// Overall structure of asynchronous execution (in coroutine style).
void ContinueOnGotPrefetchToServe(
std::unique_ptr<OnGotPrefetchToServeState> state) {
// If the cookies need to be matched, fetch them and confirm that they're
// correct.
if (base::FeatureList::IsEnabled(features::kPrefetchCookieIndices)) {
if (!state->cookies_matched.has_value()) {
StartCookieValidation(state);
if (!state) {
// Fetching the cookies asynchronously. Continue later.
return;
}
}
CHECK(state->cookies_matched.has_value());
if (!state->cookies_matched.value()) {
// Cookies did not match, but needed to. We're done here.
std::move(state->callback).Run({});
return;
}
}
// If probing hasn't happened yet, do it if necessary.
if (!state->probe_result.has_value()) {
StartProbe(state);
if (!state) {
// The probe is happening asynchronously (it took ownership of |state|),
// and this algorithm will continue later.
return;
}
if (!state->probe_result.has_value()) {
// Could not start a probe. We're done here.
std::move(state->callback).Run({});
return;
}
}
if (!PrefetchProbeResultIsSuccess(state->probe_result.value())) {
// Probe failed. We're done here.
std::move(state->callback).Run({});
return;
}
// Copy isolated cookies, if required.
if (!state->cookie_copy_complete_if_required) {
EnsureCookiesCopied(state);
if (!state) {
// Cookie copy is happening and this function will continue later.
return;
}
}
// All prerequisites should now be complete.
CHECK(!base::FeatureList::IsEnabled(features::kPrefetchCookieIndices) ||
state->cookies_matched.value_or(false));
CHECK(PrefetchProbeResultIsSuccess(state->probe_result.value()));
CHECK(state->cookie_copy_complete_if_required);
if (!state->reader) {
std::move(state->callback).Run({});
return;
}
switch (state->reader.GetServableState(PrefetchCacheableDuration())) {
case PrefetchContainer::ServableState::kNotServable:
case PrefetchContainer::ServableState::kShouldBlockUntilEligibilityGot:
case PrefetchContainer::ServableState::kShouldBlockUntilHeadReceived:
std::move(state->callback).Run({});
return;
case PrefetchContainer::ServableState::kServable:
break;
}
// Delay updating the prefetch with the probe result in case it becomes not
// servable.
state->reader.OnPrefetchProbeResult(state->probe_result.value());
PrefetchServingPageMetricsContainer* serving_page_metrics_container =
PrefetchServingPageMetricsContainerFromFrameTreeNodeId(
state->frame_tree_node_id);
if (serving_page_metrics_container) {
serving_page_metrics_container->SetPrefetchStatus(
state->reader.GetPrefetchStatus());
}
std::move(state->callback).Run(std::move(state->reader));
}
// COOKIE VALIDATION
void StartCookieValidation(std::unique_ptr<OnGotPrefetchToServeState>& state) {
WebContents* web_contents =
WebContents::FromFrameTreeNodeId(state->frame_tree_node_id);
if (!web_contents || !state->reader) {
// We can't confirm that the cookies matched. But probably everything is
// being torn down, anyway.
state->cookies_matched = false;
return;
}
if (!state->reader.VariesOnCookieIndices()) {
state->cookies_matched = true;
return;
}
network::mojom::CookieManager* cookie_manager =
web_contents->GetBrowserContext()
->GetDefaultStoragePartition()
->GetCookieManagerForBrowserProcess();
// Note: This currently relies on this being for main frame use only.
// The partitioning below needs to be adjusted if a subframe use were
// possible.
CHECK(FrameTreeNode::GloballyFindByID(state->frame_tree_node_id)
->IsMainFrame());
const GURL& url = state->reader.GetCurrentURLToServe();
net::SchemefulSite site(url);
cookie_manager->GetCookieList(
url, net::CookieOptions::MakeAllInclusive(),
net::CookiePartitionKeyCollection(
net::CookiePartitionKey::FromNetworkIsolationKey(
net::NetworkIsolationKey(site, site), net::SiteForCookies(site),
site, /*main_frame_navigation=*/true)),
base::BindOnce(&OnGotCookiesForValidation, std::move(state)));
}
void OnGotCookiesForValidation(
std::unique_ptr<OnGotPrefetchToServeState> state,
const std::vector<net::CookieWithAccessResult>& cookies,
const std::vector<net::CookieWithAccessResult>& excluded_cookies) {
std::vector<std::pair<std::string, std::string>> cookie_values;
cookie_values.reserve(cookies.size());
for (const net::CookieWithAccessResult& cookie : cookies) {
cookie_values.emplace_back(cookie.cookie.Name(), cookie.cookie.Value());
}
state->cookies_matched =
state->reader && state->reader.MatchesCookieIndices(cookie_values);
ContinueOnGotPrefetchToServe(std::move(state));
}
// ORIGIN PROBING
void StartProbe(std::unique_ptr<OnGotPrefetchToServeState>& state) {
// TODO(crbug.com/40274818): Should we check for existence of an
// `origin_prober` earlier instead of waiting until we have a matching
// prefetch?
PrefetchService* prefetch_service =
PrefetchService::GetFromFrameTreeNodeId(state->frame_tree_node_id);
if (!prefetch_service || !prefetch_service->GetPrefetchOriginProber()) {
return;
}
PrefetchOriginProber* prober = prefetch_service->GetPrefetchOriginProber();
if (!state->reader.IsIsolatedNetworkContextRequiredToServe() ||
!prober->ShouldProbeOrigins()) {
state->probe_result = PrefetchProbeResult::kNoProbing;
return;
}
GURL probe_url = url::SchemeHostPort(state->tentative_url).GetURL();
prober->Probe(probe_url,
base::BindOnce(&OnProbeComplete, std::move(state),
/*probe_start_time=*/base::TimeTicks::Now()));
}
// Called when the `PrefetchOriginProber` check is done (if performed).
// `probe_start_time` is used to calculate probe latency which is
// reported to the tab helper.
void OnProbeComplete(std::unique_ptr<OnGotPrefetchToServeState> state,
base::TimeTicks probe_start_time,
PrefetchProbeResult probe_result) {
state->probe_result = probe_result;
PrefetchServingPageMetricsContainer* serving_page_metrics_container =
PrefetchServingPageMetricsContainerFromFrameTreeNodeId(
state->frame_tree_node_id);
if (serving_page_metrics_container) {
serving_page_metrics_container->SetProbeLatency(base::TimeTicks::Now() -
probe_start_time);
}
if (!PrefetchProbeResultIsSuccess(probe_result) && state->reader) {
state->reader.OnPrefetchProbeResult(probe_result);
if (serving_page_metrics_container) {
serving_page_metrics_container->SetPrefetchStatus(
state->reader.GetPrefetchStatus());
}
}
ContinueOnGotPrefetchToServe(std::move(state));
}
// ISOLATED COOKIE COPYING
// Ensures that the cookies for prefetch are copied from its isolated
// network context to the default network context.
void EnsureCookiesCopied(std::unique_ptr<OnGotPrefetchToServeState>& state) {
PrefetchContainer::Reader& reader = state->reader;
// Start the cookie copy for the next redirect hop of |state->reader|.
if (reader && !reader.HasIsolatedCookieCopyStarted()) {
PrefetchService* prefetch_service =
PrefetchService::GetFromFrameTreeNodeId(state->frame_tree_node_id);
if (prefetch_service) {
prefetch_service->CopyIsolatedCookies(reader);
}
}
if (reader) {
reader.OnInterceptorCheckCookieCopy();
}
if (!reader || !reader.IsIsolatedCookieCopyInProgress()) {
RecordCookieWaitTime(base::TimeDelta());
state->cookie_copy_complete_if_required = true;
return;
}
reader.SetOnCookieCopyCompleteCallback(
base::BindOnce(&OnCookieCopyComplete, std::move(state),
/*cookie_copy_start_time=*/base::TimeTicks::Now()));
}
void OnCookieCopyComplete(std::unique_ptr<OnGotPrefetchToServeState> state,
base::TimeTicks cookie_copy_start_time) {
base::TimeDelta wait_time = base::TimeTicks::Now() - cookie_copy_start_time;
CHECK_GE(wait_time, base::TimeDelta());
RecordCookieWaitTime(wait_time);
state->cookie_copy_complete_if_required = true;
ContinueOnGotPrefetchToServe(std::move(state));
}
} // namespace
void OnGotPrefetchToServe(
FrameTreeNodeId frame_tree_node_id,
const GURL& tentative_resource_request_url,
base::OnceCallback<void(PrefetchContainer::Reader)> get_prefetch_callback,
PrefetchContainer::Reader reader) {
// TODO(crbug.com/40274818): With multiple prefetches matching, we should
// move some of the checks here in `PrefetchService::ReturnPrefetchToServe`.
// Why ? Because we might be able to serve a different prefetch if the
// prefetch in the `reader` cannot be served.
// The `tentative_resource_request_url` might be different from
// `GetCurrentURLToServe()` because of No-Vary-Search non-exact url match.
#if DCHECK_IS_ON()
if (reader) {
GURL::Replacements replacements;
replacements.ClearRef();
replacements.ClearQuery();
DCHECK_EQ(tentative_resource_request_url.ReplaceComponents(replacements),
reader.GetCurrentURLToServe().ReplaceComponents(replacements));
}
#endif
if (!reader) {
std::move(get_prefetch_callback).Run({});
return;
}
switch (reader.GetServableState(PrefetchCacheableDuration())) {
case PrefetchContainer::ServableState::kNotServable:
case PrefetchContainer::ServableState::kShouldBlockUntilEligibilityGot:
case PrefetchContainer::ServableState::kShouldBlockUntilHeadReceived:
std::move(get_prefetch_callback).Run({});
return;
case PrefetchContainer::ServableState::kServable:
break;
}
// We should not reach here if the cookies have changed. This should already
// have been checked in one of the call sites:
// 1) PrefetchService::ReturnPrefetchToServe (in which case |reader| should be
// empty)
// 2) PrefetchURLLoaderInterceptor::MaybeCreateLoader (before serving the next
// next redirect hop)
CHECK(!reader.HaveDefaultContextCookiesChanged());
// Asynchronous activity begins here.
// We allocate an explicit "coroutine state" for this and manage it manually.
// While slightly verbose, this avoids duplication of logic later on in
// control flow. This function will asynchronously call itself until it's
// done.
ContinueOnGotPrefetchToServe(base::WrapUnique(new OnGotPrefetchToServeState{
.frame_tree_node_id = frame_tree_node_id,
.tentative_url = tentative_resource_request_url,
.callback = std::move(get_prefetch_callback),
.reader = std::move(reader)}));
}
} // namespace content
|