/
back_forward_cache_impl.cc
1637 lines (1465 loc) · 65.5 KB
/
back_forward_cache_impl.cc
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 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/renderer_host/back_forward_cache_impl.h"
#include <string>
#include <vector>
#include "base/barrier_closure.h"
#include "base/check.h"
#include "base/containers/contains.h"
#include "base/containers/cxx20_erase.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_macros.h"
#include "base/rand_util.h"
#include "base/ranges/algorithm.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/trace_event/typed_macros.h"
#include "build/build_config.h"
#include "content/browser/bad_message.h"
#include "content/browser/renderer_host/back_forward_cache_can_store_document_result.h"
#include "content/browser/renderer_host/back_forward_cache_metrics.h"
#include "content/browser/renderer_host/frame_tree_node.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/renderer_host/render_frame_host_delegate.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_frame_proxy_host.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/visible_time_request_trigger.h"
#include "content/common/content_navigation_policy.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_process_host_observer.h"
#include "content/public/browser/visibility.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_status_code.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/scheduler/web_scheduler_tracked_feature.h"
#include "third_party/blink/public/mojom/frame/sudden_termination_disabler_type.mojom-shared.h"
#if BUILDFLAG(IS_ANDROID)
#include "content/public/browser/android/child_process_importance.h"
#endif
namespace content {
class RenderProcessHostInternalObserver;
// Allows overriding the sizes of back/forward cache.
// Sizes set via this feature's parameters take precedence over others.
BASE_FEATURE(kBackForwardCacheSize,
"BackForwardCacheSize",
// Sets the BackForwardCache size for desktop.
// See crbug.com/1291435.
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) || \
BUILDFLAG(IS_CHROMEOS)
base::FEATURE_ENABLED_BY_DEFAULT
#else
base::FEATURE_DISABLED_BY_DEFAULT
#endif
);
// Sets BackForwardCache cache_size=6 per crbug.com/1291435.
const base::FeatureParam<int> kBackForwardCacheSizeCacheSize{
&kBackForwardCacheSize, "cache_size", 6};
// Disables EnforceCacheSizeLimitInternal() with foreground_cache_size=0, as
// the BFCachePolicy manager takes care of pruning for foreground tabs as well.
const base::FeatureParam<int> kBackForwardCacheSizeForegroundCacheSize{
&kBackForwardCacheSize, "foreground_cache_size", 0};
namespace {
using blink::scheduler::WebSchedulerTrackedFeature;
using blink::scheduler::WebSchedulerTrackedFeatures;
// The default number of entries the BackForwardCache can hold per tab.
static constexpr size_t kDefaultBackForwardCacheSize = 1;
// The default number value for the "foreground_cache_size" field trial
// parameter. This parameter controls the numbers of entries associated with
// foregrounded process the BackForwardCache can hold per tab, when using the
// foreground/background cache-limiting strategy. This strategy is enabled if
// the parameter values is non-zero.
static constexpr size_t kDefaultForegroundBackForwardCacheSize = 0;
// The default time to live in seconds for documents in BackForwardCache.
// See also crbug.com/1305878.
static constexpr int kDefaultTimeToLiveInBackForwardCacheInSeconds = 600;
#if BUILDFLAG(IS_ANDROID)
bool IsProcessBindingEnabled() {
// Avoid activating BackForwardCache trial for checking the parameters
// associated with it.
if (!IsBackForwardCacheEnabled())
return false;
const std::string process_binding_param =
base::GetFieldTrialParamValueByFeature(features::kBackForwardCache,
"process_binding_strength");
return process_binding_param.empty() || process_binding_param == "DISABLE";
}
// Association of ChildProcessImportance to corresponding string names.
const base::FeatureParam<ChildProcessImportance>::Option
child_process_importance_options[] = {
{ChildProcessImportance::IMPORTANT, "IMPORTANT"},
{ChildProcessImportance::MODERATE, "MODERATE"},
{ChildProcessImportance::NORMAL, "NORMAL"}};
// Defines the binding strength for a processes holding cached pages. The value
// is read from an experiment parameter value. Ideally this would be lower than
// the one for processes holding the foreground page and similar to that of
// background tabs so that the OS will hopefully kill the foreground tab last.
// The default importance is set to MODERATE.
const base::FeatureParam<ChildProcessImportance> kChildProcessImportanceParam{
&features::kBackForwardCache, "process_binding_strength",
ChildProcessImportance::MODERATE, &child_process_importance_options};
#endif
bool IsContentInjectionSupported() {
if (!IsBackForwardCacheEnabled())
return false;
static constexpr base::FeatureParam<bool> content_injection_supported(
&features::kBackForwardCache, "content_injection_supported", true);
return content_injection_supported.Get();
}
WebSchedulerTrackedFeatures SupportedFeaturesImpl() {
WebSchedulerTrackedFeatures features;
if (!IsBackForwardCacheEnabled())
return features;
static constexpr base::FeatureParam<std::string> supported_features(
&features::kBackForwardCache, "supported_features", "");
std::vector<std::string> tokens =
base::SplitString(supported_features.Get(), ",", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
for (const std::string& token : tokens) {
auto feature = blink::scheduler::StringToFeature(token);
if (feature.has_value()) {
features.Put(feature.value());
} else if (!blink::scheduler::IsRemovedFeature(token)) {
// |feature| might not have its value when the user is in an experimental
// group with the feature, and the feature is already removed.
DLOG(WARNING) << "Invalid feature string: " << token;
}
}
return features;
}
WebSchedulerTrackedFeatures SupportedFeatures() {
static WebSchedulerTrackedFeatures features = SupportedFeaturesImpl();
return features;
}
bool IgnoresOutstandingNetworkRequestForTesting() {
if (!IsBackForwardCacheEnabled())
return false;
static constexpr base::FeatureParam<bool>
outstanding_network_request_supported(
&features::kBackForwardCache,
"ignore_outstanding_network_request_for_testing", false);
return outstanding_network_request_supported.Get();
}
// Ignore all features that the page is using and all DisableForRenderFrameHost
// calls and force all pages to be cached. Should be used only for local testing
// and debugging -- things will break when this param is used.
bool ShouldIgnoreBlocklists() {
if (!IsBackForwardCacheEnabled())
return false;
static constexpr base::FeatureParam<bool> should_ignore_blocklists(
&features::kBackForwardCache, "should_ignore_blocklists", false);
return should_ignore_blocklists.Get();
}
// A list of WebSchedulerTrackedFeatures that always block back/forward
// cache. Some of these features are listed as blocking back/forward cache
// when actually the blocking is flag controlled and they are not registered
// as being used if we don't want them to block.
constexpr WebSchedulerTrackedFeatures kDisallowedFeatures(
WebSchedulerTrackedFeature::kBroadcastChannel,
WebSchedulerTrackedFeature::kContainsPlugins,
WebSchedulerTrackedFeature::kDedicatedWorkerOrWorklet,
WebSchedulerTrackedFeature::kDummy,
WebSchedulerTrackedFeature::kIdleManager,
WebSchedulerTrackedFeature::kIndexedDBConnection,
WebSchedulerTrackedFeature::kIndexedDBEvent,
WebSchedulerTrackedFeature::kKeyboardLock,
WebSchedulerTrackedFeature::kKeepaliveRequest,
WebSchedulerTrackedFeature::kOutstandingIndexedDBTransaction,
WebSchedulerTrackedFeature::kPaymentManager,
WebSchedulerTrackedFeature::kPictureInPicture,
WebSchedulerTrackedFeature::kPortal,
WebSchedulerTrackedFeature::kPrinting,
WebSchedulerTrackedFeature::kRequestedAudioCapturePermission,
WebSchedulerTrackedFeature::kRequestedBackForwardCacheBlockedSensors,
WebSchedulerTrackedFeature::kRequestedBackgroundWorkPermission,
WebSchedulerTrackedFeature::kRequestedMIDIPermission,
WebSchedulerTrackedFeature::kRequestedVideoCapturePermission,
WebSchedulerTrackedFeature::kSharedWorker,
WebSchedulerTrackedFeature::kSpeechRecognizer,
WebSchedulerTrackedFeature::kSpeechSynthesis,
WebSchedulerTrackedFeature::kWebDatabase,
WebSchedulerTrackedFeature::kWebHID,
WebSchedulerTrackedFeature::kWebLocks,
WebSchedulerTrackedFeature::kWebOTPService,
WebSchedulerTrackedFeature::kWebRTC,
WebSchedulerTrackedFeature::kWebShare,
WebSchedulerTrackedFeature::kWebSocket,
WebSchedulerTrackedFeature::kWebTransport,
WebSchedulerTrackedFeature::kWebXR);
constexpr WebSchedulerTrackedFeatures kInjectionFeatures(
WebSchedulerTrackedFeature::kInjectedJavascript,
WebSchedulerTrackedFeature::kInjectedStyleSheet);
constexpr WebSchedulerTrackedFeatures kNetworkFeatures(
WebSchedulerTrackedFeature::kOutstandingNetworkRequestOthers,
WebSchedulerTrackedFeature::kOutstandingNetworkRequestFetch,
WebSchedulerTrackedFeature::kOutstandingNetworkRequestXHR);
// A list of WebSchedulerTrackedFeatures that should never block back/forward
// cache.
constexpr WebSchedulerTrackedFeatures kAllowedFeatures(
WebSchedulerTrackedFeature::kDocumentLoaded,
WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoCache,
// This is handled in |UpdateCanStoreToIncludeCacheControlNoStore()|, and no
// need to include in |GetDisallowedFeatures()|.
WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoStore,
// TODO(crbug.com/1357482): Figure out if these two should be allowed.
WebSchedulerTrackedFeature::kOutstandingNetworkRequestDirectSocket,
WebSchedulerTrackedFeature::kRequestedStorageAccessGrant,
// We don't block on subresource cache-control:no-store or no-cache.
WebSchedulerTrackedFeature::kSubresourceHasCacheControlNoCache,
WebSchedulerTrackedFeature::kSubresourceHasCacheControlNoStore,
// We only record this if "Cache-Control: no-store" header is present on the
// main frame.
WebSchedulerTrackedFeature::kAuthorizationHeader,
// TODO(crbug.com/1357482): Figure out if this should be allowed.
WebSchedulerTrackedFeature::kWebNfc);
// The BackForwardCache feature is controlled via an experiment. This function
// returns the allowed URL list where it is enabled.
std::string GetAllowedURLList() {
// Avoid activating BackForwardCache trial for checking the parameters
// associated with it.
if (!IsBackForwardCacheEnabled()) {
if (base::FeatureList::IsEnabled(
kRecordBackForwardCacheMetricsWithoutEnabling)) {
return base::GetFieldTrialParamValueByFeature(
kRecordBackForwardCacheMetricsWithoutEnabling, "allowed_websites");
}
return "";
}
return base::GetFieldTrialParamValueByFeature(features::kBackForwardCache,
"allowed_websites");
}
// This function returns the blocked URL list.
std::string GetBlockedURLList() {
return IsBackForwardCacheEnabled()
? base::GetFieldTrialParamValueByFeature(
features::kBackForwardCache, "blocked_websites")
: "";
}
// Returns the list of blocked CGI params
std::string GetBlockedCgiParams() {
return IsBackForwardCacheEnabled()
? base::GetFieldTrialParamValueByFeature(
features::kBackForwardCache, "blocked_cgi_params")
: "";
}
// Parses the “allowed_websites” and "blocked_websites" field trial parameters
// and creates a map to represent hosts and corresponding path prefixes.
std::map<std::string, std::vector<std::string>> ParseCommaSeparatedURLs(
base::StringPiece comma_separated_urls) {
std::map<std::string, std::vector<std::string>> urls;
for (auto& it :
base::SplitString(comma_separated_urls, ",", base::TRIM_WHITESPACE,
base::SPLIT_WANT_ALL)) {
GURL url = GURL(it);
urls[url.host()].push_back(url.path());
}
return urls;
}
// Parses the "cgi_params" field trial parameter into a set by splitting on "|".
std::unordered_set<std::string> ParseBlockedCgiParams(
base::StringPiece cgi_params_string) {
std::vector<std::string> split =
base::SplitString(cgi_params_string, "|", base::TRIM_WHITESPACE,
base::SplitResult::SPLIT_WANT_NONEMPTY);
std::unordered_set<std::string> cgi_params;
cgi_params.insert(split.begin(), split.end());
return cgi_params;
}
BackForwardCacheTestDelegate* g_bfcache_disabled_test_observer = nullptr;
void RestoreBrowserControlsState(RenderFrameHostImpl* cached_rfh) {
auto* current_rfh =
cached_rfh->frame_tree_node()->render_manager()->current_frame_host();
DCHECK_NE(current_rfh, cached_rfh);
float prev_top_controls_shown_ratio = current_rfh->GetRenderWidgetHost()
->render_frame_metadata_provider()
->LastRenderFrameMetadata()
.top_controls_shown_ratio;
if (prev_top_controls_shown_ratio < 1) {
// Make sure the state in the restored renderer matches the current one.
// If we currently aren't showing the controls let the cached renderer
// know, so that it then reacts correctly to the SHOW controls message
// that might follow during DidCommitNavigation.
cached_rfh->GetPage().UpdateBrowserControlsState(
cc::BrowserControlsState::kBoth, cc::BrowserControlsState::kHidden,
// Do not animate as we want this to happen "instantaneously"
false);
}
}
void RequestRecordTimeToVisible(RenderFrameHostImpl* rfh,
base::TimeTicks navigation_start) {
// Make sure we record only when the frame is not in hidden state to avoid
// cases like page navigating back with window.history.back(), while being
// hidden.
if (rfh->delegate()->GetVisibility() != Visibility::HIDDEN) {
rfh->GetRenderWidgetHost()->GetVisibleTimeRequestTrigger().UpdateRequest(
navigation_start, /*destination_is_loaded=*/false,
/*show_reason_tab_switching=*/false,
/*show_reason_bfcache_restore=*/true);
}
}
// Returns true if any of the processes associated with the RenderViewHosts in
// this Entry are foregrounded.
bool HasForegroundedProcess(BackForwardCacheImpl::Entry& entry) {
for (const auto& rvh : entry.render_view_hosts()) {
if (!rvh->GetProcess()->IsProcessBackgrounded()) {
return true;
}
}
return false;
}
// Returns true if all of the RenderViewHosts in this Entry have received the
// acknowledgement from renderer.
bool AllRenderViewHostsReceivedAckFromRenderer(
BackForwardCacheImpl::Entry& entry) {
for (const auto& rvh : entry.render_view_hosts()) {
if (!rvh->DidReceiveBackForwardCacheAck()) {
return false;
}
}
return true;
}
// Behavior on pages with cache-control:no-store specified by flags.
enum class CacheControlNoStoreExperimentLevel {
// No experiments for cache-control:no-store are running.
kDoNotStore = 1,
// Only the metrics gathering experiment is on.
kStoreAndEvictUponRestore = 2,
// Restore the entry only when cookies have not changed while in cache.
kStoreAndRestoreUnlessCookieChange = 3,
// Restore the entry only when HTTP Only cookies have not changed while in
// cache.
kStoreAndRestoreUnlessHTTPOnlyCookieChange = 4,
};
const char kCacheControlNoStoreExperimentLevelName[] = "level";
static constexpr base::FeatureParam<CacheControlNoStoreExperimentLevel>::Option
cache_control_levels[] = {
{CacheControlNoStoreExperimentLevel::kStoreAndEvictUponRestore,
"store-and-evict"},
{CacheControlNoStoreExperimentLevel::kStoreAndRestoreUnlessCookieChange,
"restore-unless-cookie-change"},
{CacheControlNoStoreExperimentLevel::
kStoreAndRestoreUnlessHTTPOnlyCookieChange,
"restore-unless-http-only-cookie-change"},
};
const base::FeatureParam<CacheControlNoStoreExperimentLevel>
cache_control_level{&kCacheControlNoStoreEnterBackForwardCache,
kCacheControlNoStoreExperimentLevelName,
CacheControlNoStoreExperimentLevel::kDoNotStore,
&cache_control_levels};
CacheControlNoStoreExperimentLevel GetCacheControlNoStoreLevel() {
if (!IsBackForwardCacheEnabled() ||
!base::FeatureList::IsEnabled(
kCacheControlNoStoreEnterBackForwardCache)) {
return CacheControlNoStoreExperimentLevel::kDoNotStore;
}
return cache_control_level.Get();
}
bool IsSameOriginForTreeResult(RenderFrameHostImpl* rfh,
const GURL& url,
const url::Origin& main_document_origin) {
// Treat any frame inside a fenced frame as cross origin so we don't leak
// any information.
if (rfh->IsNestedWithinFencedFrame())
return false;
return url::Origin::Create(url).IsSameOriginWith(main_document_origin);
}
} // namespace
// static
BlockListedFeatures BackForwardCacheImpl::GetAllowedFeatures(
RequestedFeatures requested_features) {
WebSchedulerTrackedFeatures result = kAllowedFeatures;
if (IsContentInjectionSupported()) {
result.PutAll(kInjectionFeatures);
}
if (IgnoresOutstandingNetworkRequestForTesting()) {
result.PutAll(kNetworkFeatures);
}
result.PutAll(SupportedFeatures());
if (requested_features == RequestedFeatures::kOnlySticky) {
// Add non-sticky disallowed features.
WebSchedulerTrackedFeatures non_sticky =
Difference(kDisallowedFeatures, blink::scheduler::StickyFeatures());
if (!IsContentInjectionSupported()) {
non_sticky.PutAll(
Difference(kInjectionFeatures, blink::scheduler::StickyFeatures()));
}
if (!IgnoresOutstandingNetworkRequestForTesting()) {
non_sticky.PutAll(
Difference(kNetworkFeatures, blink::scheduler::StickyFeatures()));
}
result.PutAll(non_sticky);
}
return result;
}
// static
BlockListedFeatures BackForwardCacheImpl::GetDisallowedFeatures(
RequestedFeatures requested_features) {
WebSchedulerTrackedFeatures result = kDisallowedFeatures;
if (!IsContentInjectionSupported()) {
result.PutAll(kInjectionFeatures);
}
if (!IgnoresOutstandingNetworkRequestForTesting()) {
result.PutAll(kNetworkFeatures);
}
result.RemoveAll(SupportedFeatures());
if (requested_features == RequestedFeatures::kOnlySticky) {
// Remove all non-sticky features from |result|.
result = Intersection(result, blink::scheduler::StickyFeatures());
}
return result;
}
// static
BackForwardCacheImpl::MessageHandlingPolicyWhenCached
BackForwardCacheImpl::GetChannelAssociatedMessageHandlingPolicy() {
// Avoid activating BackForwardCache trial for checking the parameters
// associated with it.
if (!IsBackForwardCacheEnabled())
return kMessagePolicyNone;
static constexpr char kFieldTrialParam[] = "message_handling_when_cached";
auto param = base::GetFieldTrialParamValueByFeature(
features::kBackForwardCache, kFieldTrialParam);
if (param.empty() || param == "log") {
return kMessagePolicyLog;
} else if (param == "none") {
return kMessagePolicyNone;
} else if (param == "dump") {
return kMessagePolicyDump;
} else {
DLOG(WARNING) << "Failed to parse field trial param " << kFieldTrialParam
<< " with string value " << param
<< " under feature kBackForwardCache"
<< features::kBackForwardCache.name;
return kMessagePolicyLog;
}
}
BackForwardCacheImpl::Entry::Entry(std::unique_ptr<StoredPage> stored_page)
: stored_page_(std::move(stored_page)) {}
BackForwardCacheImpl::Entry::~Entry() = default;
void BackForwardCacheImpl::Entry::WriteIntoTrace(
perfetto::TracedValue context) {
auto dict = std::move(context).WriteDictionary();
dict.Add("render_frame_host", render_frame_host());
}
void BackForwardCacheImpl::RenderProcessBackgroundedChanged(
RenderProcessHostImpl* host) {
EnforceCacheSizeLimit();
}
BackForwardCacheTestDelegate::BackForwardCacheTestDelegate() {
DCHECK(!g_bfcache_disabled_test_observer);
g_bfcache_disabled_test_observer = this;
}
BackForwardCacheTestDelegate::~BackForwardCacheTestDelegate() {
DCHECK_EQ(g_bfcache_disabled_test_observer, this);
g_bfcache_disabled_test_observer = nullptr;
}
BackForwardCacheImpl::BackForwardCacheImpl()
: allowed_urls_(ParseCommaSeparatedURLs(GetAllowedURLList())),
blocked_urls_(ParseCommaSeparatedURLs(GetBlockedURLList())),
blocked_cgi_params_(ParseBlockedCgiParams(GetBlockedCgiParams())),
weak_factory_(this) {}
BackForwardCacheImpl::~BackForwardCacheImpl() {
Shutdown();
}
absl::optional<int> GetFieldTrialParamByFeatureAsOptionalInt(
const base::Feature& feature,
const std::string& param_name) {
std::string value_as_string =
GetFieldTrialParamValueByFeature(feature, param_name);
int value_as_int = 0;
if (base::StringToInt(value_as_string, &value_as_int)) {
return absl::optional<int>(value_as_int);
}
return absl::optional<int>();
}
base::TimeDelta BackForwardCacheImpl::GetTimeToLiveInBackForwardCache() {
// We use the following order of priority if multiple values exist:
// - The TTL set in `kBackForwardCacheTimeToLiveControl` takes precedence over
// the default value.
// - Infinite if kBackForwardCacheNoTimeEviction is enabled.
// - Default value otherwise, kDefaultTimeToLiveInBackForwardCacheInSeconds.
if (base::FeatureList::IsEnabled(
features::kBackForwardCacheTimeToLiveControl)) {
absl::optional<int> time_to_live = GetFieldTrialParamByFeatureAsOptionalInt(
features::kBackForwardCacheTimeToLiveControl, "time_to_live_seconds");
if (time_to_live.has_value()) {
return base::Seconds(time_to_live.value());
}
}
if (base::FeatureList::IsEnabled(kBackForwardCacheNoTimeEviction)) {
return base::TimeDelta::Max();
}
return base::Seconds(kDefaultTimeToLiveInBackForwardCacheInSeconds);
}
// static
size_t BackForwardCacheImpl::GetCacheSize() {
if (!IsBackForwardCacheEnabled())
return 0;
if (base::FeatureList::IsEnabled(kBackForwardCacheSize)) {
return kBackForwardCacheSizeCacheSize.Get();
}
return base::GetFieldTrialParamByFeatureAsInt(
features::kBackForwardCache, "cache_size", kDefaultBackForwardCacheSize);
}
// static
size_t BackForwardCacheImpl::GetForegroundedEntriesCacheSize() {
if (!IsBackForwardCacheEnabled())
return 0;
if (base::FeatureList::IsEnabled(kBackForwardCacheSize)) {
return kBackForwardCacheSizeForegroundCacheSize.Get();
}
return base::GetFieldTrialParamByFeatureAsInt(
features::kBackForwardCache, "foreground_cache_size",
kDefaultForegroundBackForwardCacheSize);
}
// static
bool BackForwardCacheImpl::UsingForegroundBackgroundCacheSizeLimit() {
return GetForegroundedEntriesCacheSize() > 0;
}
BackForwardCacheImpl::Entry* BackForwardCacheImpl::FindMatchingEntry(
PageImpl& page) {
RenderFrameHostImpl* render_frame_host = &page.GetMainDocument();
Entry* matching_entry = nullptr;
for (std::unique_ptr<Entry>& entry : entries_) {
if (render_frame_host == entry->render_frame_host()) {
matching_entry = entry.get();
break;
}
}
return matching_entry;
}
void BackForwardCacheImpl::UpdateCanStoreToIncludeCacheControlNoStore(
BackForwardCacheCanStoreDocumentResult& result,
RenderFrameHostImpl* render_frame_host) {
// If the feature is disabled, do nothing.
if (!AllowStoringPagesWithCacheControlNoStore())
return;
// If the page didn't have cache-control: no-store, do nothing.
if (!render_frame_host->GetBackForwardCacheDisablingFeatures().Has(
WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoStore)) {
return;
}
// Note that kCacheControlNoStoreHTTPOnlyCookieModified,
// kCacheControlNoStoreCookieModified and kCacheControlNoStore are mutually
// exclusive.
if (render_frame_host->GetCookieChangeInfo()
.http_only_cookie_modification_count_ > 0) {
result.No(BackForwardCacheMetrics::NotRestoredReason::
kCacheControlNoStoreHTTPOnlyCookieModified);
} else if (render_frame_host->GetCookieChangeInfo()
.cookie_modification_count_ > 0) {
// JavaScript cookies are modified but not HTTP cookies. Only restore based
// on the experiment level.
if (GetCacheControlNoStoreLevel() <=
CacheControlNoStoreExperimentLevel::
kStoreAndRestoreUnlessCookieChange) {
result.No(BackForwardCacheMetrics::NotRestoredReason::
kCacheControlNoStoreCookieModified);
}
} else if (GetCacheControlNoStoreLevel() ==
CacheControlNoStoreExperimentLevel::kStoreAndEvictUponRestore) {
result.No(BackForwardCacheMetrics::NotRestoredReason::kCacheControlNoStore);
}
}
namespace {
void LogAndTraceResult(
const RenderFrameHostImpl& rfh,
const BackForwardCacheCanStoreDocumentResult& flattened_result,
const perfetto::StaticString& caller) {
VLOG(1) << caller.value << ": " << rfh.GetLastCommittedURL() << " : "
<< flattened_result.ToString();
TRACE_EVENT("navigation", caller,
ChromeTrackEvent::kBackForwardCacheCanStoreDocumentResult,
flattened_result);
}
} // namespace
BackForwardCacheCanStoreDocumentResultWithTree
BackForwardCacheImpl::GetCurrentBackForwardCacheEligibility(
RenderFrameHostImpl* rfh) {
BackForwardCacheCanStoreDocumentResult flattened;
auto result =
PopulateReasonsForPage(rfh, flattened, RequestedFeatures::kAllIfAcked);
LogAndTraceResult(
*rfh, result.flattened_reasons,
"BackForwardCacheImpl::GetCurrentBackForwardCacheEligibility");
return result;
}
BackForwardCacheCanStoreDocumentResultWithTree
BackForwardCacheImpl::GetCompleteBackForwardCacheEligibilityForReporting(
RenderFrameHostImpl* rfh) {
BackForwardCacheCanStoreDocumentResult flattened;
auto result = PopulateReasonsForPage(rfh, flattened, RequestedFeatures::kAll);
LogAndTraceResult(*rfh, result.flattened_reasons,
"BackForwardCacheImpl::"
"GetCompleteBackForwardCacheEligibilityForReporting");
return result;
}
BackForwardCacheCanStoreDocumentResultWithTree
BackForwardCacheImpl::GetFutureBackForwardCacheEligibilityPotential(
RenderFrameHostImpl* rfh) {
BackForwardCacheCanStoreDocumentResult flattened;
auto result =
PopulateReasonsForPage(rfh, flattened, RequestedFeatures::kOnlySticky);
LogAndTraceResult(
*rfh, result.flattened_reasons,
"BackForwardCacheImpl::GetFutureBackForwardCacheEligibilityPotential");
return result;
}
BackForwardCacheCanStoreDocumentResultWithTree
BackForwardCacheImpl::PopulateReasonsForPage(
RenderFrameHostImpl* rfh,
BackForwardCacheCanStoreDocumentResult& flattened_result,
RequestedFeatures requested_features) {
// TODO(crbug.com/1275977): This function should only be called when |rfh| is
// the primary main frame. Fix |ShouldProactivelySwapBrowsingInstance()| and
// |UnloadOldFrame()| so that it will not check bfcache eligibility if not
// primary main frame.
BackForwardCacheCanStoreDocumentResult main_document_specific_result;
// This function can be called during eviction, and |rfh| can be in
// back/forward cache, which is considered as non primary main frame.
bool main_frame_in_bfcache =
rfh->IsInBackForwardCache() && rfh->IsOutermostMainFrame();
// Call the recursive function that adds the reasons from the subtree to the
// flattened list, and return the tree if needed.
std::unique_ptr<BackForwardCacheCanStoreTreeResult> result_tree;
if (!rfh->IsInPrimaryMainFrame() && !main_frame_in_bfcache) {
// When |rfh| is not the primary main frame and is not the bfcache main
// frame, e.g. when |rfh| is prerendering, fenced frame root or is not the
// main frame, we can reach this block.
// We do not need to check the subframes' reasons because callers that reach
// here only care about whether can_store is true or false, not about the
// reasons.
main_document_specific_result.No(
BackForwardCacheMetrics::NotRestoredReason::kNotPrimaryMainFrame);
result_tree = BackForwardCacheCanStoreTreeResult::CreateEmptyTree(rfh);
} else {
// Populate main document specific reasons.
PopulateReasonsForMainDocument(main_document_specific_result, rfh);
NotRestoredReasonBuilder builder(rfh, requested_features);
result_tree = builder.GetTreeResult();
flattened_result.AddReasonsFrom(builder.GetFlattenedResult());
}
// Add the reasons for main document to the flattened list.
flattened_result.AddReasonsFrom(main_document_specific_result);
// |result_tree| does not have main document specific reasons such as
// "disabled via command line", and we have to manually add them.
result_tree->AddReasonsToSubtreeRootFrom(main_document_specific_result);
DCHECK_EQ(flattened_result, result_tree->FlattenTree());
return BackForwardCacheCanStoreDocumentResultWithTree(flattened_result,
std::move(result_tree));
}
void BackForwardCacheImpl::PopulateReasonsForMainDocument(
BackForwardCacheCanStoreDocumentResult& result,
RenderFrameHostImpl* rfh) {
bool main_frame_in_bfcache =
rfh->IsInBackForwardCache() && rfh->IsOutermostMainFrame();
DCHECK(rfh->IsInPrimaryMainFrame() || main_frame_in_bfcache);
// If the the delegate doesn't support back forward cache, disable it.
if (!rfh->delegate()->IsBackForwardCacheSupported()) {
result.No(BackForwardCacheMetrics::NotRestoredReason::
kBackForwardCacheDisabledForDelegate);
}
if (!IsBackForwardCacheEnabled() || is_disabled_for_testing_) {
result.No(
BackForwardCacheMetrics::NotRestoredReason::kBackForwardCacheDisabled);
// In addition to the general "BackForwardCacheDisabled" reason above, also
// track more specific reasons on why BackForwardCache is disabled.
if (IsBackForwardCacheDisabledByCommandLine()) {
result.No(BackForwardCacheMetrics::NotRestoredReason::
kBackForwardCacheDisabledByCommandLine);
}
if (!DeviceHasEnoughMemoryForBackForwardCache()) {
result.No(BackForwardCacheMetrics::NotRestoredReason::
kBackForwardCacheDisabledByLowMemory);
}
}
// If this function is called after we navigated to a new RenderFrameHost,
// then |rfh| must already be replaced by the new RenderFrameHost. If this
// function is called before we navigated, then |rfh| must be an active
// RenderFrameHost.
bool is_active_rfh = rfh->IsActive();
// Two pages in the same BrowsingInstance can script each other. When a page
// can be scripted from outside, it can't enter the BackForwardCache.
//
// If the |rfh| is not an "active" RenderFrameHost anymore, the
// "RelatedActiveContentsCount" below is compared against 0, not 1. This is
// because |rfh| is not "active" itself.
//
// This check makes sure the old and new document aren't sharing the same
// BrowsingInstance. Note that the existence of related active contents might
// change in the future, but we are checking this in
// GetFutureBackForwardCacheEligibilityPotential instead of
// GetCurrentBackForwardCacheEligibility because it's needed to determine
// whether to do a proactive BrowsingInstance swap or not, which should not be
// done if the page has related active contents.
unsigned expected_related_active_contents_count = is_active_rfh ? 1 : 0;
// We should never have fewer than expected.
DCHECK_GE(rfh->GetSiteInstance()->GetRelatedActiveContentsCount(),
expected_related_active_contents_count);
if (rfh->GetSiteInstance()->GetRelatedActiveContentsCount() >
expected_related_active_contents_count) {
absl::optional<ShouldSwapBrowsingInstance> browsing_instance_swap_result;
if (auto* metrics = rfh->GetBackForwardCacheMetrics())
browsing_instance_swap_result = metrics->browsing_instance_swap_result();
result.NoDueToRelatedActiveContents(browsing_instance_swap_result);
}
// Only store documents that have successful http status code.
// Note that for error pages, |last_http_status_code| is equal to 0.
if (rfh->last_http_status_code() != net::HTTP_OK)
result.No(BackForwardCacheMetrics::NotRestoredReason::kHTTPStatusNotOK);
// Interstitials and other internal error pages should set an error status
// code but there's no guarantee, e.g. https://crbug/1274308,
// https://crbug/1287996. This catches those cases. It might also make the
// kHTTPStatusNotOK check redundant.
if (rfh->IsErrorDocument())
result.No(BackForwardCacheMetrics::NotRestoredReason::kErrorDocument);
// Only store documents that were fetched via HTTP GET method.
if (rfh->last_http_method() != net::HttpRequestHeaders::kGetMethod)
result.No(BackForwardCacheMetrics::NotRestoredReason::kHTTPMethodNotGET);
// Only store documents that have a valid network::mojom::URLResponseHead.
// We actually don't know the actual case this reason is solely set without
// kHTTPStatusNotOK and kSchemeNotHTTPOrHTTPS, but crash reports imply it
// happens.
// TODO(https://crbug.com/1216997): Understand the case and remove
// DebugScenario::kDebugNoResponseHeadForHTTPOrHTTPS.
if (!rfh->last_response_head())
result.No(BackForwardCacheMetrics::NotRestoredReason::kNoResponseHead);
// Do not store main document with non HTTP/HTTPS URL scheme. Among other
// things, this excludes the new tab page and all WebUI pages.
if (!rfh->GetLastCommittedURL().SchemeIsHTTPOrHTTPS()) {
result.No(
BackForwardCacheMetrics::NotRestoredReason::kSchemeNotHTTPOrHTTPS);
}
// We should not cache pages with Cache-control: no-store. Note that
// even though this is categorized as a "feature", we will check this within
// GetFutureBackForwardCacheEligibilityPotential as it's not possible to
// change the HTTP headers, so if it's not possible to cache this page now due
// to this, it's impossible to cache this page later.
// TODO(rakina): Once we move cache-control tracking to RenderFrameHostImpl,
// change this part to use the information stored in RenderFrameHostImpl
// instead.
if (rfh->GetBackForwardCacheDisablingFeatures().Has(
WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoStore)) {
if (!AllowStoringPagesWithCacheControlNoStore()) {
// Block pages with cache-control: no-store only when
// |should_cache_control_no_store_enter| flag is false. If true, put the
// page in and evict later.
result.NoDueToFeatures(
WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoStore);
}
}
// Only store documents that have URLs allowed through experiment.
if (!IsAllowed(rfh->GetLastCommittedURL()))
result.No(BackForwardCacheMetrics::NotRestoredReason::kDomainNotAllowed);
}
void BackForwardCacheImpl::NotRestoredReasonBuilder::
PopulateStickyReasonsForDocument(
BackForwardCacheCanStoreDocumentResult& result,
RenderFrameHostImpl* rfh) {
// If the rfh has ever granted media access, prevent it from entering cache.
// TODO(crbug.com/989379): Consider only blocking when there's an active
// media stream.
if (rfh->was_granted_media_access()) {
result.No(
BackForwardCacheMetrics::NotRestoredReason::kWasGrantedMediaAccess);
}
if (rfh->IsBackForwardCacheDisabled() && !ShouldIgnoreBlocklists()) {
result.NoDueToDisableForRenderFrameHostCalled(
rfh->back_forward_cache_disabled_reasons());
}
// Do not store documents if they have inner WebContents. Inner frame trees
// that are based on MPArch are allowed to be stored. To determine if this
// is an inner WebContents we check the inner frame tree's type to see if
// it is `kPrimary`.
if (rfh->frame_tree()->delegate()->GetOuterDelegateFrameTreeNodeId() !=
FrameTreeNode::kFrameTreeNodeInvalidId &&
rfh->frame_tree()->type() == FrameTree::Type::kPrimary) {
result.No(BackForwardCacheMetrics::NotRestoredReason::kHaveInnerContents);
}
if (!IsUnloadAllowed()) {
const bool has_unload_handler = rfh->has_unload_handler();
if (has_unload_handler) {
// Note that pages with unload handlers are cached on android.
result.No(rfh->GetParent() ? BackForwardCacheMetrics::NotRestoredReason::
kUnloadHandlerExistsInSubFrame
: BackForwardCacheMetrics::NotRestoredReason::
kUnloadHandlerExistsInMainFrame);
}
}
// When it's not the final decision for putting a page in the back-forward
// cache, we should only consider "sticky" features here - features that
// will always result in a page becoming ineligible for back-forward cache
// since the first time it's used.
WebSchedulerTrackedFeatures banned_features =
Intersection(GetDisallowedFeatures(RequestedFeatures::kOnlySticky),
rfh->GetBackForwardCacheDisablingFeatures());
if (!banned_features.Empty()) {
if (!ShouldIgnoreBlocklists()) {
result.NoDueToFeatures(banned_features);
}
}
// If the main document had CCNS and this document is same-origin with the
// main document and used the "Authorization" header then add that reason.
// This does not use `IsSameOriginForTreeResult` because we want to be more
// conservative and react to *any* same-origin frame using it.
if (root_rfh_->GetBackForwardCacheDisablingFeatures().Has(
WebSchedulerTrackedFeature::kMainResourceHasCacheControlNoStore) &&
rfh->GetLastCommittedOrigin().IsSameOriginWith(
root_rfh_->GetLastCommittedOrigin()) &&
rfh->GetBackForwardCacheDisablingFeatures().Has(
WebSchedulerTrackedFeature::kAuthorizationHeader)) {
result.NoDueToFeatures(WebSchedulerTrackedFeature::kAuthorizationHeader);
}
}
void BackForwardCacheImpl::NotRestoredReasonBuilder::
PopulateNonStickyReasonsForDocument(
BackForwardCacheCanStoreDocumentResult& result,
RenderFrameHostImpl* rfh,
RequestedFeatures requested_features) {
DCHECK_NE(requested_features, RequestedFeatures::kOnlySticky);
// The DOM content must have finished loading, except when there is
// no DOM content to load when the RFH has not committed any navigation.
if (!rfh->IsDOMContentLoaded() && rfh->has_committed_any_navigation()) {
result.No(BackForwardCacheMetrics::NotRestoredReason::kLoading);
}
// Check for non-sticky features that are present at the moment.
WebSchedulerTrackedFeatures banned_features =
Intersection(GetDisallowedFeatures(RequestedFeatures::kAll),
rfh->GetBackForwardCacheDisablingFeatures());
if (!banned_features.Empty() && !ShouldIgnoreBlocklists()) {
if (requested_features == RequestedFeatures::kAll ||
(requested_features == RequestedFeatures::kAllIfAcked &&
rfh->render_view_host()->DidReceiveBackForwardCacheAck())) {
result.NoDueToFeatures(banned_features);
}
}
// Do not cache if we have navigations in any of the subframes.
if (rfh->GetParentOrOuterDocument() &&
rfh->frame_tree_node()->HasNavigation()) {
result.No(
BackForwardCacheMetrics::NotRestoredReason::kSubframeIsNavigating);
}
}
void BackForwardCacheImpl::NotRestoredReasonBuilder::PopulateReasonsForDocument(
BackForwardCacheCanStoreDocumentResult& result,
RenderFrameHostImpl* rfh,
RequestedFeatures requested_features) {
PopulateStickyReasonsForDocument(result, rfh);
if (requested_features != RequestedFeatures::kOnlySticky) {
PopulateNonStickyReasonsForDocument(result, rfh, requested_features);
}
}
BackForwardCacheCanStoreDocumentResultWithTree
BackForwardCacheImpl::CreateEvictionBackForwardCacheCanStoreTreeResult(
RenderFrameHostImpl& rfh,
BackForwardCacheCanStoreDocumentResult& eviction_reason) {
// At this point the page already has some NotRestoredReasons for eviction, so
// we should always record cache_control:no-store related reasons.
BackForwardCacheImpl::NotRestoredReasonBuilder builder(
rfh.GetOutermostMainFrame(),
/* requested_features = */ RequestedFeatures::kOnlySticky,
BackForwardCacheImpl::NotRestoredReasonBuilder::EvictionInfo(
rfh, &eviction_reason));
BackForwardCacheCanStoreDocumentResult flattened_result =
builder.GetFlattenedResult();
LogAndTraceResult(
rfh, flattened_result,
"BackForwardCacheImpl::CreateEvictionBackForwardCacheCanStoreTreeResult");
return BackForwardCacheCanStoreDocumentResultWithTree(
flattened_result, builder.GetTreeResult());
}
BackForwardCacheImpl::NotRestoredReasonBuilder::NotRestoredReasonBuilder(
RenderFrameHostImpl* root_rfh,
RequestedFeatures requested_features)
: NotRestoredReasonBuilder(root_rfh,
requested_features,
/* eviction_info = */ absl::nullopt) {}
BackForwardCacheImpl::NotRestoredReasonBuilder::NotRestoredReasonBuilder(
RenderFrameHostImpl* root_rfh,
RequestedFeatures requested_features,
absl::optional<EvictionInfo> eviction_info)
: root_rfh_(root_rfh),
bfcache_(root_rfh_->frame_tree_node()
->navigator()
.controller()
.GetBackForwardCache()),
requested_features_(requested_features),
eviction_info_(eviction_info) {
// |root_rfh_| should be either primary main frame or back/forward cached
// page's outermost main frame.
DCHECK(
root_rfh_->IsInPrimaryMainFrame() ||
(root_rfh_->IsInBackForwardCache() && root_rfh_->IsOutermostMainFrame()));
// Populate the reasons and build the tree.
std::map<RenderFrameHostImpl*, BackForwardCacheCanStoreTreeResult*>
parent_map;
root_rfh_->ForEachRenderFrameHost([&](RenderFrameHostImpl* rfh) {
auto rfh_result = PopulateReasons(rfh);
parent_map[rfh] = rfh_result.get();