Bug 1875768 - Call the appropriate postfork handler on MacOS r=glandium
[gecko.git] / netwerk / base / nsBaseChannel.cpp
blob2671b5886a2ec5ed8bda912915f68b596ebfc2cd
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 "nsUnknownDecoder.h"
12 #include "nsIScriptSecurityManager.h"
13 #include "nsMimeTypes.h"
14 #include "nsICancelable.h"
15 #include "nsIChannelEventSink.h"
16 #include "nsIStreamConverterService.h"
17 #include "nsChannelClassifier.h"
18 #include "nsAsyncRedirectVerifyHelper.h"
19 #include "nsProxyRelease.h"
20 #include "nsXULAppAPI.h"
21 #include "nsContentSecurityManager.h"
22 #include "LoadInfo.h"
23 #include "nsServiceManagerUtils.h"
24 #include "nsRedirectHistoryEntry.h"
25 #include "mozilla/AntiTrackingUtils.h"
26 #include "mozilla/BasePrincipal.h"
28 using namespace mozilla;
30 // This class is used to suspend a request across a function scope.
31 class ScopedRequestSuspender {
32 public:
33 explicit ScopedRequestSuspender(nsIRequest* request) : mRequest(request) {
34 if (mRequest && NS_FAILED(mRequest->Suspend())) {
35 NS_WARNING("Couldn't suspend pump");
36 mRequest = nullptr;
39 ~ScopedRequestSuspender() {
40 if (mRequest) mRequest->Resume();
43 private:
44 nsIRequest* mRequest;
47 // Used to suspend data events from mRequest within a function scope. This is
48 // usually needed when a function makes callbacks that could process events.
49 #define SUSPEND_PUMP_FOR_SCOPE() \
50 ScopedRequestSuspender pump_suspender__(mRequest)
52 //-----------------------------------------------------------------------------
53 // nsBaseChannel
55 nsBaseChannel::nsBaseChannel() : NeckoTargetHolder(nullptr) {
56 mContentType.AssignLiteral(UNKNOWN_CONTENT_TYPE);
59 nsBaseChannel::~nsBaseChannel() {
60 NS_ReleaseOnMainThread("nsBaseChannel::mLoadInfo", mLoadInfo.forget());
63 nsresult nsBaseChannel::Redirect(nsIChannel* newChannel, uint32_t redirectFlags,
64 bool openNewChannel) {
65 SUSPEND_PUMP_FOR_SCOPE();
67 // Transfer properties
69 newChannel->SetLoadGroup(mLoadGroup);
70 newChannel->SetNotificationCallbacks(mCallbacks);
71 newChannel->SetLoadFlags(mLoadFlags | LOAD_REPLACE);
73 // make a copy of the loadinfo, append to the redirectchain
74 // and set it on the new channel
75 nsSecurityFlags secFlags =
76 mLoadInfo->GetSecurityFlags() & ~nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL;
77 nsCOMPtr<nsILoadInfo> newLoadInfo =
78 static_cast<net::LoadInfo*>(mLoadInfo.get())
79 ->CloneWithNewSecFlags(secFlags);
81 bool isInternalRedirect =
82 (redirectFlags & (nsIChannelEventSink::REDIRECT_INTERNAL |
83 nsIChannelEventSink::REDIRECT_STS_UPGRADE));
85 newLoadInfo->AppendRedirectHistoryEntry(this, isInternalRedirect);
87 // Ensure the channel's loadInfo's result principal URI so that it's
88 // either non-null or updated to the redirect target URI.
89 // We must do this because in case the loadInfo's result principal URI
90 // is null, it would be taken from OriginalURI of the channel. But we
91 // overwrite it with the whole redirect chain first URI before opening
92 // the target channel, hence the information would be lost.
93 // If the protocol handler that created the channel wants to use
94 // the originalURI of the channel as the principal URI, it has left
95 // the result principal URI on the load info null.
96 nsCOMPtr<nsIURI> resultPrincipalURI;
98 nsCOMPtr<nsILoadInfo> existingLoadInfo = newChannel->LoadInfo();
99 if (existingLoadInfo) {
100 existingLoadInfo->GetResultPrincipalURI(getter_AddRefs(resultPrincipalURI));
102 if (!resultPrincipalURI) {
103 newChannel->GetOriginalURI(getter_AddRefs(resultPrincipalURI));
106 newLoadInfo->SetResultPrincipalURI(resultPrincipalURI);
108 newChannel->SetLoadInfo(newLoadInfo);
110 // Preserve the privacy bit if it has been overridden
111 if (mPrivateBrowsingOverriden) {
112 nsCOMPtr<nsIPrivateBrowsingChannel> newPBChannel =
113 do_QueryInterface(newChannel);
114 if (newPBChannel) {
115 newPBChannel->SetPrivate(mPrivateBrowsing);
119 if (nsCOMPtr<nsIWritablePropertyBag> bag = ::do_QueryInterface(newChannel)) {
120 nsHashPropertyBag::CopyFrom(bag, static_cast<nsIPropertyBag2*>(this));
123 // Notify consumer, giving chance to cancel redirect.
125 auto redirectCallbackHelper = MakeRefPtr<net::nsAsyncRedirectVerifyHelper>();
127 bool checkRedirectSynchronously = !openNewChannel;
128 nsCOMPtr<nsIEventTarget> target = GetNeckoTarget();
130 mRedirectChannel = newChannel;
131 mRedirectFlags = redirectFlags;
132 mOpenRedirectChannel = openNewChannel;
133 nsresult rv = redirectCallbackHelper->Init(
134 this, newChannel, redirectFlags, target, checkRedirectSynchronously);
135 if (NS_FAILED(rv)) return rv;
137 if (checkRedirectSynchronously && NS_FAILED(mStatus)) return mStatus;
139 return NS_OK;
142 nsresult nsBaseChannel::ContinueRedirect() {
143 // Make sure to do this _after_ making all the OnChannelRedirect calls
144 mRedirectChannel->SetOriginalURI(OriginalURI());
146 // If we fail to open the new channel, then we want to leave this channel
147 // unaffected, so we defer tearing down our channel until we have succeeded
148 // with the redirect.
150 if (mOpenRedirectChannel) {
151 nsresult rv = NS_OK;
152 rv = mRedirectChannel->AsyncOpen(mListener);
153 NS_ENSURE_SUCCESS(rv, rv);
156 mRedirectChannel = nullptr;
158 // close down this channel
159 Cancel(NS_BINDING_REDIRECTED);
160 ChannelDone();
162 return NS_OK;
165 bool nsBaseChannel::HasContentTypeHint() const {
166 NS_ASSERTION(!Pending(), "HasContentTypeHint called too late");
167 return !mContentType.EqualsLiteral(UNKNOWN_CONTENT_TYPE);
170 nsresult nsBaseChannel::BeginPumpingData() {
171 nsresult rv;
173 rv = BeginAsyncRead(this, getter_AddRefs(mRequest),
174 getter_AddRefs(mCancelableAsyncRequest));
175 if (NS_SUCCEEDED(rv)) {
176 MOZ_ASSERT(mRequest || mCancelableAsyncRequest,
177 "should have got a request or cancelable");
178 mPumpingData = true;
179 return NS_OK;
181 if (rv != NS_ERROR_NOT_IMPLEMENTED) {
182 return rv;
185 nsCOMPtr<nsIInputStream> stream;
186 nsCOMPtr<nsIChannel> channel;
187 rv = OpenContentStream(true, getter_AddRefs(stream), getter_AddRefs(channel));
188 if (NS_FAILED(rv)) return rv;
190 NS_ASSERTION(!stream || !channel, "Got both a channel and a stream?");
192 if (channel) {
193 nsCOMPtr<nsIRunnable> runnable = new RedirectRunnable(this, channel);
194 rv = Dispatch(runnable.forget());
195 if (NS_SUCCEEDED(rv)) mWaitingOnAsyncRedirect = true;
196 return rv;
199 // By assigning mPump, we flag this channel as pending (see Pending). It's
200 // important that the pending flag is set when we call into the stream (the
201 // call to AsyncRead results in the stream's AsyncWait method being called)
202 // and especially when we call into the loadgroup. Our caller takes care to
203 // release mPump if we return an error.
205 nsCOMPtr<nsISerialEventTarget> target = GetNeckoTarget();
206 rv = nsInputStreamPump::Create(getter_AddRefs(mPump), stream, 0, 0, true,
207 target);
208 if (NS_FAILED(rv)) {
209 return rv;
212 mPumpingData = true;
213 mRequest = mPump;
214 rv = mPump->AsyncRead(this);
215 if (NS_FAILED(rv)) {
216 return rv;
219 RefPtr<BlockingPromise> promise;
220 rv = ListenerBlockingPromise(getter_AddRefs(promise));
221 if (NS_FAILED(rv)) {
222 return rv;
225 if (promise) {
226 mPump->Suspend();
228 RefPtr<nsBaseChannel> self(this);
230 promise->Then(
231 target, __func__,
232 [self, this](nsresult rv) {
233 MOZ_ASSERT(mPump);
234 MOZ_ASSERT(NS_SUCCEEDED(rv));
235 mPump->Resume();
237 [self, this](nsresult rv) {
238 MOZ_ASSERT(mPump);
239 MOZ_ASSERT(NS_FAILED(rv));
240 Cancel(rv);
241 mPump->Resume();
245 return NS_OK;
248 void nsBaseChannel::HandleAsyncRedirect(nsIChannel* newChannel) {
249 NS_ASSERTION(!mPumpingData, "Shouldn't have gotten here");
251 nsresult rv = mStatus;
252 if (NS_SUCCEEDED(mStatus)) {
253 rv = Redirect(newChannel, nsIChannelEventSink::REDIRECT_TEMPORARY, true);
254 if (NS_SUCCEEDED(rv)) {
255 // OnRedirectVerifyCallback will be called asynchronously
256 return;
260 ContinueHandleAsyncRedirect(rv);
263 void nsBaseChannel::ContinueHandleAsyncRedirect(nsresult result) {
264 mWaitingOnAsyncRedirect = false;
266 if (NS_FAILED(result)) Cancel(result);
268 if (NS_FAILED(result) && mListener) {
269 // Notify our consumer ourselves
270 mListener->OnStartRequest(this);
271 mListener->OnStopRequest(this, mStatus);
272 ChannelDone();
275 if (mLoadGroup) mLoadGroup->RemoveRequest(this, nullptr, mStatus);
277 // Drop notification callbacks to prevent cycles.
278 mCallbacks = nullptr;
279 CallbacksChanged();
282 void nsBaseChannel::ClassifyURI() {
283 // For channels created in the child process, delegate to the parent to
284 // classify URIs.
285 if (!XRE_IsParentProcess()) {
286 return;
289 if (NS_ShouldClassifyChannel(this)) {
290 auto classifier = MakeRefPtr<net::nsChannelClassifier>(this);
291 classifier->Start();
295 //-----------------------------------------------------------------------------
296 // nsBaseChannel::nsISupports
298 NS_IMPL_ADDREF(nsBaseChannel)
299 NS_IMPL_RELEASE(nsBaseChannel)
301 NS_INTERFACE_MAP_BEGIN(nsBaseChannel)
302 NS_INTERFACE_MAP_ENTRY(nsIRequest)
303 NS_INTERFACE_MAP_ENTRY(nsIChannel)
304 NS_INTERFACE_MAP_ENTRY(nsIBaseChannel)
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 if (mPump) {
787 // If our content type is unknown, use the content type
788 // sniffer. If the sniffer is not available for some reason, then we just
789 // keep going as-is.
790 if (NS_SUCCEEDED(mStatus) &&
791 mContentType.EqualsLiteral(UNKNOWN_CONTENT_TYPE)) {
792 mPump->PeekStream(CallUnknownTypeSniffer, static_cast<nsIChannel*>(this));
795 // Now, the general type sniffers. Skip this if we have none.
796 if (mLoadFlags & LOAD_CALL_CONTENT_SNIFFERS) {
797 mPump->PeekStream(CallTypeSniffers, static_cast<nsIChannel*>(this));
801 SUSPEND_PUMP_FOR_SCOPE();
803 if (mListener) { // null in case of redirect
804 return mListener->OnStartRequest(this);
806 return NS_OK;
809 NS_IMETHODIMP
810 nsBaseChannel::OnStopRequest(nsIRequest* request, nsresult status) {
811 // If both mStatus and status are failure codes, we keep mStatus as-is since
812 // that is consistent with our GetStatus and Cancel methods.
813 if (NS_SUCCEEDED(mStatus)) mStatus = status;
815 // Cause Pending to return false.
816 mPump = nullptr;
817 mRequest = nullptr;
818 mCancelableAsyncRequest = nullptr;
819 mPumpingData = false;
821 if (mListener) { // null in case of redirect
822 mListener->OnStopRequest(this, mStatus);
824 ChannelDone();
826 // No need to suspend pump in this scope since we will not be receiving
827 // any more events from it.
829 if (mLoadGroup) mLoadGroup->RemoveRequest(this, nullptr, mStatus);
831 // Drop notification callbacks to prevent cycles.
832 mCallbacks = nullptr;
833 CallbacksChanged();
835 return NS_OK;
838 //-----------------------------------------------------------------------------
839 // nsBaseChannel::nsIStreamListener
841 NS_IMETHODIMP
842 nsBaseChannel::OnDataAvailable(nsIRequest* request, nsIInputStream* stream,
843 uint64_t offset, uint32_t count) {
844 SUSPEND_PUMP_FOR_SCOPE();
846 nsresult rv = mListener->OnDataAvailable(this, stream, offset, count);
847 if (mSynthProgressEvents && NS_SUCCEEDED(rv)) {
848 int64_t prog = offset + count;
849 if (NS_IsMainThread()) {
850 OnTransportStatus(nullptr, NS_NET_STATUS_READING, prog, mContentLength);
851 } else {
852 class OnTransportStatusAsyncEvent : public Runnable {
853 RefPtr<nsBaseChannel> mChannel;
854 int64_t mProgress;
855 int64_t mContentLength;
857 public:
858 OnTransportStatusAsyncEvent(nsBaseChannel* aChannel, int64_t aProgress,
859 int64_t aContentLength)
860 : Runnable("OnTransportStatusAsyncEvent"),
861 mChannel(aChannel),
862 mProgress(aProgress),
863 mContentLength(aContentLength) {}
865 NS_IMETHOD Run() override {
866 return mChannel->OnTransportStatus(nullptr, NS_NET_STATUS_READING,
867 mProgress, mContentLength);
871 nsCOMPtr<nsIRunnable> runnable =
872 new OnTransportStatusAsyncEvent(this, prog, mContentLength);
873 Dispatch(runnable.forget());
877 return rv;
880 NS_IMETHODIMP
881 nsBaseChannel::OnRedirectVerifyCallback(nsresult result) {
882 if (NS_SUCCEEDED(result)) result = ContinueRedirect();
884 if (NS_FAILED(result) && !mWaitingOnAsyncRedirect) {
885 if (NS_SUCCEEDED(mStatus)) mStatus = result;
886 return NS_OK;
889 if (mWaitingOnAsyncRedirect) ContinueHandleAsyncRedirect(result);
891 return NS_OK;
894 NS_IMETHODIMP
895 nsBaseChannel::RetargetDeliveryTo(nsISerialEventTarget* aEventTarget) {
896 MOZ_ASSERT(NS_IsMainThread());
898 if (!mRequest) {
899 return NS_ERROR_NOT_INITIALIZED;
902 nsCOMPtr<nsIThreadRetargetableRequest> req;
903 if (mAllowThreadRetargeting) {
904 req = do_QueryInterface(mRequest);
907 NS_ENSURE_TRUE(req, NS_ERROR_NOT_IMPLEMENTED);
909 return req->RetargetDeliveryTo(aEventTarget);
912 NS_IMETHODIMP
913 nsBaseChannel::GetDeliveryTarget(nsISerialEventTarget** aEventTarget) {
914 MOZ_ASSERT(NS_IsMainThread());
916 NS_ENSURE_TRUE(mRequest, NS_ERROR_NOT_INITIALIZED);
918 nsCOMPtr<nsIThreadRetargetableRequest> req;
919 req = do_QueryInterface(mRequest);
921 NS_ENSURE_TRUE(req, NS_ERROR_NOT_IMPLEMENTED);
922 return req->GetDeliveryTarget(aEventTarget);
925 NS_IMETHODIMP
926 nsBaseChannel::CheckListenerChain() {
927 MOZ_ASSERT(NS_IsMainThread());
929 if (!mAllowThreadRetargeting) {
930 return NS_ERROR_NOT_IMPLEMENTED;
933 nsCOMPtr<nsIThreadRetargetableStreamListener> listener =
934 do_QueryInterface(mListener);
935 if (!listener) {
936 return NS_ERROR_NO_INTERFACE;
939 return listener->CheckListenerChain();
942 NS_IMETHODIMP
943 nsBaseChannel::OnDataFinished(nsresult aStatus) {
944 if (!mListener) {
945 return NS_ERROR_FAILURE;
948 if (!mAllowThreadRetargeting) {
949 return NS_ERROR_NOT_IMPLEMENTED;
952 nsCOMPtr<nsIThreadRetargetableStreamListener> listener =
953 do_QueryInterface(mListener);
954 if (listener) {
955 return listener->OnDataFinished(aStatus);
958 return NS_OK;
961 NS_IMETHODIMP nsBaseChannel::GetCanceled(bool* aCanceled) {
962 *aCanceled = mCanceled;
963 return NS_OK;
966 void nsBaseChannel::SetupNeckoTarget() {
967 mNeckoTarget = GetMainThreadSerialEventTarget();
970 NS_IMETHODIMP nsBaseChannel::GetContentRange(
971 RefPtr<mozilla::net::ContentRange>* aRange) {
972 if (aRange) {
973 *aRange = mContentRange;
975 return NS_OK;
978 NS_IMETHODIMP nsBaseChannel::SetContentRange(
979 RefPtr<mozilla::net::ContentRange> aRange) {
980 mContentRange = aRange;
981 return NS_OK;
984 NS_IMETHODIMP nsBaseChannel::GetFullMimeType(RefPtr<TMimeType<char>>* aOut) {
985 if (aOut) {
986 *aOut = mFullMimeType;
988 return NS_OK;
991 NS_IMETHODIMP nsBaseChannel::SetFullMimeType(RefPtr<TMimeType<char>> aType) {
992 mFullMimeType = aType;
993 return NS_OK;