-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
frame_loader.cc
1774 lines (1551 loc) · 74.5 KB
/
frame_loader.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 (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights
* reserved.
* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved.
* (http://www.torchmobile.com/)
* Copyright (C) 2008 Alp Toker <alp@atoker.com>
* Copyright (C) Research In Motion Limited 2009. All rights reserved.
* Copyright (C) 2011 Kris Jordan <krisjordan@gmail.com>
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include <memory>
#include <utility>
#include "base/auto_reset.h"
#include "base/trace_event/typed_macros.h"
#include "base/unguessable_token.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/web_sandbox_flags.h"
#include "services/network/public/mojom/web_sandbox_flags.mojom-blink.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "third_party/blink/public/common/user_agent/user_agent_metadata.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/mojom/frame/frame.mojom-blink.h"
#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h"
#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature_state.mojom-blink.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/public/web/web_frame_load_type.h"
#include "third_party/blink/public/web/web_history_item.h"
#include "third_party/blink/public/web/web_navigation_params.h"
#include "third_party/blink/public/web/web_navigation_type.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/core/dom/document_init.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/ignore_opens_during_unload_count_incrementer.h"
#include "third_party/blink/renderer/core/events/page_transition_event.h"
#include "third_party/blink/renderer/core/exported/web_plugin_container_impl.h"
#include "third_party/blink/renderer/core/fragment_directive/text_fragment_anchor.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/csp/csp_source.h"
#include "third_party/blink/renderer/core/frame/frame_console.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/policy_container.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/inspector/identifiers_factory.h"
#include "third_party/blink/renderer/core/loader/document_load_timing.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/loader/form_submission.h"
#include "third_party/blink/renderer/core/loader/frame_load_request.h"
#include "third_party/blink/renderer/core/loader/frame_loader_types.h"
#include "third_party/blink/renderer/core/loader/idna_util.h"
#include "third_party/blink/renderer/core/loader/mixed_content_checker.h"
#include "third_party/blink/renderer/core/loader/progress_tracker.h"
#include "third_party/blink/renderer/core/navigation_api/navigation_api.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/frame_tree.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/plugin_data.h"
#include "third_party/blink/renderer/core/page/plugin_script_forbidden_scope.h"
#include "third_party/blink/renderer/core/page/scrolling/fragment_anchor.h"
#include "third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.h"
#include "third_party/blink/renderer/core/page/viewport_description.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/scroll/scroll_animator_base.h"
#include "third_party/blink/renderer/core/svg/graphics/svg_image.h"
#include "third_party/blink/renderer/core/xml/parser/xml_document_parser.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h"
#include "third_party/blink/renderer/platform/bindings/v8_dom_activity_logger.h"
#include "third_party/blink/renderer/platform/exported/wrapped_resource_request.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/mhtml/archive_resource.h"
#include "third_party/blink/renderer/platform/mhtml/mhtml_archive.h"
#include "third_party/blink/renderer/platform/network/http_parsers.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h"
#include "third_party/blink/renderer/platform/network/network_utils.h"
#include "third_party/blink/renderer/platform/runtime_feature_state/runtime_feature_state_override_context.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
namespace {
void LogJavaScriptUrlHistogram(LocalDOMWindow* origin_window, String script) {
origin_window->CountUse(WebFeature::kExecutedJavaScriptURLFromFrame);
if (script.length() > 6) {
return;
}
script = script.StripWhiteSpace().Replace(";", "");
if (script == "''" || script == "\"\"") {
origin_window->CountUse(WebFeature::kExecutedEmptyJavaScriptURLFromFrame);
}
}
} // namespace
bool IsBackForwardLoadType(WebFrameLoadType type) {
return type == WebFrameLoadType::kBackForward;
}
bool IsReloadLoadType(WebFrameLoadType type) {
return type == WebFrameLoadType::kReload ||
type == WebFrameLoadType::kReloadBypassingCache;
}
bool FrameLoader::NeedsHistoryItemRestore(WebFrameLoadType type) {
return type == WebFrameLoadType::kBackForward || IsReloadLoadType(type);
}
ResourceRequest FrameLoader::ResourceRequestForReload(
WebFrameLoadType frame_load_type,
ClientRedirectPolicy client_redirect_policy) {
DCHECK(IsReloadLoadType(frame_load_type));
const auto cache_mode =
frame_load_type == WebFrameLoadType::kReloadBypassingCache
? mojom::FetchCacheMode::kBypassCache
: mojom::FetchCacheMode::kValidateCache;
if (!document_loader_ || !document_loader_->GetHistoryItem())
return ResourceRequest();
ResourceRequest request =
document_loader_->GetHistoryItem()->GenerateResourceRequest(cache_mode);
// ClientRedirectPolicy is an indication that this load was triggered by some
// direct interaction with the page. If this reload is not a client redirect,
// we should reuse the referrer from the original load of the current
// document. If this reload is a client redirect (e.g., location.reload()), it
// was initiated by something in the current document and should therefore
// show the current document's url as the referrer.
if (client_redirect_policy == ClientRedirectPolicy::kClientRedirect) {
LocalDOMWindow* window = frame_->DomWindow();
Referrer referrer = SecurityPolicy::GenerateReferrer(
window->GetReferrerPolicy(), window->Url(), window->OutgoingReferrer());
request.SetReferrerString(referrer.referrer);
request.SetReferrerPolicy(referrer.referrer_policy);
}
request.SetSkipServiceWorker(frame_load_type ==
WebFrameLoadType::kReloadBypassingCache);
return request;
}
FrameLoader::FrameLoader(LocalFrame* frame)
: frame_(frame),
progress_tracker_(MakeGarbageCollected<ProgressTracker>(frame)),
dispatching_did_clear_window_object_in_main_world_(false),
virtual_time_pauser_(
frame_->GetFrameScheduler()->CreateWebScopedVirtualTimePauser(
"FrameLoader",
WebScopedVirtualTimePauser::VirtualTaskDuration::kInstant)) {
DCHECK(frame_);
TRACE_EVENT_OBJECT_CREATED_WITH_ID("loading", "FrameLoader", this);
TakeObjectSnapshot();
}
FrameLoader::~FrameLoader() {
DCHECK_EQ(state_, State::kDetached);
}
void FrameLoader::Trace(Visitor* visitor) const {
visitor->Trace(frame_);
visitor->Trace(progress_tracker_);
visitor->Trace(document_loader_);
}
void FrameLoader::Init(const DocumentToken& document_token,
std::unique_ptr<PolicyContainer> policy_container,
const StorageKey& storage_key,
ukm::SourceId document_ukm_source_id) {
DCHECK(policy_container);
ScriptForbiddenScope forbid_scripts;
// Load the initial empty document:
auto navigation_params = std::make_unique<WebNavigationParams>();
navigation_params->url = KURL(g_empty_string);
navigation_params->storage_key = storage_key;
navigation_params->document_token = document_token;
navigation_params->frame_policy =
frame_->Owner() ? frame_->Owner()->GetFramePolicy() : FramePolicy();
navigation_params->document_ukm_source_id = document_ukm_source_id;
DocumentLoader* new_document_loader = MakeGarbageCollected<DocumentLoader>(
frame_, kWebNavigationTypeOther, std::move(navigation_params),
std::move(policy_container), nullptr /* extra_data */);
CommitDocumentLoader(new_document_loader, nullptr,
CommitReason::kInitialization);
frame_->GetDocument()->CancelParsing();
// Suppress finish notifications for initial empty documents, since they don't
// generate start notifications.
document_loader_->SetSentDidFinishLoad();
// Ensure that the frame sees the correct page lifecycle state.
frame_->OnPageLifecycleStateUpdated();
TakeObjectSnapshot();
state_ = State::kInitialized;
}
LocalFrameClient* FrameLoader::Client() const {
return frame_->Client();
}
ClientRedirectPolicy CalculateClientRedirectPolicy(
ClientNavigationReason client_navigation_reason,
WebFrameLoadType frame_load_type,
bool is_on_initial_empty_document) {
if (is_on_initial_empty_document ||
client_navigation_reason == ClientNavigationReason::kNone ||
client_navigation_reason == ClientNavigationReason::kFormSubmissionGet ||
client_navigation_reason == ClientNavigationReason::kFormSubmissionPost ||
client_navigation_reason == ClientNavigationReason::kAnchorClick) {
// Navigations away from the initial empty document and some types of
// navigations like form submission shouldn't be considered as client
// redirects, because they're not actually caused by a script redirecting to
// a different URL.
return ClientRedirectPolicy::kNotClientRedirect;
}
// If the ClientRedirectReason is kFrameNavigation, only treat as a client
// redirect if the WebFrameLoadType is kReplaceCurrentItem. If this check is
// not applied, an anchor location change is classified as client redirect
// and an incorrect redirect chain is formed. On deleting one entry of this
// redirect chain, the whole chain gets deleted. This result in
// deletion of multiple items on deleting one item in history.
// https://crbug.com/1138096
if (client_navigation_reason == ClientNavigationReason::kFrameNavigation &&
frame_load_type != WebFrameLoadType::kReplaceCurrentItem)
return ClientRedirectPolicy::kNotClientRedirect;
return ClientRedirectPolicy::kClientRedirect;
}
void FrameLoader::SetDefersLoading(LoaderFreezeMode mode) {
if (frame_->GetDocument())
frame_->GetDocument()->Fetcher()->SetDefersLoading(mode);
if (document_loader_)
document_loader_->SetDefersLoading(mode);
}
void FrameLoader::SaveScrollAnchor() {
if (!document_loader_ || !document_loader_->GetHistoryItem() ||
!frame_->View())
return;
// Shouldn't clobber anything if we might still restore later.
if (NeedsHistoryItemRestore(document_loader_->LoadType()) &&
!document_loader_->GetInitialScrollState().was_scrolled_by_user)
return;
HistoryItem* history_item = document_loader_->GetHistoryItem();
if (ScrollableArea* layout_scrollable_area =
frame_->View()->LayoutViewport()) {
ScrollAnchor* scroll_anchor = layout_scrollable_area->GetScrollAnchor();
DCHECK(scroll_anchor);
const SerializedAnchor& serialized_anchor =
scroll_anchor->GetSerializedAnchor();
if (serialized_anchor.IsValid()) {
history_item->SetScrollAnchorData(
{serialized_anchor.selector,
gfx::PointF(serialized_anchor.relative_offset.X(),
serialized_anchor.relative_offset.Y()),
serialized_anchor.simhash});
}
}
}
void FrameLoader::SaveScrollState() {
if (!document_loader_ || !document_loader_->GetHistoryItem() ||
!frame_->View())
return;
// Shouldn't clobber anything if we might still restore later.
if (NeedsHistoryItemRestore(document_loader_->LoadType()) &&
!document_loader_->GetInitialScrollState().was_scrolled_by_user)
return;
HistoryItem* history_item = document_loader_->GetHistoryItem();
// For performance reasons, we don't save scroll anchors as often as we save
// scroll offsets. In order to avoid keeping around a stale anchor, we clear
// it when the saved scroll offset changes.
history_item->SetScrollAnchorData(ScrollAnchorData());
if (ScrollableArea* layout_scrollable_area = frame_->View()->LayoutViewport())
history_item->SetScrollOffset(layout_scrollable_area->GetScrollOffset());
VisualViewport& visual_viewport = frame_->GetPage()->GetVisualViewport();
if (frame_->IsMainFrame() && visual_viewport.IsActiveViewport()) {
history_item->SetVisualViewportScrollOffset(
visual_viewport.VisibleRect().OffsetFromOrigin());
history_item->SetPageScaleFactor(visual_viewport.Scale());
}
Client()->DidUpdateCurrentHistoryItem();
}
void FrameLoader::DispatchUnloadEventAndFillOldDocumentInfoIfNeeded(
bool will_commit_new_document_in_this_frame) {
FrameNavigationDisabler navigation_disabler(*frame_);
SaveScrollState();
if (SVGImage::IsInSVGImage(frame_->GetDocument()))
return;
// Only fill in the info of the unloading document if it is needed for a new
// document committing in this frame (either due to frame swap or committing
// a new document in the same FrameLoader). This avoids overwriting the info
// saved of a parent frame that's already saved in
// ScopedOldDocumentInfoForCommitCapturer when a child frame is being
// destroyed due to the parent frame committing. In that case, only the parent
// frame needs should fill in the info.
OldDocumentInfoForCommit* old_document_info =
ScopedOldDocumentInfoForCommitCapturer::CurrentInfo();
if (!old_document_info || !will_commit_new_document_in_this_frame) {
frame_->GetDocument()->DispatchUnloadEvents(nullptr);
return;
}
old_document_info->history_item = GetDocumentLoader()->GetHistoryItem();
old_document_info->had_sticky_activation_before_navigation =
frame_->HadStickyUserActivationBeforeNavigation();
frame_->GetDocument()->DispatchUnloadEvents(
&old_document_info->unload_timing_info);
}
void FrameLoader::DidExplicitOpen() {
probe::DidOpenDocument(frame_, GetDocumentLoader());
if (initial_empty_document_status_ ==
InitialEmptyDocumentStatus::kInitialOrSynchronousAboutBlank) {
initial_empty_document_status_ = InitialEmptyDocumentStatus::
kInitialOrSynchronousAboutBlankButExplicitlyOpened;
}
// Only model a document.open() as part of a navigation if its parent is not
// done or in the process of completing.
if (Frame* parent = frame_->Tree().Parent()) {
auto* parent_local_frame = DynamicTo<LocalFrame>(parent);
if ((parent_local_frame &&
parent_local_frame->GetDocument()->LoadEventStillNeeded()) ||
(parent->IsRemoteFrame() && parent->IsLoading())) {
progress_tracker_->ProgressStarted();
}
}
}
void FrameLoader::FinishedParsing() {
if (state_ == State::kUninitialized)
return;
progress_tracker_->FinishedParsing();
frame_->GetLocalFrameHostRemote().DidDispatchDOMContentLoadedEvent();
if (Client()) {
ScriptForbiddenScope forbid_scripts;
Client()->DispatchDidDispatchDOMContentLoadedEvent();
}
if (Client()) {
Client()->RunScriptsAtDocumentReady(
document_loader_ ? document_loader_->IsCommittedButEmpty() : true);
}
if (frame_->View()) {
ProcessFragment(frame_->GetDocument()->Url(), document_loader_->LoadType(),
kNavigationToDifferentDocument);
}
frame_->GetDocument()->CheckCompleted();
}
// TODO(dgozman): we are calling this method too often, hoping that it
// does not do anything when navigation is in progress, or when loading
// has finished already. We should call it at the right times.
void FrameLoader::DidFinishNavigation(NavigationFinishState state) {
if (document_loader_) {
// Only declare the whole frame finished if the committed navigation is done
// and there is no provisional navigation in progress.
// The navigation API may prevent a navigation from completing while waiting
// for a JS-provided promise to resolve, so check it as well.
if (!document_loader_->SentDidFinishLoad() || HasProvisionalNavigation())
return;
if (frame_->DomWindow()->navigation()->HasNonDroppedOngoingNavigation())
return;
}
// This code in this block is meant to prepare a document for display, but
// this code may also run when swapping out a provisional frame. In that case,
// skip the display work.
if (frame_->IsLoading() && !frame_->IsProvisional()) {
progress_tracker_->ProgressCompleted();
// Retry restoring scroll offset since finishing loading disables content
// size clamping.
RestoreScrollPositionAndViewState();
if (document_loader_)
document_loader_->SetLoadType(WebFrameLoadType::kStandard);
frame_->FinishedLoading(state);
}
// When a subframe finishes loading, the parent should check if *all*
// subframes have finished loading (which may mean that the parent can declare
// that the parent itself has finished loading). This local-subframe-focused
// code has a remote-subframe equivalent in
// WebRemoteFrameImpl::DidStopLoading.
Frame* parent = frame_->Tree().Parent();
if (parent)
parent->CheckCompleted();
}
Frame* FrameLoader::Opener() {
return frame_->Opener();
}
void FrameLoader::SetOpener(LocalFrame* opener) {
// If the frame is already detached, the opener has already been cleared.
frame_->SetOpener(opener);
}
bool FrameLoader::AllowPlugins() {
// With Oilpan, a FrameLoader might be accessed after the Page has been
// detached. FrameClient will not be accessible, so bail early.
if (!Client())
return false;
Settings* settings = frame_->GetSettings();
return settings && settings->GetPluginsEnabled();
}
void FrameLoader::DetachDocumentLoader(Member<DocumentLoader>& loader,
bool flush_microtask_queue) {
if (!loader)
return;
FrameNavigationDisabler navigation_disabler(*frame_);
loader->DetachFromFrame(flush_microtask_queue);
loader = nullptr;
}
void FrameLoader::ProcessScrollForSameDocumentNavigation(
const KURL& url,
WebFrameLoadType frame_load_type,
absl::optional<HistoryItem::ViewState> view_state,
mojom::blink::ScrollRestorationType scroll_restoration_type) {
if (view_state) {
RestoreScrollPositionAndViewState(frame_load_type, *view_state,
scroll_restoration_type);
}
// We need to scroll to the fragment whether or not a hash change occurred,
// since the user might have scrolled since the previous navigation.
ProcessFragment(url, frame_load_type, kNavigationWithinSameDocument);
TakeObjectSnapshot();
}
bool FrameLoader::AllowRequestForThisFrame(const FrameLoadRequest& request) {
// If no origin Document* was specified, skip remaining security checks and
// assume the caller has fully initialized the FrameLoadRequest.
if (!request.GetOriginWindow())
return true;
const KURL& url = request.GetResourceRequest().Url();
if (url.ProtocolIsJavaScript()) {
if (request.GetOriginWindow()
->CheckAndGetJavascriptUrl(request.JavascriptWorld().get(), url,
frame_->DeprecatedLocalOwner())
.empty()) {
return false;
}
if (frame_->Owner() && ((frame_->Owner()->GetFramePolicy().sandbox_flags &
network::mojom::blink::WebSandboxFlags::kOrigin) !=
network::mojom::blink::WebSandboxFlags::kNone)) {
return false;
}
}
if (!request.CanDisplay(url)) {
request.GetOriginWindow()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kError,
"Not allowed to load local resource: " + url.ElidedString()));
return false;
}
return true;
}
static WebNavigationType DetermineNavigationType(
WebFrameLoadType frame_load_type,
bool is_form_submission,
bool have_event) {
bool is_reload = IsReloadLoadType(frame_load_type);
bool is_back_forward = IsBackForwardLoadType(frame_load_type);
if (is_form_submission) {
if (is_reload)
return kWebNavigationTypeFormResubmittedReload;
if (is_back_forward)
return kWebNavigationTypeFormResubmittedBackForward;
return kWebNavigationTypeFormSubmitted;
}
if (have_event)
return kWebNavigationTypeLinkClicked;
if (is_reload)
return kWebNavigationTypeReload;
if (is_back_forward)
return kWebNavigationTypeBackForward;
return kWebNavigationTypeOther;
}
static mojom::blink::RequestContextType
DetermineRequestContextFromNavigationType(
const WebNavigationType navigation_type) {
switch (navigation_type) {
case kWebNavigationTypeLinkClicked:
return mojom::blink::RequestContextType::HYPERLINK;
case kWebNavigationTypeOther:
return mojom::blink::RequestContextType::LOCATION;
case kWebNavigationTypeFormResubmittedBackForward:
case kWebNavigationTypeFormResubmittedReload:
case kWebNavigationTypeFormSubmitted:
return mojom::blink::RequestContextType::FORM;
case kWebNavigationTypeBackForward:
case kWebNavigationTypeReload:
return mojom::blink::RequestContextType::INTERNAL;
}
NOTREACHED();
return mojom::blink::RequestContextType::HYPERLINK;
}
static network::mojom::RequestDestination
DetermineRequestDestinationFromNavigationType(
const WebNavigationType navigation_type) {
switch (navigation_type) {
case kWebNavigationTypeLinkClicked:
case kWebNavigationTypeOther:
case kWebNavigationTypeFormResubmittedBackForward:
case kWebNavigationTypeFormResubmittedReload:
case kWebNavigationTypeFormSubmitted:
return network::mojom::RequestDestination::kDocument;
case kWebNavigationTypeBackForward:
case kWebNavigationTypeReload:
return network::mojom::RequestDestination::kEmpty;
}
NOTREACHED();
return network::mojom::RequestDestination::kDocument;
}
void FrameLoader::StartNavigation(FrameLoadRequest& request,
WebFrameLoadType frame_load_type) {
CHECK(!IsBackForwardLoadType(frame_load_type));
DCHECK(request.GetTriggeringEventInfo() !=
mojom::blink::TriggeringEventInfo::kUnknown);
DCHECK(frame_->GetDocument());
if (HTMLFrameOwnerElement* element = frame_->DeprecatedLocalOwner())
element->CancelPendingLazyLoad();
ResourceRequest& resource_request = request.GetResourceRequest();
const KURL& url = resource_request.Url();
LocalDOMWindow* origin_window = request.GetOriginWindow();
TRACE_EVENT2("navigation", "FrameLoader::StartNavigation", "url",
url.GetString().Utf8(), "load_type",
static_cast<int>(frame_load_type));
resource_request.SetHasUserGesture(
LocalFrame::HasTransientUserActivation(frame_));
if (!AllowRequestForThisFrame(request))
return;
// Block renderer-initiated loads of filesystem: URLs not in a Chrome App.
if (!base::FeatureList::IsEnabled(
features::kFileSystemUrlNavigationForChromeAppsOnly) &&
url.ProtocolIs("filesystem") &&
!base::FeatureList::IsEnabled(features::kFileSystemUrlNavigation)) {
frame_->GetDocument()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kSecurity,
mojom::blink::ConsoleMessageLevel::kError,
"Not allowed to navigate to " + url.Protocol() +
" URL: " + url.ElidedString()));
return;
}
// Block renderer-initiated loads of data: and filesystem: URLs in the top
// frame (unless they are reload requests).
//
// If the mime type of the data URL is supported, the URL will
// eventually be rendered, so block it here. Otherwise, the load might be
// handled by a plugin or end up as a download, so allow it to let the
// embedder figure out what to do with it. Navigations to filesystem URLs are
// always blocked here.
if (frame_->IsMainFrame() && origin_window &&
request.ClientRedirectReason() != ClientNavigationReason::kReload &&
!frame_->Client()->AllowContentInitiatedDataUrlNavigations(
origin_window->Url()) &&
(url.ProtocolIs("filesystem") ||
(url.ProtocolIsData() &&
network_utils::IsDataURLMimeTypeSupported(url)))) {
frame_->GetDocument()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kSecurity,
mojom::blink::ConsoleMessageLevel::kError,
"Not allowed to navigate top frame to " + url.Protocol() +
" URL: " + url.ElidedString()));
return;
}
// TODO(dgozman): merge page dismissal check and FrameNavigationDisabler.
if (!frame_->IsNavigationAllowed() ||
frame_->GetDocument()->PageDismissalEventBeingDispatched() !=
Document::kNoDismissal) {
return;
}
if (url.ProtocolIs("filesystem")) {
document_loader_->CountUse(
mojom::blink::WebFeature::kFileSystemUrlNavigation);
}
// Convert navigations from the initial empty document to do replacement if
// needed. Note that we don't convert reloads or history navigations (so only
// kStandard navigations can get converted to do replacement).
if (frame_load_type == WebFrameLoadType::kStandard &&
IsOnInitialEmptyDocument()) {
frame_load_type = WebFrameLoadType::kReplaceCurrentItem;
}
bool same_document_navigation =
request.GetNavigationPolicy() == kNavigationPolicyCurrentTab &&
ShouldPerformFragmentNavigation(
request.Form(), resource_request.HttpMethod(), frame_load_type, url);
// Perform same document navigation.
if (same_document_navigation) {
DCHECK(origin_window);
document_loader_->CommitSameDocumentNavigation(
url, frame_load_type, nullptr,
CalculateClientRedirectPolicy(request.ClientRedirectReason(),
frame_load_type,
IsOnInitialEmptyDocument()),
resource_request.HasUserGesture(), origin_window->GetSecurityOrigin(),
/*is_synchronously_committed=*/true, request.GetTriggeringEventInfo(),
/*is_browser_initiated=*/false,
/*soft_navigation_heuristics_task_id=*/absl::nullopt);
return;
}
// If we're navigating and there's still a text fragment permission token on
// the document loader, it means this navigation didn't try to invoke a text
// fragment. In this case, we want to propagate this to the next document to
// allow text-fragments across client-side redirects.
bool text_fragment_token = GetDocumentLoader()->ConsumeTextFragmentToken();
resource_request.SetHasTextFragmentToken(text_fragment_token);
WebNavigationType navigation_type = DetermineNavigationType(
frame_load_type, resource_request.HttpBody() || request.Form(),
request.GetTriggeringEventInfo() !=
mojom::blink::TriggeringEventInfo::kNotFromEvent);
mojom::blink::RequestContextType request_context_type =
DetermineRequestContextFromNavigationType(navigation_type);
// TODO(lyf): handle `frame` context type. https://crbug.com/1019716
if (mojom::blink::RequestContextType::LOCATION == request_context_type &&
!frame_->IsMainFrame()) {
request_context_type = mojom::blink::RequestContextType::IFRAME;
}
resource_request.SetRequestContext(request_context_type);
resource_request.SetRequestDestination(
DetermineRequestDestinationFromNavigationType(navigation_type));
request.SetFrameType(frame_->IsMainFrame()
? mojom::RequestContextFrameType::kTopLevel
: mojom::RequestContextFrameType::kNested);
// TODO(arthursonzogni): 'frame-src' check is disabled on the
// renderer side, but is enforced on the browser side.
// See http://crbug.com/692595 for understanding why it
// can't be enforced on both sides instead.
// 'form-action' check in the frame that is navigating is disabled on the
// renderer side, but is enforced on the browser side instead.
// N.B. check in the frame that initiates the navigation stills occurs in
// blink and is not enforced on the browser-side.
// TODO(arthursonzogni) The 'form-action' check should be fully disabled
// in blink, except when the form submission doesn't trigger a navigation
// (i.e. javascript urls). Please see https://crbug.com/701749.
// Report-only CSP headers are checked in browser.
const FetchClientSettingsObject* fetch_client_settings_object = nullptr;
if (origin_window) {
fetch_client_settings_object = &origin_window->Fetcher()
->GetProperties()
.GetFetchClientSettingsObject();
}
ModifyRequestForCSP(resource_request, fetch_client_settings_object,
origin_window, request.GetFrameType());
DCHECK(Client()->HasWebView());
// Check for non-escaped new lines in the url.
if (url.PotentiallyDanglingMarkup() && url.ProtocolIsInHTTPFamily()) {
Deprecation::CountDeprecation(
origin_window, WebFeature::kCanRequestURLHTTPContainingNewline);
return;
}
if (url.ProtocolIsJavaScript()) {
if (!origin_window ||
origin_window->CanExecuteScripts(kAboutToExecuteScript)) {
if (origin_window && request.GetFrameType() ==
mojom::blink::RequestContextFrameType::kNested) {
LogJavaScriptUrlHistogram(origin_window, url.GetPath());
}
frame_->GetDocument()->ProcessJavaScriptUrl(url,
request.JavascriptWorld());
}
return;
}
if (request.GetNavigationPolicy() == kNavigationPolicyCurrentTab &&
(!origin_window || origin_window->GetSecurityOrigin()->CanAccess(
frame_->DomWindow()->GetSecurityOrigin()))) {
auto* params = MakeGarbageCollected<NavigateEventDispatchParams>(
url, NavigateEventType::kCrossDocument, frame_load_type);
params->form = request.Form();
if (request.GetTriggeringEventInfo() ==
mojom::blink::TriggeringEventInfo::kFromTrustedEvent) {
params->involvement = UserNavigationInvolvement::kActivation;
}
if (frame_->DomWindow()->navigation()->DispatchNavigateEvent(params) !=
NavigationApi::DispatchResult::kContinue) {
return;
}
}
if (frame_->IsMainFrame())
LocalFrame::ConsumeTransientUserActivation(frame_);
// The main resource request gets logged here, because V8DOMActivityLogger
// is looked up based on the current v8::Context. When the request actually
// begins, the v8::Context may no longer be on the stack.
if (V8DOMActivityLogger* activity_logger =
V8DOMActivityLogger::CurrentActivityLoggerIfIsolatedWorld()) {
if (!DocumentLoader::WillLoadUrlAsEmpty(url)) {
Vector<String> argv;
argv.push_back("Main resource");
argv.push_back(url.GetString());
activity_logger->LogEvent("blinkRequestResource", argv.size(),
argv.data());
}
}
if (request.ClientRedirectReason() != ClientNavigationReason::kNone) {
probe::FrameRequestedNavigation(frame_, frame_, url,
request.ClientRedirectReason(),
request.GetNavigationPolicy());
}
// TODO(crbug.com/896041): Instead of just bypassing the CSP for navigations
// from isolated world, ideally we should enforce the isolated world CSP by
// plumbing the correct CSP to the browser.
using CSPDisposition = network::mojom::CSPDisposition;
CSPDisposition should_check_main_world_csp =
ContentSecurityPolicy::ShouldBypassMainWorldDeprecated(
request.JavascriptWorld().get())
? CSPDisposition::DO_NOT_CHECK
: CSPDisposition::CHECK;
// If this is a subframe load to a uuid-in-package: URL, allow loading from a
// Web Bundle attached to the parent document.
if (url.Protocol() == "uuid-in-package") {
auto* parent_local_frame = DynamicTo<LocalFrame>(frame_->Tree().Parent());
if (parent_local_frame &&
parent_local_frame->DomWindow() == origin_window &&
origin_window->Fetcher()) {
origin_window->Fetcher()->AttachWebBundleTokenIfNeeded(resource_request);
// Report to the UseCounter of the parent frame (i.e. the frame that
// loaded a WebBundle).
origin_window->CountUse(
mojom::blink::WebFeature::kUuidInPackageUrlNavigation);
}
}
// Warn if the resource URL's hostname contains IDNA deviation characters.
// Only warn if the resource URL's origin is different than its requestor
// (we don't want to warn for <img src="faß.de/image.img"> on faß.de).
// TODO(crbug.com/1396475): Remove once Non-Transitional mode is shipped.
if (resource_request.RequestorOrigin() &&
!resource_request.RequestorOrigin()->IsSameOriginWith(
SecurityOrigin::Create(url).get()) &&
url.HasIDNA2008DeviationCharacter()) {
String message = GetConsoleWarningForIDNADeviationCharacters(url);
if (!message.empty()) {
request.GetOriginWindow()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kWarning, message));
origin_window->CountUse(
WebFeature::kIDNA2008DeviationCharacterInHostnameOfIFrame);
}
}
Client()->BeginNavigation(
resource_request, request.GetRequestorBaseURL(), request.GetFrameType(),
origin_window, nullptr /* document_loader */, navigation_type,
request.GetNavigationPolicy(), frame_load_type,
request.ForceHistoryPush(),
CalculateClientRedirectPolicy(
request.ClientRedirectReason(), frame_load_type,
IsOnInitialEmptyDocument()) == ClientRedirectPolicy::kClientRedirect,
request.IsUnfencedTopNavigation(), request.GetTriggeringEventInfo(),
request.Form(), should_check_main_world_csp, request.GetBlobURLToken(),
request.GetInputStartTime(), request.HrefTranslate().GetString(),
request.Impression(), request.GetInitiatorFrameToken(),
request.TakeSourceLocation(),
request.TakeInitiatorPolicyContainerKeepAliveHandle(),
request.IsContainerInitiated());
}
static void FillStaticResponseIfNeeded(WebNavigationParams* params,
LocalFrame* frame) {
if (params->is_static_data)
return;
const KURL& url = params->url;
// See WebNavigationParams for special case explanations.
if (url.IsAboutSrcdocURL()) {
CHECK(params->body_loader);
// Originally, this branch was responsible for retrieving the value of the
// srcdoc attribute and turning it into a body loader when committing a
// navigation to about:srcdoc. To support out-of-process sandboxed iframes,
// the value of the srcdoc attribute is now sent to the browser in
// BeginNavigation, and the body loader should have already been created
// by the time the browser asks the renderer to commit, like other
// standard navigations.
return;
}
MHTMLArchive* archive = nullptr;
if (auto* parent = DynamicTo<LocalFrame>(frame->Tree().Parent()))
archive = parent->Loader().GetDocumentLoader()->Archive();
if (archive && !url.ProtocolIsData()) {
// If we have an archive loaded in some ancestor frame, we should
// retrieve document content from that archive. This is different from
// loading an archive into this frame, which will be handled separately
// once we load the body and parse it as an archive.
params->body_loader.reset();
ArchiveResource* archive_resource = archive->SubresourceForURL(url);
if (archive_resource) {
SharedBuffer* archive_data = archive_resource->Data();
WebNavigationParams::FillStaticResponse(
params, archive_resource->MimeType(),
archive_resource->TextEncoding(),
base::make_span(archive_data->Data(), archive_data->size()));
} else {
// The requested archive resource does not exist. In an ideal world, this
// would commit as a failed navigation, but the browser doesn't know
// anything about what resources are available in the archive. Just
// synthesize an empty document so that something commits still.
// TODO(https://crbug.com/1112965): remove these special cases by adding
// an URLLoaderFactory implementation for MHTML archives.
WebNavigationParams::FillStaticResponse(
params, "text/html", "UTF-8",
"<html><body>"
"<!-- failed to find resource in MHTML archive -->"
"</body></html>");
}
}
// Checking whether a URL would load as empty (e.g. about:blank) must be done
// after checking for content with the corresponding URL in the MHTML archive,
// since MHTML archives can define custom content to load for about:blank...
//
// Note that no static response needs to be filled here; instead, this is
// synthesised later by `DocumentLoader::InitializeEmptyResponse()`.
if (DocumentLoader::WillLoadUrlAsEmpty(params->url))
return;
const String& mime_type = params->response.MimeType();
if (MIMETypeRegistry::IsSupportedMIMEType(mime_type))
return;
PluginData* plugin_data = frame->GetPluginData();
if (!mime_type.empty() && plugin_data &&
plugin_data->SupportsMimeType(mime_type)) {
return;
}
// Typically, PlzNavigate checks that the MIME type can be handled on the
// browser side before sending it to the renderer. However, there are rare
// scenarios where it's possible for the renderer to send a commit request
// with a MIME type the renderer cannot handle:
//
// - (hypothetical) some sort of race between enabling/disabling plugins
// and when it's checked by the navigation URL loader / handled in the
// renderer.
// - mobile emulation disables plugins on the renderer side, but the browser
// navigation code is not aware of this.
//
// Similar to the missing archive resource case above, synthesise a resource
// to commit.
//
// WebNavigationParams::FillStaticResponse() fills the response of |params|
// using |params|'s |url| which is the initial URL even after redirections. So
// updates the URL to the current URL before calling FillStaticResponse().
params->url = params->response.CurrentRequestUrl();
WebNavigationParams::FillStaticResponse(
params, "text/html", "UTF-8",
"<html><body>"
"<!-- no enabled plugin supports this MIME type -->"
"</body></html>");
}
// The browser navigation code should never send a `CommitNavigation()` request
// that fails this check.
static void AssertCanNavigate(WebNavigationParams* params, LocalFrame* frame) {
if (params->is_static_data)
return;
if (DocumentLoader::WillLoadUrlAsEmpty(params->url))
return;
int status_code = params->response.HttpStatusCode();
// If the server sends 204 or 205, this means the server does not want to
// replace the page contents. However, PlzNavigate should have handled it
// browser-side and never sent a commit request to the renderer.
if (status_code == 204 || status_code == 205)
CHECK(false);
// If the server attached a Content-Disposition indicating that the resource
// is an attachment, this is actually a download. However, PlzNavigate should
// have handled it browser-side and never sent a commit request to the
// renderer.
if (IsContentDispositionAttachment(
params->response.HttpHeaderField(http_names::kContentDisposition))) {
CHECK(false);
}
}