Source code

Revision control

Copy as Markdown

Other Tools

/* -*- 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 "NeckoCommon.h"
#include "mozilla/AntiTrackingUtils.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/LoadInfo.h"
#include "mozilla/MozPromiseInlines.h" // For MozPromise::FromDomPromise
#include "mozilla/NullPrincipal.h"
#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/ProcessIsolation.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 "nsContentSecurityManager.h"
#include "nsDocShell.h"
#include "nsDocShellLoadState.h"
#include "nsDocShellLoadTypes.h"
#include "nsDOMNavigationTiming.h"
#include "nsDSURIContentListener.h"
#include "nsObjectLoadingContent.h"
#include "nsOpenWindowInfo.h"
#include "nsExternalHelperAppService.h"
#include "nsHttpChannel.h"
#include "nsIBrowser.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 "nsSHistory.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/ReferrerInfo.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)
extern mozilla::LazyLogModule gSHIPBFCacheLog;
// Bug 136580: Limit to the number of nested content frames that can have the
// same URL. This is to stop content that is recursively loading
// itself. Note that "#foo" on the end of URL doesn't affect
// whether it's considered identical, but "?foo" or ";foo" are
// considered and compared.
// Limit this to 2, like chromium does.
static constexpr int kMaxSameURLContentFrames = 2;
using namespace mozilla::dom;
namespace mozilla {
namespace net {
static ContentParentId GetContentProcessId(ContentParent* aContentParent) {
return aContentParent ? aContentParent->ChildID() : ContentParentId{0};
}
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->HasInternalLoadFlags(
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(),
aLoadState->GetEffectiveTriggeringRemoteType(), securityFlags,
sandboxFlags);
} else {
OriginAttributes attrs;
aBrowsingContext->GetOriginAttributes(attrs);
loadInfo = LoadInfo::CreateForDocument(
aBrowsingContext, aLoadState->URI(), aLoadState->TriggeringPrincipal(),
aLoadState->GetEffectiveTriggeringRemoteType(), attrs, securityFlags,
sandboxFlags);
}
if (aLoadState->IsExemptFromHTTPSOnlyMode()) {
uint32_t httpsOnlyStatus = loadInfo->GetHttpsOnlyStatus();
httpsOnlyStatus |= nsILoadInfo::HTTPS_ONLY_EXEMPT;
loadInfo->SetHttpsOnlyStatus(httpsOnlyStatus);
}
loadInfo->SetTriggeringSandboxFlags(aLoadState->TriggeringSandboxFlags());
loadInfo->SetHasValidUserGestureActivation(
aLoadState->HasValidUserGestureActivation());
loadInfo->SetIsMetaRefresh(aLoadState->IsMetaRefresh());
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());
loadInfo->SetIsMetaRefresh(aLoadState->IsMetaRefresh());
return loadInfo.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);
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) ||
mContentType.IsEmpty()) {
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(nsIEarlyHintObserver)
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);
}
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;
}
bool CheckRecursiveLoad(CanonicalBrowsingContext* aLoadingContext,
nsDocShellLoadState* aLoadState, bool aIsDocumentLoad) {
// Bug 136580: Check for recursive frame loading excluding about:srcdoc URIs.
// srcdoc URIs require their contents to be specified inline, so it isn't
// possible for undesirable recursion to occur without the aid of a
// non-srcdoc URI, which this method will block normally.
// Besides, URI is not enough to guarantee uniqueness of srcdoc documents.
nsAutoCString buffer;
if (aLoadState->URI()->SchemeIs("about")) {
nsresult rv = aLoadState->URI()->GetPathQueryRef(buffer);
if (NS_SUCCEEDED(rv) && buffer.EqualsLiteral("srcdoc")) {
// Duplicates allowed up to depth limits
return true;
}
}
RefPtr<WindowGlobalParent> parent;
if (!aIsDocumentLoad) { // object load
parent = aLoadingContext->GetCurrentWindowGlobal();
} else {
parent = aLoadingContext->GetParentWindowContext();
}
int matchCount = 0;
CanonicalBrowsingContext* ancestorBC;
for (WindowGlobalParent* ancestorWGP = parent; ancestorWGP;
ancestorWGP = ancestorBC->GetParentWindowContext()) {
ancestorBC = ancestorWGP->BrowsingContext();
MOZ_ASSERT(ancestorBC);
if (nsCOMPtr<nsIURI> parentURI = ancestorWGP->GetDocumentURI()) {
bool equal;
nsresult rv = aLoadState->URI()->EqualsExceptRef(parentURI, &equal);
NS_ENSURE_SUCCESS(rv, false);
if (equal) {
matchCount++;
if (matchCount >= kMaxSameURLContentFrames) {
NS_WARNING(
"Too many nested content frames/objects have the same url "
"(recursion?) "
"so giving up");
return false;
}
}
}
}
return true;
}
// Check that the load state, potentially received from a child process, appears
// to be performing a load of the specified LoadingSessionHistoryInfo.
// Returns a static (telemetry-safe) string naming what did not match, or
// nullptr if it succeeds.
static const char* ValidateHistoryLoad(
CanonicalBrowsingContext* aLoadingContext,
nsDocShellLoadState* aLoadState) {
MOZ_ASSERT(SessionHistoryInParent());
MOZ_ASSERT(aLoadState->LoadIsFromSessionHistory());
if (!aLoadState->GetLoadingSessionHistoryInfo()) {
return "Missing LoadingSessionHistoryInfo";
}
const SessionHistoryInfo* snapshot =
SessionHistoryEntry::GetInfoSnapshotForValidationByLoadId(
aLoadState->GetLoadingSessionHistoryInfo()->mLoadId);
if (!snapshot) {
return "Invalid LoadId";
}
// History loads do not inherit principal.
if (aLoadState->HasInternalLoadFlags(
nsDocShell::INTERNAL_LOAD_FLAGS_INHERIT_PRINCIPAL)) {
return "LOAD_FLAGS_INHERIT_PRINCIPAL";
}
auto uriEq = [](nsIURI* a, nsIURI* b) -> bool {
bool eq = false;
return a == b || (a && b && NS_SUCCEEDED(a->Equals(b, &eq)) && eq);
};
auto principalEq = [](nsIPrincipal* a, nsIPrincipal* b) -> bool {
return a == b || (a && b && a->Equals(b));
};
// XXX: Needing to do all of this validation manually is kinda gross.
if (!uriEq(snapshot->GetURI(), aLoadState->URI())) {
return "URI";
}
if (!uriEq(snapshot->GetOriginalURI(), aLoadState->OriginalURI())) {
return "OriginalURI";
}
if (!aLoadState->ResultPrincipalURIIsSome() ||
!uriEq(snapshot->GetResultPrincipalURI(),
aLoadState->ResultPrincipalURI())) {
return "ResultPrincipalURI";
}
if (!uriEq(snapshot->GetUnstrippedURI(), aLoadState->GetUnstrippedURI())) {
return "UnstrippedURI";
}
if (!principalEq(snapshot->GetTriggeringPrincipal(),
aLoadState->TriggeringPrincipal())) {
return "TriggeringPrincipal";
}
if (!principalEq(snapshot->GetPrincipalToInherit(),
aLoadState->PrincipalToInherit())) {
return "PrincipalToInherit";
}
if (!principalEq(snapshot->GetPartitionedPrincipalToInherit(),
aLoadState->PartitionedPrincipalToInherit())) {
return "PartitionedPrincipalToInherit";
}
// Everything matches!
return nullptr;
}
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,
dom::ContentParent* aContentParent,
nsresult* aRv) -> RefPtr<OpenPromise> {
auto* loadingContext = GetLoadingBrowsingContext();
MOZ_DIAGNOSTIC_ASSERT_IF(loadingContext->GetParent(),
loadingContext->GetParentWindowContext());
OriginAttributes attrs;
loadingContext->GetOriginAttributes(attrs);
mLoadIdentifier = aLoadState->GetLoadIdentifier();
// See description of mFileName in nsDocShellLoadState.h
mIsDownload = !aLoadState->FileName().IsVoid();
mIsLoadingJSURI = net::SchemeIsJavascript(aLoadState->URI());
// Check for infinite recursive object or iframe loads
if (aLoadState->OriginalFrameSrc() || !mIsDocumentLoad) {
if (!CheckRecursiveLoad(loadingContext, aLoadState, mIsDocumentLoad)) {
*aRv = NS_ERROR_RECURSIVE_DOCUMENT_LOAD;
mParentChannelListener = nullptr;
return nullptr;
}
}
// If we are using SHIP and this load is from session history, validate that
// the load matches our local copy of the loading history entry.
//
// NOTE: Keep this check in-sync with the check in
// `nsDocShellLoadState::GetEffectiveTriggeringRemoteType()`!
if (SessionHistoryInParent() && aLoadState->LoadIsFromSessionHistory() &&
aLoadState->LoadType() != LOAD_ERROR_PAGE) {
if (const char* mismatch =
ValidateHistoryLoad(loadingContext, aLoadState)) {
LOG(
("DocumentLoadListener::Open with invalid loading history entry "
"[this=%p, mismatch=%s]",
this, mismatch));
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
MOZ_CRASH_UNSAFE_PRINTF(
"DocumentLoadListener::Open for invalid history entry due to "
"mismatch of '%s'",
mismatch);
#endif
*aRv = NS_ERROR_DOM_SECURITY_ERR;
mParentChannelListener = nullptr;
return nullptr;
}
}
if (aLoadState->GetRemoteTypeOverride()) {
if (!mIsDocumentLoad || !NS_IsAboutBlank(aLoadState->URI()) ||
!loadingContext->IsTopContent()) {
LOG(
("DocumentLoadListener::Open with invalid remoteTypeOverride "
"[this=%p]",
this));
*aRv = NS_ERROR_DOM_SECURITY_ERR;
mParentChannelListener = nullptr;
return nullptr;
}
mRemoteTypeOverride = aLoadState->GetRemoteTypeOverride();
}
if (NS_WARN_IF(!loadingContext->IsOwnedByProcess(
GetContentProcessId(aContentParent)))) {
LOG(
("DocumentLoadListener::Open called from non-current content process "
"[this=%p, current=%" PRIu64 ", caller=%" PRIu64 "]",
this, loadingContext->OwnerProcessId(),
uint64_t(GetContentProcessId(aContentParent))));
*aRv = NS_BINDING_ABORTED;
mParentChannelListener = nullptr;
return nullptr;
}
if (mIsDocumentLoad && loadingContext->IsContent() &&
NS_WARN_IF(loadingContext->IsReplaced())) {
LOG(
("DocumentLoadListener::Open called from replaced BrowsingContext "
"[this=%p, browserid=%" PRIx64 ", bcid=%" PRIx64 "]",
this, loadingContext->BrowserId(), loadingContext->Id()));
*aRv = NS_BINDING_ABORTED;
mParentChannelListener = nullptr;
return nullptr;
}
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 && aLoadState->LoadType() != LOAD_ERROR_PAGE &&
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);
}
mDocumentChannelId = aChannelId;
RefPtr<nsHttpChannel> httpChannelImpl = do_QueryObject(mChannel);
if (httpChannelImpl) {
httpChannelImpl->SetWarningReporter(this);
if (mIsDocumentLoad && loadingContext->IsTop()) {
httpChannelImpl->SetEarlyHintObserver(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->HasInternalLoadFlags(
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->InternalLoadFlags(), 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);
nsCOMPtr<nsILoadInfo> loadInfo = mChannel->LoadInfo();
loadInfo->SetChannelCreationOriginalURI(aLoadState->URI());
mContentParent = aContentParent;
mLoadStateExternalLoadFlags = aLoadState->LoadFlags();
mLoadStateInternalLoadFlags = aLoadState->InternalLoadFlags();
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?");
}
// For content-initiated loads, this flag is set in nsDocShell::LoadURI.
// For parent-initiated loads, we have to set it here.
// Below comment is copied from nsDocShell::LoadURI -
// If we have a system triggering principal, we can assume that this load was
// triggered by some UI in the browser chrome, such as the URL bar or
// bookmark bar. This should count as a user interaction for the current sh
// entry, so that the user may navigate back to the current entry, from the
// entry that is going to be added as part of this load.
if (!mSupportsRedirectToRealChannel && aLoadState->TriggeringPrincipal() &&
aLoadState->TriggeringPrincipal()->IsSystemPrincipal()) {
WindowContext* topWc = loadingContext->GetTopWindowContext();
if (topWc && !topWc->IsDiscarded()) {
MOZ_ALWAYS_SUCCEEDS(topWc->SetSHEntryHasUserInteraction(true));
}
}
*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,
dom::ContentParent* aContentParent, 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, aContentParent,
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,
dom::ContentParent* aContentParent,
ObjectUpgradeHandler* aObjectUpgradeHandler, nsresult* aRv)
-> RefPtr<OpenPromise> {
LOG(("DocumentLoadListener [%p] OpenObject [uri=%s]", this,
aLoadState->URI()->GetSpecOrDefault().get()));
MOZ_ASSERT(!mIsDocumentLoad);
auto sandboxFlags = aLoadState->TriggeringSandboxFlags();
RefPtr<LoadInfo> loadInfo = CreateObjectLoadInfo(
aLoadState, aInnerWindowId, aContentPolicyType, sandboxFlags);
mObjectUpgradeHandler = aObjectUpgradeHandler;
return Open(aLoadState, loadInfo, aLoadFlags, aCacheKey, aChannelId,
aAsyncOpenTime, aTiming, std::move(aInfo), aUrgentStart,
aContentParent, 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(), &rv);
}
base::ProcessId DocumentLoadListener::OtherPid() const {
return mContentParent ? mContentParent->OtherPid() : base::ProcessId{0};
}
void DocumentLoadListener::FireStateChange(uint32_t aStateFlags,
nsresult aStatus) {
nsCOMPtr<nsIChannel> request = GetChannel();
RefPtr<BrowsingContextWebProgress> webProgress =
GetLoadingBrowsingContext()->GetWebProgress();
if (webProgress) {
NS_DispatchToMainThread(
NS_NewRunnableFunction("DocumentLoadListener::FireStateChange", [=]() {
webProgress->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.mContinueNavigating) {
// 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,
Maybe<uint64_t> aChannelId)
-> 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;
}
loadListener->mDocumentChannelId = aChannelId;
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,
"DocumentLoadListener::NotifyDocumentChannelFailed"_ns);
}
void DocumentLoadListener::Disconnect(bool aContinueNavigating) {
LOG(("DocumentLoadListener Disconnect [this=%p, aContinueNavigating=%d]",
this, aContinueNavigating));
// 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);
httpChannelImpl->SetEarlyHintObserver(nullptr);
}
// Don't cancel ongoing early hints when continuing to load the web page.
// Early hints are loaded earlier in the code and shouldn't get cancelled
// here. See also: Bug 1765652
if (!aContinueNavigating) {
mEarlyHintsService.Cancel("DocumentLoadListener::Disconnect"_ns);
}
if (auto* ctx = GetDocumentBrowsingContext()) {
ctx->EndDocumentLoad(aContinueNavigating);
}
}
void DocumentLoadListener::Cancel(const nsresult& aStatusCode,
const nsACString& aReason) {
LOG(
("DocumentLoadListener Cancel [this=%p, "
"aStatusCode=%" PRIx32 " ]",
this, static_cast<uint32_t>(aStatusCode)));
if (mOpenPromiseResolved) {
return;
}
if (mChannel) {
mChannel->CancelWithReason(aStatusCode, aReason);
}
DisconnectListeners(aStatusCode, aStatusCode);
}
void DocumentLoadListener::DisconnectListeners(nsresult aStatus,
nsresult aLoadGroupStatus,
bool aContinueNavigating) {
LOG(
("DocumentLoadListener DisconnectListener [this=%p, "
"aStatus=%" PRIx32 ", aLoadGroupStatus=%" PRIx32
", aContinueNavigating=%d]",
this, static_cast<uint32_t>(aStatus),
static_cast<uint32_t>(aLoadGroupStatus), aContinueNavigating));
RejectOpenPromise(aStatus, aLoadGroupStatus, aContinueNavigating, __func__);
Disconnect(aContinueNavigating);
// Clear any pending stream filter requests. If we're going to be sending a
// response to the content process due to a navigation, our caller will have
// already stashed the array to be passed to `TriggerRedirectToRealChannel`,
// so it's safe for us to clear here.
// TODO: If we retargeted the stream to a non-default handler (e.g. to trigger
// a download), we currently never attach a stream filter. Should we attach a
// stream filter in those situations as well?
mStreamFilterRequests.Clear();
}
void DocumentLoadListener::RedirectToRealChannelFinished(nsresult aRv) {
LOG(
("DocumentLoadListener RedirectToRealChannelFinished [this=%p, "
"aRv=%" PRIx32 " ]",
this, static_cast<uint32_t>(aRv)));
if (NS_FAILED(aRv)) {
FinishReplacementChannelSetup(aRv);
return;
}
// Wait for background channel ready on target channel
nsCOMPtr<nsIRedirectChannelRegistrar> redirectReg =
RedirectChannelRegistrar::GetOrCreate();
MOZ_ASSERT(redirectReg);
nsCOMPtr<nsIParentChannel> redirectParentChannel;
redirectReg->GetParentChannel(mRedirectChannelId,
getter_AddRefs(redirectParentChannel));
if (!redirectParentChannel) {
FinishReplacementChannelSetup(NS_ERROR_FAILURE);
return;
}
nsCOMPtr<nsIParentRedirectingChannel> redirectingParent =
do_QueryInterface(redirectParentChannel);
if (!redirectingParent) {
// Continue verification procedure if redirecting to non-Http protocol
FinishReplacementChannelSetup(NS_OK);
return;
}
// Ask redirected channel if verification can proceed.
// ReadyToVerify will be invoked when redirected channel is ready.
redirectingParent->ContinueVerification(this);
}
NS_IMETHODIMP
DocumentLoadListener::ReadyToVerify(nsresult aResultCode) {
FinishReplacementChannelSetup(aResultCode);
return NS_OK;
}
void DocumentLoadListener::FinishReplacementChannelSetup(nsresult aResult) {
LOG(
("DocumentLoadListener FinishReplacementChannelSetup [this=%p, "
"aResult=%x]",
this, int(aResult)));
auto endDocumentLoad = MakeScopeExit([&]() {
if (auto* ctx = GetDocumentBrowsingContext()) {
ctx->EndDocumentLoad(false);
}
});
mStreamFilterRequests.Clear();
nsCOMPtr<nsIRedirectChannelRegistrar> registrar =
RedirectChannelRegistrar::GetOrCreate();
MOZ_ASSERT(registrar);
nsCOMPtr<nsIParentChannel> redirectChannel;
nsresult rv = registrar->GetParentChannel(mRedirectChannelId,
getter_AddRefs(redirectChannel));
if (NS_FAILED(rv) || !redirectChannel) {
aResult = NS_ERROR_FAILURE;
}
// Release all previously registered channels, they are no longer needed to
// be kept in the registrar from this moment.
registrar->DeregisterChannels(mRedirectChannelId);
mRedirectChannelId = 0;
if (NS_FAILED(aResult)) {
if (redirectChannel) {
redirectChannel->Delete();
}
mChannel->Cancel(aResult);
mChannel->Resume();
return;
}
MOZ_ASSERT(
!SameCOMIdentity(redirectChannel, static_cast<nsIParentChannel*>(this)));
redirectChannel->SetParentListener(mParentChannelListener);
ApplyPendingFunctions(redirectChannel);
if (!ResumeSuspendedChannel(redirectChannel)) {
nsCOMPtr<nsILoadGroup> loadGroup;
mChannel->GetLoadGroup(getter_AddRefs(loadGroup));
if (loadGroup) {
// We added ourselves to the load group, but attempting
// to resume has notified us that the channel is already
// finished. Better remove ourselves from the loadgroup
// again. The only time the channel will be in a loadgroup
// is if we're connected to the parent process.
nsresult status = NS_OK;
mChannel->GetStatus(&status);
loadGroup->RemoveRequest(mChannel, nullptr, status);
}
}
}
void DocumentLoadListener::ApplyPendingFunctions(
nsIParentChannel* aChannel) const {
// We stored the values from all nsIParentChannel functions called since we
// couldn't handle them. Copy them across to the real channel since it
// should know what to do.
nsCOMPtr<nsIParentChannel> parentChannel = aChannel;
for (const auto& variant : mIParentChannelFunctions) {
variant.match(
[parentChannel](const ClassifierMatchedInfoParams& aParams) {
parentChannel->SetClassifierMatchedInfo(
aParams.mList, aParams.mProvider, aParams.mFullHash);
},
[parentChannel](const ClassifierMatchedTrackingInfoParams& aParams) {
parentChannel->SetClassifierMatchedTrackingInfo(aParams.mLists,
aParams.mFullHashes);
},
[parentChannel](const ClassificationFlagsParams& aParams) {
parentChannel->NotifyClassificationFlags(aParams.mClassificationFlags,
aParams.mIsThirdParty);
});
}
RefPtr<HttpChannelSecurityWarningReporter> reporter;
if (RefPtr<HttpChannelParent> httpParent = do_QueryObject(aChannel)) {
reporter = httpParent;
} else if (RefPtr<nsHttpChannel> httpChannel = do_QueryObject(aChannel)) {
reporter = httpChannel->GetWarningReporter();
}
if (reporter) {
for (const auto& variant : mSecurityWarningFunctions) {
variant.match(
[reporter](const ReportSecurityMessageParams& aParams) {
Unused << reporter->ReportSecurityMessage(aParams.mMessageTag,
aParams.mMessageCategory);
},
[reporter](const LogBlockedCORSRequestParams& aParams) {
Unused << reporter->LogBlockedCORSRequest(aParams.mMessage,
aParams.mCategory);
},
[reporter](const LogMimeTypeMismatchParams& aParams) {
Unused << reporter->LogMimeTypeMismatch(
aParams.mMessageName, aParams.mWarning, aParams.mURL,
aParams.mContentType);
});
}
}
}
bool DocumentLoadListener::ResumeSuspendedChannel(
nsIStreamListener* aListener) {
LOG(("DocumentLoadListener ResumeSuspendedChannel [this=%p]", this));
RefPtr<nsHttpChannel> httpChannel = do_QueryObject(mChannel);
if (httpChannel) {
httpChannel->SetApplyConversion(mOldApplyConversion);
}
if (!mIsFinished) {
mParentChannelListener->SetListenerAfterRedirect(aListener);
}
// If we failed to suspend the channel, then we might have received
// some messages while the redirected was being handled.
// Manually send them on now.
nsTArray<StreamListenerFunction> streamListenerFunctions =
std::move(mStreamListenerFunctions);
if (!aListener) {
streamListenerFunctions.Clear();
}
ForwardStreamListenerFunctions(streamListenerFunctions, aListener);
// We don't expect to get new stream listener functions added
// via re-entrancy. If this ever happens, we should understand
// exactly why before allowing it.
NS_ASSERTION(mStreamListenerFunctions.IsEmpty(),
"Should not have added new stream listener function!");
mChannel->Resume();
// Our caller will invoke `EndDocumentLoad` for us.
return !mIsFinished;
}
void DocumentLoadListener::SerializeRedirectData(
RedirectToRealChannelArgs& aArgs, bool aIsCrossProcess,
uint32_t aRedirectFlags, uint32_t aLoadFlags, ContentParent* aParent,
nsTArray<EarlyHintConnectArgs>&& aEarlyHints) const {
aArgs.uri() = GetChannelCreationURI();
aArgs.loadIdentifier() = mLoadIdentifier;
aArgs.earlyHints() = std::move(aEarlyHints);
// I previously used HttpBaseChannel::CloneLoadInfoForRedirect, but that
// clears the principal to inherit, which fails tests (probably because this
// 'redirect' is usually just an implementation detail). It's also http
// only, and mChannel can be anything that we redirected to.
nsCOMPtr<nsILoadInfo> channelLoadInfo = mChannel->LoadInfo();
nsCOMPtr<nsIPrincipal> principalToInherit;
channelLoadInfo->GetPrincipalToInherit(getter_AddRefs(principalToInherit));
const RefPtr<nsHttpChannel> baseChannel = do_QueryObject(mChannel);
nsCOMPtr<nsILoadContext> loadContext;
NS_QueryNotificationCallbacks(mChannel, loadContext);
nsCOMPtr<nsILoadInfo> redirectLoadInfo;
// Only use CloneLoadInfoForRedirect if we have a load context,
// since it internally tries to pull OriginAttributes from the
// the load context and asserts if they don't match the load info.
// We can end up without a load context if the channel has been aborted
// and the callbacks have been cleared.
if (baseChannel && loadContext) {
redirectLoadInfo = baseChannel->CloneLoadInfoForRedirect(
aArgs.uri(), nsIChannelEventSink::REDIRECT_INTERNAL);
redirectLoadInfo->SetResultPrincipalURI(aArgs.uri());
// The clone process clears this, and then we fail tests..
// docshell/test/mochitest/test_forceinheritprincipal_overrule_owner.html
if (principalToInherit) {
redirectLoadInfo->SetPrincipalToInherit(principalToInherit);
}
} else {
redirectLoadInfo =
static_cast<mozilla::net::LoadInfo*>(channelLoadInfo.get())->Clone();
redirectLoadInfo->AppendRedirectHistoryEntry(mChannel, true);
}
const Maybe<ClientInfo>& reservedClientInfo =
channelLoadInfo->GetReservedClientInfo();
if (reservedClientInfo) {
redirectLoadInfo->SetReservedClientInfo(*reservedClientInfo);
}
aArgs.registrarId() = mRedirectChannelId;
MOZ_ALWAYS_SUCCEEDS(
ipc::LoadInfoToLoadInfoArgs(redirectLoadInfo, &aArgs.loadInfo()));
mChannel->GetOriginalURI(getter_AddRefs(aArgs.originalURI()));
// mChannel can be a nsHttpChannel as well as InterceptedHttpChannel so we
// can't use baseChannel here.
if (nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(mChannel)) {
MOZ_ALWAYS_SUCCEEDS(httpChannel->GetChannelId(&aArgs.channelId()));
}
aArgs.redirectMode() = nsIHttpChannelInternal::REDIRECT_MODE_FOLLOW;
nsCOMPtr<nsIHttpChannelInternal> httpChannelInternal =
do_QueryInterface(mChannel);
if (httpChannelInternal) {
MOZ_ALWAYS_SUCCEEDS(
httpChannelInternal->GetRedirectMode(&aArgs.redirectMode()));
}
if (baseChannel) {
aArgs.init() =
Some(baseChannel
->CloneReplacementChannelConfig(
true, aRedirectFlags,
HttpBaseChannel::ReplacementReason::DocumentChannel)
.Serialize(aParent));
}
uint32_t contentDispositionTemp;
nsresult rv = mChannel->GetContentDisposition(&contentDispositionTemp);
if (NS_SUCCEEDED(rv)) {
aArgs.contentDisposition() = Some(contentDispositionTemp);
}
nsString contentDispositionFilenameTemp;
rv = mChannel->GetContentDispositionFilename(contentDispositionFilenameTemp);
if (NS_SUCCEEDED(rv)) {
aArgs.contentDispositionFilename() = Some(contentDispositionFilenameTemp);
}
SetNeedToAddURIVisit(mChannel, false);
aArgs.newLoadFlags() = aLoadFlags;
aArgs.redirectFlags() = aRedirectFlags;
aArgs.properties() = do_QueryObject(mChannel);
aArgs.srcdocData() = mSrcdocData;
aArgs.baseUri() = mBaseURI;
aArgs.loadStateExternalLoadFlags() = mLoadStateExternalLoadFlags;
aArgs.loadStateInternalLoadFlags() = mLoadStateInternalLoadFlags;
aArgs.loadStateLoadType() = mLoadStateLoadType;
aArgs.originalUriString() = mOriginalUriString;
if (mLoadingSessionHistoryInfo) {
aArgs.loadingSessionHistoryInfo().emplace(*mLoadingSessionHistoryInfo);
}
}
static bool IsFirstLoadInWindow(nsIChannel* aChannel) {
if (nsCOMPtr<nsIPropertyBag2> props = do_QueryInterface(aChannel)) {
bool tmp = false;
nsresult rv =
props->GetPropertyAsBool(u"docshell.newWindowTarget"_ns, &tmp);
return NS_SUCCEEDED(rv) && tmp;
}
return false;
}
// Get where the document loaded by this nsIChannel should be rendered. This
// will be `OPEN_CURRENTWINDOW` unless we're loading an attachment which would
// normally open in an external program, but we're instead choosing to render
// internally.
static int32_t GetWhereToOpen(nsIChannel* aChannel, bool aIsDocumentLoad) {
// Ignore content disposition for loads from an object or embed element.
if (!aIsDocumentLoad) {
return nsIBrowserDOMWindow::OPEN_CURRENTWINDOW;
}
// Always continue in the same window if we're not loading an attachment.
uint32_t disposition = nsIChannel::DISPOSITION_INLINE;
if (NS_FAILED(aChannel->GetContentDisposition(&disposition)) ||
disposition != nsIChannel::DISPOSITION_ATTACHMENT) {
return nsIBrowserDOMWindow::OPEN_CURRENTWINDOW;
}
// If the channel is for a new window target, continue in the same window.
if (IsFirstLoadInWindow(aChannel)) {
return nsIBrowserDOMWindow::OPEN_CURRENTWINDOW;
}
// Respect the user's preferences with browser.link.open_newwindow
// FIXME: There should probably be a helper for this, as the logic is
// duplicated in a few places.
int32_t where = Preferences::GetInt("browser.link.open_newwindow",
nsIBrowserDOMWindow::OPEN_NEWTAB);
if (where == nsIBrowserDOMWindow::OPEN_CURRENTWINDOW ||
where == nsIBrowserDOMWindow::OPEN_NEWWINDOW ||
where == nsIBrowserDOMWindow::OPEN_NEWTAB) {
return where;
}
return nsIBrowserDOMWindow::OPEN_NEWTAB;
}
static DocumentLoadListener::ProcessBehavior GetProcessSwitchBehavior(
Element* aBrowserElement) {
if (aBrowserElement->HasAttribute(u"maychangeremoteness"_ns)) {
return DocumentLoadListener::ProcessBehavior::PROCESS_BEHAVIOR_STANDARD;
}
nsCOMPtr<nsIBrowser> browser = aBrowserElement->AsBrowser();
bool isRemoteBrowser = false;
browser->GetIsRemoteBrowser(&isRemoteBrowser);
if (isRemoteBrowser) {
return DocumentLoadListener::ProcessBehavior::
PROCESS_BEHAVIOR_SUBFRAME_ONLY;
}
return DocumentLoadListener::ProcessBehavior::PROCESS_BEHAVIOR_DISABLED;
}
static bool ContextCanProcessSwitch(CanonicalBrowsingContext* aBrowsingContext,
WindowGlobalParent* aParentWindow,
bool aSwitchToNewTab) {
if (NS_WARN_IF(!aBrowsingContext)) {
MOZ_LOG(gProcessIsolationLog, LogLevel::Warning,
("Process Switch Abort: no browsing context"));
return false;
}
if (!aBrowsingContext->IsContent()) {
MOZ_LOG(gProcessIsolationLog, LogLevel::Warning,
("Process Switch Abort: non-content browsing context"));
return false;
}
// If we're switching into a new tab, we can skip the remaining checks, as
// we're not actually changing the process of aBrowsingContext, so whether or
// not it is allowed to process switch isn't relevant.
if (aSwitchToNewTab) {
return true;
}
if (aParentWindow && !aBrowsingContext->UseRemoteSubframes()) {
MOZ_LOG(gProcessIsolationLog, LogLevel::Warning,
("Process Switch Abort: remote subframes disabled"));
return false;
}
if (aParentWindow && aParentWindow->IsInProcess()) {
MOZ_LOG(gProcessIsolationLog, LogLevel::Warning,
("Process Switch Abort: Subframe with in-process parent"));
return false;
}
// Determine what process switching behaviour is being requested by the root
// <browser> element.
Element* browserElement = aBrowsingContext->Top()->GetEmbedderElement();
if (!browserElement) {
MOZ_LOG(gProcessIsolationLog, LogLevel::Warning,
("Process Switch Abort: cannot get embedder element"));
return false;
}
nsCOMPtr<nsIBrowser> browser = browserElement->AsBrowser();
if (!browser) {
MOZ_LOG(gProcessIsolationLog, LogLevel::Warning,
("Process Switch Abort: not loaded within nsIBrowser"));
return false;
}
DocumentLoadListener::ProcessBehavior processBehavior =
GetProcessSwitchBehavior(browserElement);
// Check if the process switch we're considering is disabled by the
// <browser>'s process behavior.
if (processBehavior ==
DocumentLoadListener::ProcessBehavior::PROCESS_BEHAVIOR_DISABLED) {
MOZ_LOG(gProcessIsolationLog, LogLevel::Warning,
("Process Switch Abort: switch disabled by <browser>"));
return false;
}
if (!aParentWindow && processBehavior ==
DocumentLoadListener::ProcessBehavior::
PROCESS_BEHAVIOR_SUBFRAME_ONLY) {
MOZ_LOG(gProcessIsolationLog, LogLevel::Warning,
("Process Switch Abort: toplevel switch disabled by <browser>"));
return false;
}
return true;
}
static RefPtr<dom::BrowsingContextCallbackReceivedPromise> SwitchToNewTab(
CanonicalBrowsingContext* aLoadingBrowsingContext, int32_t aWhere) {
MOZ_ASSERT(aWhere == nsIBrowserDOMWindow::OPEN_NEWTAB ||
aWhere == nsIBrowserDOMWindow::OPEN_NEWWINDOW,
"Unsupported open location");
auto promise =
MakeRefPtr<dom::BrowsingContextCallbackReceivedPromise::Private>(
__func__);
// Get the nsIBrowserDOMWindow for the given BrowsingContext's tab.
nsCOMPtr<nsIBrowserDOMWindow> browserDOMWindow =
aLoadingBrowsingContext->GetBrowserDOMWindow();
if (NS_WARN_IF(!browserDOMWindow)) {
MOZ_LOG(gProcessIsolationLog, LogLevel::Warning,
("Process Switch Abort: Unable to get nsIBrowserDOMWindow"));
promise->Reject(NS_ERROR_FAILURE, __func__);
return promise;