Bug 1839454 - Don't try and call gcparam in the browser when running JS reftests...
[gecko.git] / netwerk / base / nsBaseChannel.cpp
blob3ce7fb9d4b5fef9bd623b773bac8535e5a4a606d
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set sw=2 sts=2 ts=8 et tw=80 : */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "nsBaseChannel.h"
8 #include "nsContentUtils.h"
9 #include "nsURLHelper.h"
10 #include "nsNetCID.h"
11 #include "nsMimeTypes.h"
12 #include "nsUnknownDecoder.h"
13 #include "nsIScriptSecurityManager.h"
14 #include "nsMimeTypes.h"
15 #include "nsICancelable.h"
16 #include "nsIChannelEventSink.h"
17 #include "nsIStreamConverterService.h"
18 #include "nsChannelClassifier.h"
19 #include "nsAsyncRedirectVerifyHelper.h"
20 #include "nsProxyRelease.h"
21 #include "nsXULAppAPI.h"
22 #include "nsContentSecurityManager.h"
23 #include "LoadInfo.h"
24 #include "nsServiceManagerUtils.h"
25 #include "nsRedirectHistoryEntry.h"
26 #include "mozilla/AntiTrackingUtils.h"
27 #include "mozilla/BasePrincipal.h"
29 using namespace mozilla;
31 // This class is used to suspend a request across a function scope.
32 class ScopedRequestSuspender {
33 public:
34 explicit ScopedRequestSuspender(nsIRequest* request) : mRequest(request) {
35 if (mRequest && NS_FAILED(mRequest->Suspend())) {
36 NS_WARNING("Couldn't suspend pump");
37 mRequest = nullptr;
40 ~ScopedRequestSuspender() {
41 if (mRequest) mRequest->Resume();
44 private:
45 nsIRequest* mRequest;
48 // Used to suspend data events from mRequest within a function scope. This is
49 // usually needed when a function makes callbacks that could process events.
50 #define SUSPEND_PUMP_FOR_SCOPE() \
51 ScopedRequestSuspender pump_suspender__(mRequest)
53 //-----------------------------------------------------------------------------
54 // nsBaseChannel
56 nsBaseChannel::nsBaseChannel() : NeckoTargetHolder(nullptr) {
57 mContentType.AssignLiteral(UNKNOWN_CONTENT_TYPE);
60 nsBaseChannel::~nsBaseChannel() {
61 NS_ReleaseOnMainThread("nsBaseChannel::mLoadInfo", mLoadInfo.forget());
64 nsresult nsBaseChannel::Redirect(nsIChannel* newChannel, uint32_t redirectFlags,
65 bool openNewChannel) {
66 SUSPEND_PUMP_FOR_SCOPE();
68 // Transfer properties
70 newChannel->SetLoadGroup(mLoadGroup);
71 newChannel->SetNotificationCallbacks(mCallbacks);
72 newChannel->SetLoadFlags(mLoadFlags | LOAD_REPLACE);
74 // make a copy of the loadinfo, append to the redirectchain
75 // and set it on the new channel
76 nsSecurityFlags secFlags =
77 mLoadInfo->GetSecurityFlags() & ~nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL;
78 nsCOMPtr<nsILoadInfo> newLoadInfo =
79 static_cast<net::LoadInfo*>(mLoadInfo.get())
80 ->CloneWithNewSecFlags(secFlags);
82 bool isInternalRedirect =
83 (redirectFlags & (nsIChannelEventSink::REDIRECT_INTERNAL |
84 nsIChannelEventSink::REDIRECT_STS_UPGRADE));
86 newLoadInfo->AppendRedirectHistoryEntry(this, isInternalRedirect);
88 // Ensure the channel's loadInfo's result principal URI so that it's
89 // either non-null or updated to the redirect target URI.
90 // We must do this because in case the loadInfo's result principal URI
91 // is null, it would be taken from OriginalURI of the channel. But we
92 // overwrite it with the whole redirect chain first URI before opening
93 // the target channel, hence the information would be lost.
94 // If the protocol handler that created the channel wants to use
95 // the originalURI of the channel as the principal URI, it has left
96 // the result principal URI on the load info null.
97 nsCOMPtr<nsIURI> resultPrincipalURI;
99 nsCOMPtr<nsILoadInfo> existingLoadInfo = newChannel->LoadInfo();
100 if (existingLoadInfo) {
101 existingLoadInfo->GetResultPrincipalURI(getter_AddRefs(resultPrincipalURI));
103 if (!resultPrincipalURI) {
104 newChannel->GetOriginalURI(getter_AddRefs(resultPrincipalURI));
107 newLoadInfo->SetResultPrincipalURI(resultPrincipalURI);
109 newChannel->SetLoadInfo(newLoadInfo);
111 // Preserve the privacy bit if it has been overridden
112 if (mPrivateBrowsingOverriden) {
113 nsCOMPtr<nsIPrivateBrowsingChannel> newPBChannel =
114 do_QueryInterface(newChannel);
115 if (newPBChannel) {
116 newPBChannel->SetPrivate(mPrivateBrowsing);
120 if (nsCOMPtr<nsIWritablePropertyBag> bag = ::do_QueryInterface(newChannel)) {
121 nsHashPropertyBag::CopyFrom(bag, static_cast<nsIPropertyBag2*>(this));
124 // Notify consumer, giving chance to cancel redirect.
126 auto redirectCallbackHelper = MakeRefPtr<net::nsAsyncRedirectVerifyHelper>();
128 bool checkRedirectSynchronously = !openNewChannel;
129 nsCOMPtr<nsIEventTarget> target = GetNeckoTarget();
131 mRedirectChannel = newChannel;
132 mRedirectFlags = redirectFlags;
133 mOpenRedirectChannel = openNewChannel;
134 nsresult rv = redirectCallbackHelper->Init(
135 this, newChannel, redirectFlags, target, checkRedirectSynchronously);
136 if (NS_FAILED(rv)) return rv;
138 if (checkRedirectSynchronously && NS_FAILED(mStatus)) return mStatus;
140 return NS_OK;
143 nsresult nsBaseChannel::ContinueRedirect() {
144 // Make sure to do this _after_ making all the OnChannelRedirect calls
145 mRedirectChannel->SetOriginalURI(OriginalURI());
147 // If we fail to open the new channel, then we want to leave this channel
148 // unaffected, so we defer tearing down our channel until we have succeeded
149 // with the redirect.
151 if (mOpenRedirectChannel) {
152 nsresult rv = NS_OK;
153 rv = mRedirectChannel->AsyncOpen(mListener);
154 NS_ENSURE_SUCCESS(rv, rv);
157 mRedirectChannel = nullptr;
159 // close down this channel
160 Cancel(NS_BINDING_REDIRECTED);
161 ChannelDone();
163 return NS_OK;
166 bool nsBaseChannel::HasContentTypeHint() const {
167 NS_ASSERTION(!Pending(), "HasContentTypeHint called too late");
168 return !mContentType.EqualsLiteral(UNKNOWN_CONTENT_TYPE);
171 nsresult nsBaseChannel::BeginPumpingData() {
172 nsresult rv;
174 rv = BeginAsyncRead(this, getter_AddRefs(mRequest),
175 getter_AddRefs(mCancelableAsyncRequest));
176 if (NS_SUCCEEDED(rv)) {
177 MOZ_ASSERT(mRequest || mCancelableAsyncRequest,
178 "should have got a request or cancelable");
179 mPumpingData = true;
180 return NS_OK;
182 if (rv != NS_ERROR_NOT_IMPLEMENTED) {
183 return rv;
186 nsCOMPtr<nsIInputStream> stream;
187 nsCOMPtr<nsIChannel> channel;
188 rv = OpenContentStream(true, getter_AddRefs(stream), getter_AddRefs(channel));
189 if (NS_FAILED(rv)) return rv;
191 NS_ASSERTION(!stream || !channel, "Got both a channel and a stream?");
193 if (channel) {
194 nsCOMPtr<nsIRunnable> runnable = new RedirectRunnable(this, channel);
195 rv = Dispatch(runnable.forget());
196 if (NS_SUCCEEDED(rv)) mWaitingOnAsyncRedirect = true;
197 return rv;
200 // By assigning mPump, we flag this channel as pending (see Pending). It's
201 // important that the pending flag is set when we call into the stream (the
202 // call to AsyncRead results in the stream's AsyncWait method being called)
203 // and especially when we call into the loadgroup. Our caller takes care to
204 // release mPump if we return an error.
206 nsCOMPtr<nsISerialEventTarget> target = GetNeckoTarget();
207 rv = nsInputStreamPump::Create(getter_AddRefs(mPump), stream, 0, 0, true,
208 target);
209 if (NS_FAILED(rv)) {
210 return rv;
213 mPumpingData = true;
214 mRequest = mPump;
215 rv = mPump->AsyncRead(this);
216 if (NS_FAILED(rv)) {
217 return rv;
220 RefPtr<BlockingPromise> promise;
221 rv = ListenerBlockingPromise(getter_AddRefs(promise));
222 if (NS_FAILED(rv)) {
223 return rv;
226 if (promise) {
227 mPump->Suspend();
229 RefPtr<nsBaseChannel> self(this);
231 promise->Then(
232 target, __func__,
233 [self, this](nsresult rv) {
234 MOZ_ASSERT(mPump);
235 MOZ_ASSERT(NS_SUCCEEDED(rv));
236 mPump->Resume();
238 [self, this](nsresult rv) {
239 MOZ_ASSERT(mPump);
240 MOZ_ASSERT(NS_FAILED(rv));
241 Cancel(rv);
242 mPump->Resume();
246 return NS_OK;
249 void nsBaseChannel::HandleAsyncRedirect(nsIChannel* newChannel) {
250 NS_ASSERTION(!mPumpingData, "Shouldn't have gotten here");
252 nsresult rv = mStatus;
253 if (NS_SUCCEEDED(mStatus)) {
254 rv = Redirect(newChannel, nsIChannelEventSink::REDIRECT_TEMPORARY, true);
255 if (NS_SUCCEEDED(rv)) {
256 // OnRedirectVerifyCallback will be called asynchronously
257 return;
261 ContinueHandleAsyncRedirect(rv);
264 void nsBaseChannel::ContinueHandleAsyncRedirect(nsresult result) {
265 mWaitingOnAsyncRedirect = false;
267 if (NS_FAILED(result)) Cancel(result);
269 if (NS_FAILED(result) && mListener) {
270 // Notify our consumer ourselves
271 mListener->OnStartRequest(this);
272 mListener->OnStopRequest(this, mStatus);
273 ChannelDone();
276 if (mLoadGroup) mLoadGroup->RemoveRequest(this, nullptr, mStatus);
278 // Drop notification callbacks to prevent cycles.
279 mCallbacks = nullptr;
280 CallbacksChanged();
283 void nsBaseChannel::ClassifyURI() {
284 // For channels created in the child process, delegate to the parent to
285 // classify URIs.
286 if (!XRE_IsParentProcess()) {
287 return;
290 if (NS_ShouldClassifyChannel(this)) {
291 auto classifier = MakeRefPtr<net::nsChannelClassifier>(this);
292 classifier->Start();
296 //-----------------------------------------------------------------------------
297 // nsBaseChannel::nsISupports
299 NS_IMPL_ADDREF(nsBaseChannel)
300 NS_IMPL_RELEASE(nsBaseChannel)
302 NS_INTERFACE_MAP_BEGIN(nsBaseChannel)
303 NS_INTERFACE_MAP_ENTRY(nsIRequest)
304 NS_INTERFACE_MAP_ENTRY(nsIChannel)
305 NS_INTERFACE_MAP_ENTRY(nsIThreadRetargetableRequest)
306 NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
307 NS_INTERFACE_MAP_ENTRY(nsITransportEventSink)
308 NS_INTERFACE_MAP_ENTRY(nsIRequestObserver)
309 NS_INTERFACE_MAP_ENTRY(nsIStreamListener)
310 NS_INTERFACE_MAP_ENTRY(nsIThreadRetargetableStreamListener)
311 NS_INTERFACE_MAP_ENTRY(nsIAsyncVerifyRedirectCallback)
312 NS_INTERFACE_MAP_ENTRY(nsIPrivateBrowsingChannel)
313 NS_INTERFACE_MAP_END_INHERITING(nsHashPropertyBag)
315 //-----------------------------------------------------------------------------
316 // nsBaseChannel::nsIRequest
318 NS_IMETHODIMP
319 nsBaseChannel::GetName(nsACString& result) {
320 if (!mURI) {
321 result.Truncate();
322 return NS_OK;
324 return mURI->GetSpec(result);
327 NS_IMETHODIMP
328 nsBaseChannel::IsPending(bool* result) {
329 *result = Pending();
330 return NS_OK;
333 NS_IMETHODIMP
334 nsBaseChannel::GetStatus(nsresult* status) {
335 if (mRequest && NS_SUCCEEDED(mStatus)) {
336 mRequest->GetStatus(status);
337 } else {
338 *status = mStatus;
340 return NS_OK;
343 NS_IMETHODIMP nsBaseChannel::SetCanceledReason(const nsACString& aReason) {
344 return SetCanceledReasonImpl(aReason);
347 NS_IMETHODIMP nsBaseChannel::GetCanceledReason(nsACString& aReason) {
348 return GetCanceledReasonImpl(aReason);
351 NS_IMETHODIMP nsBaseChannel::CancelWithReason(nsresult aStatus,
352 const nsACString& aReason) {
353 return CancelWithReasonImpl(aStatus, aReason);
356 NS_IMETHODIMP
357 nsBaseChannel::Cancel(nsresult status) {
358 // Ignore redundant cancelation
359 if (mCanceled) {
360 return NS_OK;
363 mCanceled = true;
364 mStatus = status;
366 if (mCancelableAsyncRequest) {
367 mCancelableAsyncRequest->Cancel(status);
370 if (mRequest) {
371 mRequest->Cancel(status);
374 return NS_OK;
377 NS_IMETHODIMP
378 nsBaseChannel::Suspend() {
379 NS_ENSURE_TRUE(mPumpingData, NS_ERROR_NOT_INITIALIZED);
380 NS_ENSURE_TRUE(mRequest, NS_ERROR_NOT_IMPLEMENTED);
381 return mRequest->Suspend();
384 NS_IMETHODIMP
385 nsBaseChannel::Resume() {
386 NS_ENSURE_TRUE(mPumpingData, NS_ERROR_NOT_INITIALIZED);
387 NS_ENSURE_TRUE(mRequest, NS_ERROR_NOT_IMPLEMENTED);
388 return mRequest->Resume();
391 NS_IMETHODIMP
392 nsBaseChannel::GetLoadFlags(nsLoadFlags* aLoadFlags) {
393 *aLoadFlags = mLoadFlags;
394 return NS_OK;
397 NS_IMETHODIMP
398 nsBaseChannel::SetLoadFlags(nsLoadFlags aLoadFlags) {
399 mLoadFlags = aLoadFlags;
400 return NS_OK;
403 NS_IMETHODIMP
404 nsBaseChannel::GetTRRMode(nsIRequest::TRRMode* aTRRMode) {
405 return GetTRRModeImpl(aTRRMode);
408 NS_IMETHODIMP
409 nsBaseChannel::SetTRRMode(nsIRequest::TRRMode aTRRMode) {
410 return SetTRRModeImpl(aTRRMode);
413 NS_IMETHODIMP
414 nsBaseChannel::GetLoadGroup(nsILoadGroup** aLoadGroup) {
415 nsCOMPtr<nsILoadGroup> loadGroup(mLoadGroup);
416 loadGroup.forget(aLoadGroup);
417 return NS_OK;
420 NS_IMETHODIMP
421 nsBaseChannel::SetLoadGroup(nsILoadGroup* aLoadGroup) {
422 if (!CanSetLoadGroup(aLoadGroup)) {
423 return NS_ERROR_FAILURE;
426 mLoadGroup = aLoadGroup;
427 CallbacksChanged();
428 UpdatePrivateBrowsing();
429 return NS_OK;
432 //-----------------------------------------------------------------------------
433 // nsBaseChannel::nsIChannel
435 NS_IMETHODIMP
436 nsBaseChannel::GetOriginalURI(nsIURI** aURI) {
437 RefPtr<nsIURI> uri = OriginalURI();
438 uri.forget(aURI);
439 return NS_OK;
442 NS_IMETHODIMP
443 nsBaseChannel::SetOriginalURI(nsIURI* aURI) {
444 NS_ENSURE_ARG_POINTER(aURI);
445 mOriginalURI = aURI;
446 return NS_OK;
449 NS_IMETHODIMP
450 nsBaseChannel::GetURI(nsIURI** aURI) {
451 nsCOMPtr<nsIURI> uri(mURI);
452 uri.forget(aURI);
453 return NS_OK;
456 NS_IMETHODIMP
457 nsBaseChannel::GetOwner(nsISupports** aOwner) {
458 nsCOMPtr<nsISupports> owner(mOwner);
459 owner.forget(aOwner);
460 return NS_OK;
463 NS_IMETHODIMP
464 nsBaseChannel::SetOwner(nsISupports* aOwner) {
465 mOwner = aOwner;
466 return NS_OK;
469 NS_IMETHODIMP
470 nsBaseChannel::SetLoadInfo(nsILoadInfo* aLoadInfo) {
471 MOZ_RELEASE_ASSERT(aLoadInfo, "loadinfo can't be null");
472 mLoadInfo = aLoadInfo;
474 // Need to update |mNeckoTarget| when load info has changed.
475 SetupNeckoTarget();
476 return NS_OK;
479 NS_IMETHODIMP
480 nsBaseChannel::GetLoadInfo(nsILoadInfo** aLoadInfo) {
481 nsCOMPtr<nsILoadInfo> loadInfo(mLoadInfo);
482 loadInfo.forget(aLoadInfo);
483 return NS_OK;
486 NS_IMETHODIMP
487 nsBaseChannel::GetIsDocument(bool* aIsDocument) {
488 return NS_GetIsDocumentChannel(this, aIsDocument);
491 NS_IMETHODIMP
492 nsBaseChannel::GetNotificationCallbacks(nsIInterfaceRequestor** aCallbacks) {
493 nsCOMPtr<nsIInterfaceRequestor> callbacks(mCallbacks);
494 callbacks.forget(aCallbacks);
495 return NS_OK;
498 NS_IMETHODIMP
499 nsBaseChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aCallbacks) {
500 if (!CanSetCallbacks(aCallbacks)) {
501 return NS_ERROR_FAILURE;
504 mCallbacks = aCallbacks;
505 CallbacksChanged();
506 UpdatePrivateBrowsing();
507 return NS_OK;
510 NS_IMETHODIMP
511 nsBaseChannel::GetSecurityInfo(nsITransportSecurityInfo** aSecurityInfo) {
512 *aSecurityInfo = do_AddRef(mSecurityInfo).take();
513 return NS_OK;
516 NS_IMETHODIMP
517 nsBaseChannel::GetContentType(nsACString& aContentType) {
518 aContentType = mContentType;
519 return NS_OK;
522 NS_IMETHODIMP
523 nsBaseChannel::SetContentType(const nsACString& aContentType) {
524 // mContentCharset is unchanged if not parsed
525 bool dummy;
526 net_ParseContentType(aContentType, mContentType, mContentCharset, &dummy);
527 return NS_OK;
530 NS_IMETHODIMP
531 nsBaseChannel::GetContentCharset(nsACString& aContentCharset) {
532 aContentCharset = mContentCharset;
533 return NS_OK;
536 NS_IMETHODIMP
537 nsBaseChannel::SetContentCharset(const nsACString& aContentCharset) {
538 mContentCharset = aContentCharset;
539 return NS_OK;
542 NS_IMETHODIMP
543 nsBaseChannel::GetContentDisposition(uint32_t* aContentDisposition) {
544 // preserve old behavior, fail unless explicitly set.
545 if (mContentDispositionHint == UINT32_MAX) {
546 return NS_ERROR_NOT_AVAILABLE;
549 *aContentDisposition = mContentDispositionHint;
550 return NS_OK;
553 NS_IMETHODIMP
554 nsBaseChannel::SetContentDisposition(uint32_t aContentDisposition) {
555 mContentDispositionHint = aContentDisposition;
556 return NS_OK;
559 NS_IMETHODIMP
560 nsBaseChannel::GetContentDispositionFilename(
561 nsAString& aContentDispositionFilename) {
562 if (!mContentDispositionFilename) {
563 return NS_ERROR_NOT_AVAILABLE;
566 aContentDispositionFilename = *mContentDispositionFilename;
567 return NS_OK;
570 NS_IMETHODIMP
571 nsBaseChannel::SetContentDispositionFilename(
572 const nsAString& aContentDispositionFilename) {
573 mContentDispositionFilename =
574 MakeUnique<nsString>(aContentDispositionFilename);
576 // For safety reasons ensure the filename doesn't contain null characters and
577 // replace them with underscores. We may later pass the extension to system
578 // MIME APIs that expect null terminated strings.
579 mContentDispositionFilename->ReplaceChar(char16_t(0), '_');
581 return NS_OK;
584 NS_IMETHODIMP
585 nsBaseChannel::GetContentDispositionHeader(
586 nsACString& aContentDispositionHeader) {
587 return NS_ERROR_NOT_AVAILABLE;
590 NS_IMETHODIMP
591 nsBaseChannel::GetContentLength(int64_t* aContentLength) {
592 *aContentLength = mContentLength;
593 return NS_OK;
596 NS_IMETHODIMP
597 nsBaseChannel::SetContentLength(int64_t aContentLength) {
598 mContentLength = aContentLength;
599 return NS_OK;
602 NS_IMETHODIMP
603 nsBaseChannel::Open(nsIInputStream** aStream) {
604 nsCOMPtr<nsIStreamListener> listener;
605 nsresult rv =
606 nsContentSecurityManager::doContentSecurityCheck(this, listener);
607 NS_ENSURE_SUCCESS(rv, rv);
609 NS_ENSURE_TRUE(mURI, NS_ERROR_NOT_INITIALIZED);
610 NS_ENSURE_TRUE(!mPumpingData, NS_ERROR_IN_PROGRESS);
611 NS_ENSURE_TRUE(!mWasOpened, NS_ERROR_IN_PROGRESS);
613 nsCOMPtr<nsIChannel> chan;
614 rv = OpenContentStream(false, aStream, getter_AddRefs(chan));
615 NS_ASSERTION(!chan || !*aStream, "Got both a channel and a stream?");
616 if (NS_SUCCEEDED(rv) && chan) {
617 rv = Redirect(chan, nsIChannelEventSink::REDIRECT_INTERNAL, false);
618 if (NS_FAILED(rv)) return rv;
619 rv = chan->Open(aStream);
620 } else if (rv == NS_ERROR_NOT_IMPLEMENTED) {
621 return NS_ImplementChannelOpen(this, aStream);
624 if (NS_SUCCEEDED(rv)) {
625 mWasOpened = true;
626 ClassifyURI();
629 return rv;
632 NS_IMETHODIMP
633 nsBaseChannel::AsyncOpen(nsIStreamListener* aListener) {
634 nsCOMPtr<nsIStreamListener> listener = aListener;
636 nsresult rv =
637 nsContentSecurityManager::doContentSecurityCheck(this, listener);
638 if (NS_FAILED(rv)) {
639 mCallbacks = nullptr;
640 return rv;
643 MOZ_ASSERT(
644 mLoadInfo->GetSecurityMode() == 0 ||
645 mLoadInfo->GetInitialSecurityCheckDone() ||
646 (mLoadInfo->GetSecurityMode() ==
647 nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL &&
648 mLoadInfo->GetLoadingPrincipal() &&
649 mLoadInfo->GetLoadingPrincipal()->IsSystemPrincipal()),
650 "security flags in loadInfo but doContentSecurityCheck() not called");
652 NS_ENSURE_TRUE(mURI, NS_ERROR_NOT_INITIALIZED);
653 NS_ENSURE_TRUE(!mPumpingData, NS_ERROR_IN_PROGRESS);
654 NS_ENSURE_TRUE(!mWasOpened, NS_ERROR_ALREADY_OPENED);
655 NS_ENSURE_ARG(listener);
657 SetupNeckoTarget();
659 // Skip checking for chrome:// sub-resources.
660 nsAutoCString scheme;
661 mURI->GetScheme(scheme);
662 if (!scheme.EqualsLiteral("file")) {
663 NS_CompareLoadInfoAndLoadContext(this);
666 // Ensure that this is an allowed port before proceeding.
667 rv = NS_CheckPortSafety(mURI);
668 if (NS_FAILED(rv)) {
669 mCallbacks = nullptr;
670 return rv;
673 AntiTrackingUtils::UpdateAntiTrackingInfoForChannel(this);
675 // Store the listener and context early so that OpenContentStream and the
676 // stream's AsyncWait method (called by AsyncRead) can have access to them
677 // via the StreamListener methods. However, since
678 // this typically introduces a reference cycle between this and the listener,
679 // we need to be sure to break the reference if this method does not succeed.
680 mListener = listener;
682 // This method assigns mPump as a side-effect. We need to clear mPump if
683 // this method fails.
684 rv = BeginPumpingData();
685 if (NS_FAILED(rv)) {
686 mPump = nullptr;
687 mRequest = nullptr;
688 mPumpingData = false;
689 ChannelDone();
690 mCallbacks = nullptr;
691 return rv;
694 // At this point, we are going to return success no matter what.
696 mWasOpened = true;
698 SUSPEND_PUMP_FOR_SCOPE();
700 if (mLoadGroup) mLoadGroup->AddRequest(this, nullptr);
702 ClassifyURI();
704 return NS_OK;
707 //-----------------------------------------------------------------------------
708 // nsBaseChannel::nsITransportEventSink
710 NS_IMETHODIMP
711 nsBaseChannel::OnTransportStatus(nsITransport* transport, nsresult status,
712 int64_t progress, int64_t progressMax) {
713 // In some cases, we may wish to suppress transport-layer status events.
715 if (!mPumpingData || NS_FAILED(mStatus)) {
716 return NS_OK;
719 SUSPEND_PUMP_FOR_SCOPE();
721 // Lazily fetch mProgressSink
722 if (!mProgressSink) {
723 if (mQueriedProgressSink) {
724 return NS_OK;
726 GetCallback(mProgressSink);
727 mQueriedProgressSink = true;
728 if (!mProgressSink) {
729 return NS_OK;
733 if (!HasLoadFlag(LOAD_BACKGROUND)) {
734 nsAutoString statusArg;
735 if (GetStatusArg(status, statusArg)) {
736 mProgressSink->OnStatus(this, status, statusArg.get());
740 if (progress) {
741 mProgressSink->OnProgress(this, progress, progressMax);
744 return NS_OK;
747 //-----------------------------------------------------------------------------
748 // nsBaseChannel::nsIInterfaceRequestor
750 NS_IMETHODIMP
751 nsBaseChannel::GetInterface(const nsIID& iid, void** result) {
752 NS_QueryNotificationCallbacks(mCallbacks, mLoadGroup, iid, result);
753 return *result ? NS_OK : NS_ERROR_NO_INTERFACE;
756 //-----------------------------------------------------------------------------
757 // nsBaseChannel::nsIRequestObserver
759 static void CallTypeSniffers(void* aClosure, const uint8_t* aData,
760 uint32_t aCount) {
761 nsIChannel* chan = static_cast<nsIChannel*>(aClosure);
763 nsAutoCString newType;
764 NS_SniffContent(NS_CONTENT_SNIFFER_CATEGORY, chan, aData, aCount, newType);
765 if (!newType.IsEmpty()) {
766 chan->SetContentType(newType);
770 static void CallUnknownTypeSniffer(void* aClosure, const uint8_t* aData,
771 uint32_t aCount) {
772 nsIChannel* chan = static_cast<nsIChannel*>(aClosure);
774 RefPtr<nsUnknownDecoder> sniffer = new nsUnknownDecoder();
776 nsAutoCString detected;
777 nsresult rv = sniffer->GetMIMETypeFromContent(chan, aData, aCount, detected);
778 if (NS_SUCCEEDED(rv)) chan->SetContentType(detected);
781 NS_IMETHODIMP
782 nsBaseChannel::OnStartRequest(nsIRequest* request) {
783 MOZ_ASSERT_IF(mRequest, request == mRequest);
784 MOZ_ASSERT_IF(mCancelableAsyncRequest, !mRequest);
786 nsAutoCString scheme;
787 mURI->GetScheme(scheme);
789 if (mPump && !scheme.EqualsLiteral("ftp")) {
790 // If our content type is unknown, use the content type
791 // sniffer. If the sniffer is not available for some reason, then we just
792 // keep going as-is.
793 if (NS_SUCCEEDED(mStatus) &&
794 mContentType.EqualsLiteral(UNKNOWN_CONTENT_TYPE)) {
795 mPump->PeekStream(CallUnknownTypeSniffer, static_cast<nsIChannel*>(this));
798 // Now, the general type sniffers. Skip this if we have none.
799 if (mLoadFlags & LOAD_CALL_CONTENT_SNIFFERS) {
800 mPump->PeekStream(CallTypeSniffers, static_cast<nsIChannel*>(this));
804 SUSPEND_PUMP_FOR_SCOPE();
806 if (mListener) { // null in case of redirect
807 return mListener->OnStartRequest(this);
809 return NS_OK;
812 NS_IMETHODIMP
813 nsBaseChannel::OnStopRequest(nsIRequest* request, nsresult status) {
814 // If both mStatus and status are failure codes, we keep mStatus as-is since
815 // that is consistent with our GetStatus and Cancel methods.
816 if (NS_SUCCEEDED(mStatus)) mStatus = status;
818 // Cause Pending to return false.
819 mPump = nullptr;
820 mRequest = nullptr;
821 mCancelableAsyncRequest = nullptr;
822 mPumpingData = false;
824 if (mListener) { // null in case of redirect
825 mListener->OnStopRequest(this, mStatus);
827 ChannelDone();
829 // No need to suspend pump in this scope since we will not be receiving
830 // any more events from it.
832 if (mLoadGroup) mLoadGroup->RemoveRequest(this, nullptr, mStatus);
834 // Drop notification callbacks to prevent cycles.
835 mCallbacks = nullptr;
836 CallbacksChanged();
838 return NS_OK;
841 //-----------------------------------------------------------------------------
842 // nsBaseChannel::nsIStreamListener
844 NS_IMETHODIMP
845 nsBaseChannel::OnDataAvailable(nsIRequest* request, nsIInputStream* stream,
846 uint64_t offset, uint32_t count) {
847 SUSPEND_PUMP_FOR_SCOPE();
849 nsresult rv = mListener->OnDataAvailable(this, stream, offset, count);
850 if (mSynthProgressEvents && NS_SUCCEEDED(rv)) {
851 int64_t prog = offset + count;
852 if (NS_IsMainThread()) {
853 OnTransportStatus(nullptr, NS_NET_STATUS_READING, prog, mContentLength);
854 } else {
855 class OnTransportStatusAsyncEvent : public Runnable {
856 RefPtr<nsBaseChannel> mChannel;
857 int64_t mProgress;
858 int64_t mContentLength;
860 public:
861 OnTransportStatusAsyncEvent(nsBaseChannel* aChannel, int64_t aProgress,
862 int64_t aContentLength)
863 : Runnable("OnTransportStatusAsyncEvent"),
864 mChannel(aChannel),
865 mProgress(aProgress),
866 mContentLength(aContentLength) {}
868 NS_IMETHOD Run() override {
869 return mChannel->OnTransportStatus(nullptr, NS_NET_STATUS_READING,
870 mProgress, mContentLength);
874 nsCOMPtr<nsIRunnable> runnable =
875 new OnTransportStatusAsyncEvent(this, prog, mContentLength);
876 Dispatch(runnable.forget());
880 return rv;
883 NS_IMETHODIMP
884 nsBaseChannel::OnRedirectVerifyCallback(nsresult result) {
885 if (NS_SUCCEEDED(result)) result = ContinueRedirect();
887 if (NS_FAILED(result) && !mWaitingOnAsyncRedirect) {
888 if (NS_SUCCEEDED(mStatus)) mStatus = result;
889 return NS_OK;
892 if (mWaitingOnAsyncRedirect) ContinueHandleAsyncRedirect(result);
894 return NS_OK;
897 NS_IMETHODIMP
898 nsBaseChannel::RetargetDeliveryTo(nsISerialEventTarget* aEventTarget) {
899 MOZ_ASSERT(NS_IsMainThread());
901 NS_ENSURE_TRUE(mRequest, NS_ERROR_NOT_INITIALIZED);
903 nsCOMPtr<nsIThreadRetargetableRequest> req;
904 if (mAllowThreadRetargeting) {
905 req = do_QueryInterface(mRequest);
908 NS_ENSURE_TRUE(req, NS_ERROR_NOT_IMPLEMENTED);
910 return req->RetargetDeliveryTo(aEventTarget);
913 NS_IMETHODIMP
914 nsBaseChannel::GetDeliveryTarget(nsISerialEventTarget** aEventTarget) {
915 MOZ_ASSERT(NS_IsMainThread());
917 NS_ENSURE_TRUE(mRequest, NS_ERROR_NOT_INITIALIZED);
919 nsCOMPtr<nsIThreadRetargetableRequest> req;
920 req = do_QueryInterface(mRequest);
922 NS_ENSURE_TRUE(req, NS_ERROR_NOT_IMPLEMENTED);
923 return req->GetDeliveryTarget(aEventTarget);
926 NS_IMETHODIMP
927 nsBaseChannel::CheckListenerChain() {
928 MOZ_ASSERT(NS_IsMainThread());
930 if (!mAllowThreadRetargeting) {
931 return NS_ERROR_NOT_IMPLEMENTED;
934 nsCOMPtr<nsIThreadRetargetableStreamListener> listener =
935 do_QueryInterface(mListener);
936 if (!listener) {
937 return NS_ERROR_NO_INTERFACE;
940 return listener->CheckListenerChain();
943 NS_IMETHODIMP nsBaseChannel::GetCanceled(bool* aCanceled) {
944 *aCanceled = mCanceled;
945 return NS_OK;
948 void nsBaseChannel::SetupNeckoTarget() {
949 mNeckoTarget =
950 nsContentUtils::GetEventTargetByLoadInfo(mLoadInfo, TaskCategory::Other);