forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDocumentLoadListener.cpp
2544 lines (2195 loc) · 95 KB
/
DocumentLoadListener.cpp
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et tw=80 : */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "DocumentLoadListener.h"
#include "mozilla/AntiTrackingUtils.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/MozPromiseInlines.h" // For MozPromise::FromDomPromise
#include "mozilla/ScopeExit.h"
#include "mozilla/StaticPrefs_extensions.h"
#include "mozilla/StaticPrefs_fission.h"
#include "mozilla/StaticPrefs_security.h"
#include "mozilla/dom/BrowserParent.h"
#include "mozilla/dom/BrowsingContextGroup.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/ChildProcessChannelListener.h"
#include "mozilla/dom/ClientChannelHelper.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/ContentProcessManager.h"
#include "mozilla/dom/SessionHistoryEntry.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "mozilla/dom/ipc/IdType.h"
#include "mozilla/net/CookieJarSettings.h"
#include "mozilla/net/HttpChannelParent.h"
#include "mozilla/net/RedirectChannelRegistrar.h"
#include "nsContentSecurityUtils.h"
#include "nsDocShell.h"
#include "nsDocShellLoadState.h"
#include "nsDocShellLoadTypes.h"
#include "nsDOMNavigationTiming.h"
#include "nsExternalHelperAppService.h"
#include "nsHttpChannel.h"
#include "nsIBrowser.h"
#include "nsIE10SUtils.h"
#include "nsIHttpChannelInternal.h"
#include "nsIStreamConverterService.h"
#include "nsIViewSourceChannel.h"
#include "nsImportModule.h"
#include "nsIXULRuntime.h"
#include "nsMimeTypes.h"
#include "nsQueryObject.h"
#include "nsRedirectHistoryEntry.h"
#include "nsSandboxFlags.h"
#include "nsStringStream.h"
#include "nsURILoader.h"
#include "nsWebNavigationInfo.h"
#include "mozilla/dom/BrowserParent.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/nsHTTPSOnlyUtils.h"
#include "mozilla/dom/RemoteWebProgress.h"
#include "mozilla/dom/RemoteWebProgressRequest.h"
#include "mozilla/net/UrlClassifierFeatureFactory.h"
#include "mozilla/ExtensionPolicyService.h"
#ifdef ANDROID
# include "mozilla/widget/nsWindow.h"
#endif /* ANDROID */
mozilla::LazyLogModule gDocumentChannelLog("DocumentChannel");
#define LOG(fmt) MOZ_LOG(gDocumentChannelLog, mozilla::LogLevel::Verbose, fmt)
using namespace mozilla::dom;
namespace mozilla {
namespace net {
static void SetNeedToAddURIVisit(nsIChannel* aChannel,
bool aNeedToAddURIVisit) {
nsCOMPtr<nsIWritablePropertyBag2> props(do_QueryInterface(aChannel));
if (!props) {
return;
}
props->SetPropertyAsBool(u"docshell.needToAddURIVisit"_ns,
aNeedToAddURIVisit);
}
static auto SecurityFlagsForLoadInfo(nsDocShellLoadState* aLoadState)
-> nsSecurityFlags {
// TODO: Block copied from nsDocShell::DoURILoad, refactor out somewhere
nsSecurityFlags securityFlags =
nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL;
if (aLoadState->LoadType() == LOAD_ERROR_PAGE) {
securityFlags |= nsILoadInfo::SEC_LOAD_ERROR_PAGE;
}
if (aLoadState->PrincipalToInherit()) {
bool isSrcdoc =
aLoadState->HasLoadFlags(nsDocShell::INTERNAL_LOAD_FLAGS_IS_SRCDOC);
bool inheritAttrs = nsContentUtils::ChannelShouldInheritPrincipal(
aLoadState->PrincipalToInherit(), aLoadState->URI(),
true, // aInheritForAboutBlank
isSrcdoc);
bool isData = SchemeIsData(aLoadState->URI());
if (inheritAttrs && !isData) {
securityFlags |= nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL;
}
}
return securityFlags;
}
// Construct a LoadInfo object to use when creating the internal channel for a
// Document/SubDocument load.
static auto CreateDocumentLoadInfo(CanonicalBrowsingContext* aBrowsingContext,
nsDocShellLoadState* aLoadState)
-> already_AddRefed<LoadInfo> {
uint32_t sandboxFlags = aBrowsingContext->GetSandboxFlags();
RefPtr<LoadInfo> loadInfo;
auto securityFlags = SecurityFlagsForLoadInfo(aLoadState);
if (aBrowsingContext->GetParent()) {
loadInfo = LoadInfo::CreateForFrame(aBrowsingContext,
aLoadState->TriggeringPrincipal(),
securityFlags, sandboxFlags);
} else {
OriginAttributes attrs;
aBrowsingContext->GetOriginAttributes(attrs);
loadInfo = LoadInfo::CreateForDocument(aBrowsingContext,
aLoadState->TriggeringPrincipal(),
attrs, securityFlags, sandboxFlags);
}
loadInfo->SetTriggeringSandboxFlags(aLoadState->TriggeringSandboxFlags());
loadInfo->SetHasValidUserGestureActivation(
aLoadState->HasValidUserGestureActivation());
return loadInfo.forget();
}
// Construct a LoadInfo object to use when creating the internal channel for an
// Object/Embed load.
static auto CreateObjectLoadInfo(nsDocShellLoadState* aLoadState,
uint64_t aInnerWindowId,
nsContentPolicyType aContentPolicyType,
uint32_t aSandboxFlags)
-> already_AddRefed<LoadInfo> {
RefPtr<WindowGlobalParent> wgp =
WindowGlobalParent::GetByInnerWindowId(aInnerWindowId);
MOZ_RELEASE_ASSERT(wgp);
auto securityFlags = SecurityFlagsForLoadInfo(aLoadState);
RefPtr<LoadInfo> loadInfo = LoadInfo::CreateForNonDocument(
wgp, wgp->DocumentPrincipal(), aContentPolicyType, securityFlags,
aSandboxFlags);
loadInfo->SetHasValidUserGestureActivation(
aLoadState->HasValidUserGestureActivation());
loadInfo->SetTriggeringSandboxFlags(aLoadState->TriggeringSandboxFlags());
return loadInfo.forget();
}
static auto WebProgressForBrowsingContext(
CanonicalBrowsingContext* aBrowsingContext)
-> already_AddRefed<BrowsingContextWebProgress> {
return RefPtr<BrowsingContextWebProgress>(aBrowsingContext->GetWebProgress())
.forget();
}
/**
* An extension to nsDocumentOpenInfo that we run in the parent process, so
* that we can make the decision to retarget to content handlers or the external
* helper app, before we make process switching decisions.
*
* This modifies the behaviour of nsDocumentOpenInfo so that it can do
* retargeting, but doesn't do stream conversion (but confirms that we will be
* able to do so later).
*
* We still run nsDocumentOpenInfo in the content process, but disable
* retargeting, so that it can only apply stream conversion, and then send data
* to the docshell.
*/
class ParentProcessDocumentOpenInfo final : public nsDocumentOpenInfo,
public nsIMultiPartChannelListener {
public:
ParentProcessDocumentOpenInfo(ParentChannelListener* aListener,
uint32_t aFlags,
mozilla::dom::BrowsingContext* aBrowsingContext,
bool aIsDocumentLoad)
: nsDocumentOpenInfo(aFlags, false),
mBrowsingContext(aBrowsingContext),
mListener(aListener),
mIsDocumentLoad(aIsDocumentLoad) {
LOG(("ParentProcessDocumentOpenInfo ctor [this=%p]", this));
}
NS_DECL_ISUPPORTS_INHERITED
// The default content listener is always a docshell, so this manually
// implements the same checks, and if it succeeds, uses the parent
// channel listener so that we forward onto DocumentLoadListener.
bool TryDefaultContentListener(nsIChannel* aChannel,
const nsCString& aContentType) {
uint32_t canHandle = nsWebNavigationInfo::IsTypeSupported(
aContentType, mBrowsingContext->GetAllowPlugins());
if (canHandle != nsIWebNavigationInfo::UNSUPPORTED) {
m_targetStreamListener = mListener;
nsLoadFlags loadFlags = 0;
aChannel->GetLoadFlags(&loadFlags);
aChannel->SetLoadFlags(loadFlags | nsIChannel::LOAD_TARGETED);
return true;
}
return false;
}
bool TryDefaultContentListener(nsIChannel* aChannel) override {
return TryDefaultContentListener(aChannel, mContentType);
}
// Generally we only support stream converters that can tell
// use exactly what type they'll output. If we find one, then
// we just target to our default listener directly (without
// conversion), and the content process nsDocumentOpenInfo will
// run and do the actual conversion.
nsresult TryStreamConversion(nsIChannel* aChannel) override {
// The one exception is nsUnknownDecoder, which works in the parent
// (and we need to know what the content type is before we can
// decide if it will be handled in the parent), so we run that here.
if (mContentType.LowerCaseEqualsASCII(UNKNOWN_CONTENT_TYPE)) {
return nsDocumentOpenInfo::TryStreamConversion(aChannel);
}
nsresult rv;
nsCOMPtr<nsIStreamConverterService> streamConvService =
do_GetService(NS_STREAMCONVERTERSERVICE_CONTRACTID, &rv);
nsAutoCString str;
rv = streamConvService->ConvertedType(mContentType, aChannel, str);
NS_ENSURE_SUCCESS(rv, rv);
// We only support passing data to the default content listener
// (docshell), and we don't supported chaining converters.
if (TryDefaultContentListener(aChannel, str)) {
mContentType = str;
return NS_OK;
}
// This is the same result as nsStreamConverterService uses when it
// can't find a converter
return NS_ERROR_FAILURE;
}
nsresult TryExternalHelperApp(nsIExternalHelperAppService* aHelperAppService,
nsIChannel* aChannel) override {
RefPtr<nsIStreamListener> listener;
nsresult rv = aHelperAppService->CreateListener(
mContentType, aChannel, mBrowsingContext, false, nullptr,
getter_AddRefs(listener));
if (NS_SUCCEEDED(rv)) {
m_targetStreamListener = listener;
}
return rv;
}
nsDocumentOpenInfo* Clone() override {
mCloned = true;
return new ParentProcessDocumentOpenInfo(mListener, mFlags,
mBrowsingContext, mIsDocumentLoad);
}
nsresult OnDocumentStartRequest(nsIRequest* request) {
LOG(("ParentProcessDocumentOpenInfo OnDocumentStartRequest [this=%p]",
this));
nsresult rv = nsDocumentOpenInfo::OnStartRequest(request);
// If we didn't find a content handler,
// and we don't have a listener, then just forward to our
// default listener. This happens when the channel is in
// an error state, and we want to just forward that on to be
// handled in the content process.
if (NS_SUCCEEDED(rv) && !mUsedContentHandler && !m_targetStreamListener) {
m_targetStreamListener = mListener;
return m_targetStreamListener->OnStartRequest(request);
}
if (m_targetStreamListener != mListener) {
LOG(
("ParentProcessDocumentOpenInfo targeted to non-default listener "
"[this=%p]",
this));
// If this is the only part, then we can immediately tell our listener
// that it won't be getting any content and disconnect it. For multipart
// channels we have to wait until we've handled all parts before we know.
// This does mean that the content process can still Cancel() a multipart
// response while the response is being handled externally, but this
// matches the single-process behaviour.
// If we got cloned, then we don't need to do this, as only the last link
// needs to do it.
// Multi-part channels are guaranteed to call OnAfterLastPart, which we
// forward to the listeners, so it will handle disconnection at that
// point.
nsCOMPtr<nsIMultiPartChannel> multiPartChannel =
do_QueryInterface(request);
if (!multiPartChannel && !mCloned) {
DisconnectChildListeners(NS_FAILED(rv) ? rv : NS_BINDING_RETARGETED,
rv);
}
}
return rv;
}
nsresult OnObjectStartRequest(nsIRequest* request) {
LOG(("ParentProcessDocumentOpenInfo OnObjectStartRequest [this=%p]", this));
// Just redirect to the nsObjectLoadingContent in the content process.
m_targetStreamListener = mListener;
return m_targetStreamListener->OnStartRequest(request);
}
NS_IMETHOD OnStartRequest(nsIRequest* request) override {
LOG(("ParentProcessDocumentOpenInfo OnStartRequest [this=%p]", this));
if (mIsDocumentLoad) {
return OnDocumentStartRequest(request);
}
return OnObjectStartRequest(request);
}
NS_IMETHOD OnAfterLastPart(nsresult aStatus) override {
mListener->OnAfterLastPart(aStatus);
return NS_OK;
}
private:
virtual ~ParentProcessDocumentOpenInfo() {
LOG(("ParentProcessDocumentOpenInfo dtor [this=%p]", this));
}
void DisconnectChildListeners(nsresult aStatus, nsresult aLoadGroupStatus) {
// Tell the DocumentLoadListener to notify the content process that it's
// been entirely retargeted, and to stop waiting.
// Clear mListener's pointer to the DocumentLoadListener to break the
// reference cycle.
RefPtr<DocumentLoadListener> doc = do_GetInterface(ToSupports(mListener));
MOZ_ASSERT(doc);
doc->DisconnectListeners(aStatus, aLoadGroupStatus);
mListener->SetListenerAfterRedirect(nullptr);
}
RefPtr<mozilla::dom::BrowsingContext> mBrowsingContext;
RefPtr<ParentChannelListener> mListener;
const bool mIsDocumentLoad;
/**
* Set to true if we got cloned to create a chained listener.
*/
bool mCloned = false;
};
NS_IMPL_ADDREF_INHERITED(ParentProcessDocumentOpenInfo, nsDocumentOpenInfo)
NS_IMPL_RELEASE_INHERITED(ParentProcessDocumentOpenInfo, nsDocumentOpenInfo)
NS_INTERFACE_MAP_BEGIN(ParentProcessDocumentOpenInfo)
NS_INTERFACE_MAP_ENTRY(nsIMultiPartChannelListener)
NS_INTERFACE_MAP_END_INHERITING(nsDocumentOpenInfo)
NS_IMPL_ADDREF(DocumentLoadListener)
NS_IMPL_RELEASE(DocumentLoadListener)
NS_INTERFACE_MAP_BEGIN(DocumentLoadListener)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIInterfaceRequestor)
NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
NS_INTERFACE_MAP_ENTRY(nsIParentChannel)
NS_INTERFACE_MAP_ENTRY(nsIAsyncVerifyRedirectReadyCallback)
NS_INTERFACE_MAP_ENTRY(nsIChannelEventSink)
NS_INTERFACE_MAP_ENTRY(nsIMultiPartChannelListener)
NS_INTERFACE_MAP_ENTRY(nsIProgressEventSink)
NS_INTERFACE_MAP_ENTRY_CONCRETE(DocumentLoadListener)
NS_INTERFACE_MAP_END
DocumentLoadListener::DocumentLoadListener(
CanonicalBrowsingContext* aLoadingBrowsingContext, bool aIsDocumentLoad)
: mIsDocumentLoad(aIsDocumentLoad) {
LOG(("DocumentLoadListener ctor [this=%p]", this));
mParentChannelListener =
new ParentChannelListener(this, aLoadingBrowsingContext,
aLoadingBrowsingContext->UsePrivateBrowsing());
}
DocumentLoadListener::~DocumentLoadListener() {
LOG(("DocumentLoadListener dtor [this=%p]", this));
}
void DocumentLoadListener::AddURIVisit(nsIChannel* aChannel,
uint32_t aLoadFlags) {
if (mLoadStateLoadType == LOAD_ERROR_PAGE ||
mLoadStateLoadType == LOAD_BYPASS_HISTORY) {
return;
}
nsCOMPtr<nsIURI> uri;
NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
nsCOMPtr<nsIURI> previousURI;
uint32_t previousFlags = 0;
if (mLoadStateLoadType & nsIDocShell::LOAD_CMD_RELOAD) {
previousURI = uri;
} else {
nsDocShell::ExtractLastVisit(aChannel, getter_AddRefs(previousURI),
&previousFlags);
}
// Get the HTTP response code, if available.
uint32_t responseStatus = 0;
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aChannel);
if (httpChannel) {
Unused << httpChannel->GetResponseStatus(&responseStatus);
}
RefPtr<CanonicalBrowsingContext> browsingContext =
GetDocumentBrowsingContext();
nsCOMPtr<nsIWidget> widget =
browsingContext->GetParentProcessWidgetContaining();
nsDocShell::InternalAddURIVisit(uri, previousURI, previousFlags,
responseStatus, browsingContext, widget,
mLoadStateLoadType);
}
CanonicalBrowsingContext* DocumentLoadListener::GetLoadingBrowsingContext()
const {
return mParentChannelListener ? mParentChannelListener->GetBrowsingContext()
: nullptr;
}
CanonicalBrowsingContext* DocumentLoadListener::GetDocumentBrowsingContext()
const {
return mIsDocumentLoad ? GetLoadingBrowsingContext() : nullptr;
}
CanonicalBrowsingContext* DocumentLoadListener::GetTopBrowsingContext() const {
auto* loadingContext = GetLoadingBrowsingContext();
return loadingContext ? loadingContext->Top() : nullptr;
}
WindowGlobalParent* DocumentLoadListener::GetParentWindowContext() const {
return mParentWindowContext;
}
auto DocumentLoadListener::Open(nsDocShellLoadState* aLoadState,
LoadInfo* aLoadInfo, nsLoadFlags aLoadFlags,
uint32_t aCacheKey,
const Maybe<uint64_t>& aChannelId,
const TimeStamp& aAsyncOpenTime,
nsDOMNavigationTiming* aTiming,
Maybe<ClientInfo>&& aInfo, bool aUrgentStart,
base::ProcessId aPid, nsresult* aRv)
-> RefPtr<OpenPromise> {
auto* loadingContext = GetLoadingBrowsingContext();
MOZ_DIAGNOSTIC_ASSERT_IF(loadingContext->GetParent(),
loadingContext->GetParentWindowContext());
OriginAttributes attrs;
loadingContext->GetOriginAttributes(attrs);
mLoadIdentifier = aLoadState->GetLoadIdentifier();
if (!nsDocShell::CreateAndConfigureRealChannelForLoadState(
loadingContext, aLoadState, aLoadInfo, mParentChannelListener,
nullptr, attrs, aLoadFlags, aCacheKey, *aRv,
getter_AddRefs(mChannel))) {
LOG(("DocumentLoadListener::Open failed to create channel [this=%p]",
this));
mParentChannelListener = nullptr;
return nullptr;
}
auto* documentContext = GetDocumentBrowsingContext();
if (documentContext && mozilla::SessionHistoryInParent()) {
// It's hard to know at this point whether session history will be enabled
// in the browsing context, so we always create an entry for a load here.
mLoadingSessionHistoryInfo =
documentContext->CreateLoadingSessionHistoryEntryForLoad(aLoadState,
mChannel);
if (!mLoadingSessionHistoryInfo) {
*aRv = NS_BINDING_ABORTED;
mParentChannelListener = nullptr;
mChannel = nullptr;
return nullptr;
}
}
nsCOMPtr<nsIURI> uriBeingLoaded;
Unused << NS_WARN_IF(
NS_FAILED(mChannel->GetURI(getter_AddRefs(uriBeingLoaded))));
RefPtr<HttpBaseChannel> httpBaseChannel = do_QueryObject(mChannel, aRv);
if (uriBeingLoaded && httpBaseChannel) {
nsCOMPtr<nsIURI> topWindowURI;
if (mIsDocumentLoad && loadingContext->IsTop()) {
// If this is for the top level loading, the top window URI should be the
// URI which we are loading.
topWindowURI = uriBeingLoaded;
} else if (RefPtr<WindowGlobalParent> topWindow = AntiTrackingUtils::
GetTopWindowExcludingExtensionAccessibleContentFrames(
loadingContext, uriBeingLoaded)) {
nsCOMPtr<nsIPrincipal> topWindowPrincipal =
topWindow->DocumentPrincipal();
if (topWindowPrincipal && !topWindowPrincipal->GetIsNullPrincipal()) {
auto* basePrin = BasePrincipal::Cast(topWindowPrincipal);
basePrin->GetURI(getter_AddRefs(topWindowURI));
}
}
httpBaseChannel->SetTopWindowURI(topWindowURI);
}
nsCOMPtr<nsIIdentChannel> identChannel = do_QueryInterface(mChannel);
if (identChannel && aChannelId) {
Unused << identChannel->SetChannelId(*aChannelId);
}
RefPtr<nsHttpChannel> httpChannelImpl = do_QueryObject(mChannel);
if (httpChannelImpl) {
httpChannelImpl->SetWarningReporter(this);
}
nsCOMPtr<nsITimedChannel> timedChannel = do_QueryInterface(mChannel);
if (timedChannel) {
timedChannel->SetAsyncOpen(aAsyncOpenTime);
}
if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(mChannel)) {
Unused << httpChannel->SetRequestContextID(
loadingContext->GetRequestContextId());
nsCOMPtr<nsIClassOfService> cos(do_QueryInterface(httpChannel));
if (cos && aUrgentStart) {
cos->AddClassFlags(nsIClassOfService::UrgentStart);
}
}
// Setup a ClientChannelHelper to watch for redirects, and copy
// across any serviceworker related data between channels as needed.
AddClientChannelHelperInParent(mChannel, std::move(aInfo));
if (documentContext && !documentContext->StartDocumentLoad(this)) {
LOG(("DocumentLoadListener::Open failed StartDocumentLoad [this=%p]",
this));
*aRv = NS_BINDING_ABORTED;
mParentChannelListener = nullptr;
mChannel = nullptr;
return nullptr;
}
// Recalculate the openFlags, matching the logic in use in Content process.
// NOTE: The only case not handled here to mirror Content process is
// redirecting to re-use the channel.
MOZ_ASSERT(!aLoadState->GetPendingRedirectedChannel());
uint32_t openFlags =
nsDocShell::ComputeURILoaderFlags(loadingContext, aLoadState->LoadType());
RefPtr<ParentProcessDocumentOpenInfo> openInfo =
new ParentProcessDocumentOpenInfo(mParentChannelListener, openFlags,
loadingContext, mIsDocumentLoad);
openInfo->Prepare();
#ifdef ANDROID
RefPtr<MozPromise<bool, bool, false>> promise;
if (documentContext && aLoadState->LoadType() != LOAD_ERROR_PAGE &&
!(aLoadState->HasLoadFlags(
nsDocShell::INTERNAL_LOAD_FLAGS_BYPASS_LOAD_URI_DELEGATE)) &&
!(aLoadState->LoadType() & LOAD_HISTORY)) {
nsCOMPtr<nsIWidget> widget =
documentContext->GetParentProcessWidgetContaining();
RefPtr<nsWindow> window = nsWindow::From(widget);
if (window) {
promise = window->OnLoadRequest(
aLoadState->URI(), nsIBrowserDOMWindow::OPEN_CURRENTWINDOW,
aLoadState->LoadFlags(), aLoadState->TriggeringPrincipal(),
aLoadState->HasValidUserGestureActivation(),
documentContext->IsTopContent());
}
}
if (promise) {
RefPtr<DocumentLoadListener> self = this;
promise->Then(
GetCurrentSerialEventTarget(), __func__,
[=](const MozPromise<bool, bool, false>::ResolveOrRejectValue& aValue) {
if (aValue.IsResolve()) {
bool handled = aValue.ResolveValue();
if (handled) {
self->DisconnectListeners(NS_ERROR_ABORT, NS_ERROR_ABORT);
mParentChannelListener = nullptr;
} else {
nsresult rv = mChannel->AsyncOpen(openInfo);
if (NS_FAILED(rv)) {
self->DisconnectListeners(rv, rv);
mParentChannelListener = nullptr;
}
}
}
});
} else
#endif /* ANDROID */
{
*aRv = mChannel->AsyncOpen(openInfo);
if (NS_FAILED(*aRv)) {
LOG(("DocumentLoadListener::Open failed AsyncOpen [this=%p rv=%" PRIx32
"]",
this, static_cast<uint32_t>(*aRv)));
if (documentContext) {
documentContext->EndDocumentLoad(false);
}
mParentChannelListener = nullptr;
return nullptr;
}
}
// HTTPS-Only Mode fights potential timeouts caused by upgrades. Instantly
// after opening the document channel we have to kick off countermeasures.
nsHTTPSOnlyUtils::PotentiallyFireHttpRequestToShortenTimout(this);
mOtherPid = aPid;
mChannelCreationURI = aLoadState->URI();
mLoadStateLoadFlags = aLoadState->LoadFlags();
mLoadStateLoadType = aLoadState->LoadType();
mTiming = aTiming;
mSrcdocData = aLoadState->SrcdocData();
mBaseURI = aLoadState->BaseURI();
mOriginalUriString = aLoadState->GetOriginalURIString();
if (documentContext) {
mParentWindowContext = documentContext->GetParentWindowContext();
} else {
mParentWindowContext =
WindowGlobalParent::GetByInnerWindowId(aLoadInfo->GetInnerWindowID());
MOZ_RELEASE_ASSERT(mParentWindowContext->GetBrowsingContext() ==
GetLoadingBrowsingContext(),
"mismatched parent window context?");
}
*aRv = NS_OK;
mOpenPromise = new OpenPromise::Private(__func__);
// We make the promise use direct task dispatch in order to reduce the number
// of event loops iterations.
mOpenPromise->UseDirectTaskDispatch(__func__);
return mOpenPromise;
}
auto DocumentLoadListener::OpenDocument(
nsDocShellLoadState* aLoadState, uint32_t aCacheKey,
const Maybe<uint64_t>& aChannelId, const TimeStamp& aAsyncOpenTime,
nsDOMNavigationTiming* aTiming, Maybe<dom::ClientInfo>&& aInfo,
Maybe<bool> aUriModified, Maybe<bool> aIsXFOError, base::ProcessId aPid,
nsresult* aRv) -> RefPtr<OpenPromise> {
LOG(("DocumentLoadListener [%p] OpenDocument [uri=%s]", this,
aLoadState->URI()->GetSpecOrDefault().get()));
MOZ_ASSERT(mIsDocumentLoad);
RefPtr<CanonicalBrowsingContext> browsingContext =
GetDocumentBrowsingContext();
// If this is a top-level load, then rebuild the LoadInfo from scratch,
// since the goal is to be able to initiate loads in the parent, where the
// content process won't have provided us with an existing one.
RefPtr<LoadInfo> loadInfo =
CreateDocumentLoadInfo(browsingContext, aLoadState);
nsLoadFlags loadFlags = aLoadState->CalculateChannelLoadFlags(
browsingContext, std::move(aUriModified), std::move(aIsXFOError));
return Open(aLoadState, loadInfo, loadFlags, aCacheKey, aChannelId,
aAsyncOpenTime, aTiming, std::move(aInfo), false, aPid, aRv);
}
auto DocumentLoadListener::OpenObject(
nsDocShellLoadState* aLoadState, uint32_t aCacheKey,
const Maybe<uint64_t>& aChannelId, const TimeStamp& aAsyncOpenTime,
nsDOMNavigationTiming* aTiming, Maybe<dom::ClientInfo>&& aInfo,
uint64_t aInnerWindowId, nsLoadFlags aLoadFlags,
nsContentPolicyType aContentPolicyType, bool aUrgentStart,
base::ProcessId aPid, ObjectUpgradeHandler* aObjectUpgradeHandler,
nsresult* aRv) -> RefPtr<OpenPromise> {
LOG(("DocumentLoadListener [%p] OpenObject [uri=%s]", this,
aLoadState->URI()->GetSpecOrDefault().get()));
MOZ_ASSERT(!mIsDocumentLoad);
auto sandboxFlags = GetLoadingBrowsingContext()->GetSandboxFlags();
RefPtr<LoadInfo> loadInfo = CreateObjectLoadInfo(
aLoadState, aInnerWindowId, aContentPolicyType, sandboxFlags);
mObjectUpgradeHandler = aObjectUpgradeHandler;
return Open(aLoadState, loadInfo, aLoadFlags, aCacheKey, aChannelId,
aAsyncOpenTime, aTiming, std::move(aInfo), aUrgentStart, aPid,
aRv);
}
auto DocumentLoadListener::OpenInParent(nsDocShellLoadState* aLoadState,
bool aSupportsRedirectToRealChannel)
-> RefPtr<OpenPromise> {
MOZ_ASSERT(mIsDocumentLoad);
// We currently only support passing nullptr for aLoadInfo for
// top level browsing contexts.
auto* browsingContext = GetDocumentBrowsingContext();
if (!browsingContext->IsTopContent() ||
!browsingContext->GetContentParent()) {
LOG(("DocumentLoadListener::OpenInParent failed because of subdoc"));
return nullptr;
}
if (nsCOMPtr<nsIContentSecurityPolicy> csp = aLoadState->Csp()) {
// Check CSP navigate-to
bool allowsNavigateTo = false;
nsresult rv = csp->GetAllowsNavigateTo(aLoadState->URI(),
aLoadState->IsFormSubmission(),
false, /* aWasRedirected */
false, /* aEnforceWhitelist */
&allowsNavigateTo);
if (NS_FAILED(rv) || !allowsNavigateTo) {
return nullptr;
}
}
// Clone because this mutates the load flags in the load state, which
// breaks nsDocShells expectations of being able to do it.
RefPtr<nsDocShellLoadState> loadState = new nsDocShellLoadState(*aLoadState);
loadState->CalculateLoadURIFlags();
RefPtr<nsDOMNavigationTiming> timing = new nsDOMNavigationTiming(nullptr);
timing->NotifyNavigationStart(
browsingContext->IsActive()
? nsDOMNavigationTiming::DocShellState::eActive
: nsDOMNavigationTiming::DocShellState::eInactive);
const mozilla::dom::LoadingSessionHistoryInfo* loadingInfo =
loadState->GetLoadingSessionHistoryInfo();
uint32_t cacheKey = 0;
auto loadType = aLoadState->LoadType();
if (loadType == LOAD_HISTORY || loadType == LOAD_RELOAD_NORMAL ||
loadType == LOAD_RELOAD_CHARSET_CHANGE ||
loadType == LOAD_RELOAD_CHARSET_CHANGE_BYPASS_CACHE ||
loadType == LOAD_RELOAD_CHARSET_CHANGE_BYPASS_PROXY_AND_CACHE) {
if (loadingInfo) {
cacheKey = loadingInfo->mInfo.GetCacheKey();
}
}
// Loads start in the content process might have exposed a channel id to
// observers, so we need to preserve the value in the parent. That can't have
// happened here, so Nothing() is fine.
Maybe<uint64_t> channelId = Nothing();
// Initial client info is only relevant for subdocument loads, which we're
// not supporting yet.
Maybe<dom::ClientInfo> initialClientInfo;
mSupportsRedirectToRealChannel = aSupportsRedirectToRealChannel;
// This is a top-level load, so rebuild the LoadInfo from scratch,
// since in the parent the
// content process won't have provided us with an existing one.
RefPtr<LoadInfo> loadInfo =
CreateDocumentLoadInfo(browsingContext, aLoadState);
nsLoadFlags loadFlags = loadState->CalculateChannelLoadFlags(
browsingContext,
Some(loadingInfo && loadingInfo->mInfo.GetURIWasModified()), Nothing());
nsresult rv;
return Open(loadState, loadInfo, loadFlags, cacheKey, channelId,
TimeStamp::Now(), timing, std::move(initialClientInfo), false,
browsingContext->GetContentParent()->OtherPid(), &rv);
}
void DocumentLoadListener::FireStateChange(uint32_t aStateFlags,
nsresult aStatus) {
nsCOMPtr<nsIChannel> request = GetChannel();
nsCOMPtr<nsIWebProgress> webProgress =
new RemoteWebProgress(GetLoadType(), true, true);
RefPtr<BrowsingContextWebProgress> loadingWebProgress =
WebProgressForBrowsingContext(GetLoadingBrowsingContext());
if (loadingWebProgress) {
NS_DispatchToMainThread(
NS_NewRunnableFunction("DocumentLoadListener::FireStateChange", [=]() {
loadingWebProgress->OnStateChange(webProgress, request, aStateFlags,
aStatus);
}));
}
}
static void SetNavigating(CanonicalBrowsingContext* aBrowsingContext,
bool aNavigating) {
nsCOMPtr<nsIBrowser> browser;
if (RefPtr<Element> currentElement = aBrowsingContext->GetEmbedderElement()) {
browser = currentElement->AsBrowser();
}
if (!browser) {
return;
}
NS_DispatchToMainThread(NS_NewRunnableFunction(
"DocumentLoadListener::SetNavigating",
[browser, aNavigating]() { browser->SetIsNavigating(aNavigating); }));
}
/* static */ bool DocumentLoadListener::LoadInParent(
CanonicalBrowsingContext* aBrowsingContext, nsDocShellLoadState* aLoadState,
bool aSetNavigating) {
SetNavigating(aBrowsingContext, aSetNavigating);
RefPtr<DocumentLoadListener> load =
new DocumentLoadListener(aBrowsingContext, true);
RefPtr<DocumentLoadListener::OpenPromise> promise = load->OpenInParent(
aLoadState, /* aSupportsRedirectToRealChannel */ false);
if (!promise) {
SetNavigating(aBrowsingContext, false);
return false;
}
// We passed false for aSupportsRedirectToRealChannel, so we should always
// take the process switching path, and reject this promise.
promise->Then(
GetCurrentSerialEventTarget(), __func__,
[load](DocumentLoadListener::OpenPromise::ResolveOrRejectValue&& aValue) {
MOZ_ASSERT(aValue.IsReject());
DocumentLoadListener::OpenPromiseFailedType& rejectValue =
aValue.RejectValue();
if (!rejectValue.mSwitchedProcess) {
// If we're not switching the load to a new process, then it is
// finished (and failed), and we should fire a state change to notify
// observers. Normally the docshell would fire this, and it would get
// filtered out by BrowserParent if needed.
load->FireStateChange(nsIWebProgressListener::STATE_STOP |
nsIWebProgressListener::STATE_IS_WINDOW |
nsIWebProgressListener::STATE_IS_NETWORK,
rejectValue.mStatus);
}
});
load->FireStateChange(nsIWebProgressListener::STATE_START |
nsIWebProgressListener::STATE_IS_DOCUMENT |
nsIWebProgressListener::STATE_IS_REQUEST |
nsIWebProgressListener::STATE_IS_WINDOW |
nsIWebProgressListener::STATE_IS_NETWORK,
NS_OK);
SetNavigating(aBrowsingContext, false);
return true;
}
/* static */
bool DocumentLoadListener::SpeculativeLoadInParent(
dom::CanonicalBrowsingContext* aBrowsingContext,
nsDocShellLoadState* aLoadState) {
LOG(("DocumentLoadListener::OpenFromParent"));
RefPtr<DocumentLoadListener> listener =
new DocumentLoadListener(aBrowsingContext, true);
auto promise = listener->OpenInParent(aLoadState, true);
if (promise) {
// Create an entry in the redirect channel registrar to
// allocate an identifier for this load.
nsCOMPtr<nsIRedirectChannelRegistrar> registrar =
RedirectChannelRegistrar::GetOrCreate();
uint64_t loadIdentifier = aLoadState->GetLoadIdentifier();
DebugOnly<nsresult> rv =
registrar->RegisterChannel(nullptr, loadIdentifier);
MOZ_ASSERT(NS_SUCCEEDED(rv));
// Register listener (as an nsIParentChannel) under our new identifier.
rv = registrar->LinkChannels(loadIdentifier, listener, nullptr);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
return !!promise;
}
void DocumentLoadListener::CleanupParentLoadAttempt(uint64_t aLoadIdent) {
nsCOMPtr<nsIRedirectChannelRegistrar> registrar =
RedirectChannelRegistrar::GetOrCreate();
nsCOMPtr<nsIParentChannel> parentChannel;
registrar->GetParentChannel(aLoadIdent, getter_AddRefs(parentChannel));
RefPtr<DocumentLoadListener> loadListener = do_QueryObject(parentChannel);
if (loadListener) {
// If the load listener is still registered, then we must have failed
// to connect DocumentChannel into it. Better cancel it!
loadListener->NotifyDocumentChannelFailed();
}
registrar->DeregisterChannels(aLoadIdent);
}
auto DocumentLoadListener::ClaimParentLoad(DocumentLoadListener** aListener,
uint64_t aLoadIdent)
-> RefPtr<OpenPromise> {
nsCOMPtr<nsIRedirectChannelRegistrar> registrar =
RedirectChannelRegistrar::GetOrCreate();
nsCOMPtr<nsIParentChannel> parentChannel;
registrar->GetParentChannel(aLoadIdent, getter_AddRefs(parentChannel));
RefPtr<DocumentLoadListener> loadListener = do_QueryObject(parentChannel);
registrar->DeregisterChannels(aLoadIdent);
if (!loadListener) {
// The parent went away unexpectedly.
*aListener = nullptr;
return nullptr;
}
MOZ_DIAGNOSTIC_ASSERT(loadListener->mOpenPromise);
loadListener.forget(aListener);
return (*aListener)->mOpenPromise;
}
void DocumentLoadListener::NotifyDocumentChannelFailed() {
LOG(("DocumentLoadListener NotifyDocumentChannelFailed [this=%p]", this));
// There's been no calls to ClaimParentLoad, and so no listeners have been
// attached to mOpenPromise yet. As such we can run Then() on it.
mOpenPromise->Then(
GetMainThreadSerialEventTarget(), __func__,
[](DocumentLoadListener::OpenPromiseSucceededType&& aResolveValue) {
aResolveValue.mPromise->Resolve(NS_BINDING_ABORTED, __func__);
},
[]() {});
Cancel(NS_BINDING_ABORTED);
}
void DocumentLoadListener::Disconnect() {
LOG(("DocumentLoadListener Disconnect [this=%p]", this));
// The nsHttpChannel may have a reference to this parent, release it
// to avoid circular references.
RefPtr<nsHttpChannel> httpChannelImpl = do_QueryObject(mChannel);
if (httpChannelImpl) {
httpChannelImpl->SetWarningReporter(nullptr);
}
if (auto* ctx = GetDocumentBrowsingContext()) {
ctx->EndDocumentLoad(mDoingProcessSwitch);
}
}
void DocumentLoadListener::Cancel(const nsresult& aStatusCode) {
LOG(
("DocumentLoadListener Cancel [this=%p, "
"aStatusCode=%" PRIx32 " ]",
this, static_cast<uint32_t>(aStatusCode)));
if (mOpenPromiseResolved) {
return;
}
if (mChannel) {
mChannel->Cancel(aStatusCode);
}
DisconnectListeners(aStatusCode, aStatusCode);
}
void DocumentLoadListener::DisconnectListeners(nsresult aStatus,
nsresult aLoadGroupStatus,
bool aSwitchedProcess) {
LOG(
("DocumentLoadListener DisconnectListener [this=%p, "
"aStatus=%" PRIx32 " aLoadGroupStatus=%" PRIx32 " ]",
this, static_cast<uint32_t>(aStatus),
static_cast<uint32_t>(aLoadGroupStatus)));
RejectOpenPromise(aStatus, aLoadGroupStatus, aSwitchedProcess, __func__);
Disconnect();
if (!aSwitchedProcess) {
// If we're not going to send anything else to the content process, and
// we haven't yet consumed a stream filter promise, then we're never going
// to. If we're disconnecting the old content process due to a proces
// switch, then we can rely on FinishReplacementChannelSetup being called
// (even if the switch failed), so we clear at that point instead.
// TODO: This might be because we retargeted the stream to the download
// handler or similar. Do we need to attach a stream filter to that?
mStreamFilterRequests.Clear();
}
}
void DocumentLoadListener::RedirectToRealChannelFinished(nsresult aRv) {
LOG(
("DocumentLoadListener RedirectToRealChannelFinished [this=%p, "
"aRv=%" PRIx32 " ]",
this, static_cast<uint32_t>(aRv)));
if (NS_FAILED(aRv)) {