1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #ifndef nsBaseChannel_h__
7 #define nsBaseChannel_h__
9 #include "mozilla/Maybe.h"
10 #include "mozilla/MozPromise.h"
11 #include "mozilla/UniquePtr.h"
12 #include "mozilla/net/NeckoTargetHolder.h"
13 #include "mozilla/net/PrivateBrowsingChannel.h"
14 #include "nsHashPropertyBag.h"
15 #include "nsIAsyncVerifyRedirectCallback.h"
16 #include "nsIChannel.h"
17 #include "nsIInterfaceRequestor.h"
18 #include "nsILoadGroup.h"
19 #include "nsILoadInfo.h"
20 #include "nsIProgressEventSink.h"
21 #include "nsIStreamListener.h"
22 #include "nsIThreadRetargetableRequest.h"
23 #include "nsIThreadRetargetableStreamListener.h"
24 #include "nsITransport.h"
25 #include "nsITransportSecurityInfo.h"
27 #include "nsInputStreamPump.h"
29 #include "nsThreadUtils.h"
35 //-----------------------------------------------------------------------------
36 // nsBaseChannel is designed to be subclassed. The subclass is responsible for
37 // implementing the OpenContentStream method, which will be called by the
38 // nsIChannel::AsyncOpen and nsIChannel::Open implementations.
40 // nsBaseChannel implements nsIInterfaceRequestor to provide a convenient way
41 // for subclasses to query both the nsIChannel::notificationCallbacks and
42 // nsILoadGroup::notificationCallbacks for supported interfaces.
44 // nsBaseChannel implements nsITransportEventSink to support progress & status
45 // notifications generated by the transport layer.
48 : public nsHashPropertyBag
,
50 public nsIThreadRetargetableRequest
,
51 public nsIInterfaceRequestor
,
52 public nsITransportEventSink
,
53 public nsIAsyncVerifyRedirectCallback
,
54 public mozilla::net::PrivateBrowsingChannel
<nsBaseChannel
>,
55 public mozilla::net::NeckoTargetHolder
,
56 protected nsIThreadRetargetableStreamListener
{
58 NS_DECL_ISUPPORTS_INHERITED
61 NS_DECL_NSIINTERFACEREQUESTOR
62 NS_DECL_NSITRANSPORTEVENTSINK
63 NS_DECL_NSIASYNCVERIFYREDIRECTCALLBACK
64 NS_DECL_NSITHREADRETARGETABLEREQUEST
65 NS_DECL_NSITHREADRETARGETABLESTREAMLISTENER
70 // -----------------------------------------------
71 // Methods to be implemented by the derived class:
73 virtual ~nsBaseChannel();
75 using BlockingPromise
= mozilla::MozPromise
<nsresult
, nsresult
, true>;
78 // Implemented by subclass to supply data stream. The parameter, async, is
79 // true when called from nsIChannel::AsyncOpen and false otherwise. When
80 // async is true, the resulting stream will be used with a nsIInputStreamPump
81 // instance. This means that if it is a non-blocking stream that supports
82 // nsIAsyncInputStream that it will be read entirely on the main application
83 // thread, and its AsyncWait method will be called whenever ReadSegments
84 // returns NS_BASE_STREAM_WOULD_BLOCK. Otherwise, if the stream is blocking,
85 // then it will be read on one of the background I/O threads, and it does not
86 // need to implement ReadSegments. If async is false, this method may return
87 // NS_ERROR_NOT_IMPLEMENTED to cause the basechannel to implement Open in
88 // terms of AsyncOpen (see NS_ImplementChannelOpen).
89 // A callee is allowed to return an nsIChannel instead of an nsIInputStream.
90 // That case will be treated as a redirect to the new channel. By default
91 // *channel will be set to null by the caller, so callees who don't want to
92 // return one an just not touch it.
93 virtual nsresult
OpenContentStream(bool async
, nsIInputStream
** stream
,
94 nsIChannel
** channel
) = 0;
96 // Implemented by subclass to begin pumping data for an async channel, in
97 // lieu of returning a stream. If implemented, OpenContentStream will never
98 // be called for async channels. If not implemented, AsyncOpen will fall
99 // back to OpenContentStream.
101 // On success, the callee must begin pumping data to the stream listener,
102 // and at some point call OnStartRequest followed by OnStopRequest.
104 // Additionally, when a successful nsresult is returned, then the subclass
105 // should be setting through its two out params either:
106 // - a request object, which may be used to suspend, resume, and cancel
107 // the underlying request.
108 // - or a cancelable object (e.g. when a request can't be returned right away
109 // due to some async work needed to retrieve it). which may be used to
110 // cancel the underlying request (e.g. because the channel has been
113 // Not returning a request or cancelable leads to potentially leaking the
114 // an underling stream pump (which would keep to be pumping data even after
115 // the channel has been canceled and nothing is going to handle the data
116 // available, e.g. see Bug 1706594).
117 virtual nsresult
BeginAsyncRead(nsIStreamListener
* listener
,
118 nsIRequest
** request
,
119 nsICancelable
** cancelableRequest
) {
120 return NS_ERROR_NOT_IMPLEMENTED
;
123 // This method may return a promise that will keep the input stream pump
124 // suspended until the promise is resolved or rejected. On resolution the
125 // pump is resumed. On rejection the channel is canceled with the resulting
126 // error and then the pump is also resumed to propagate the error to the
127 // channel listener. Use it to do any asynchronous/background tasks you need
128 // to finish prior calling OnStartRequest of the listener. This method is
129 // called right after OpenContentStream() with async == true, after the input
130 // stream pump has already been called asyncRead().
131 virtual nsresult
ListenerBlockingPromise(BlockingPromise
** aPromise
) {
132 NS_ENSURE_ARG(aPromise
);
137 // The basechannel calls this method from its OnTransportStatus method to
138 // determine whether to call nsIProgressEventSink::OnStatus in addition to
139 // nsIProgressEventSink::OnProgress. This method may be overriden by the
140 // subclass to enable nsIProgressEventSink::OnStatus events. If this method
141 // returns true, then the statusArg out param specifies the "statusArg" value
142 // to pass to the OnStatus method. By default, OnStatus messages are
143 // suppressed. The status parameter passed to this method is the status value
144 // from the OnTransportStatus method.
145 virtual bool GetStatusArg(nsresult status
, nsString
& statusArg
) {
149 // Called when the callbacks available to this channel may have changed.
150 virtual void OnCallbacksChanged() {}
152 // Called when our channel is done, to allow subclasses to drop resources.
153 virtual void OnChannelDone() {}
156 // ----------------------------------------------
157 // Methods provided for use by the derived class:
159 // Redirect to another channel. This method takes care of notifying
160 // observers of this redirect as well as of opening the new channel, if asked
161 // to do so. It also cancels |this| with the status code
162 // NS_BINDING_REDIRECTED. A failure return from this method means that the
163 // redirect could not be performed (no channel was opened; this channel
164 // wasn't canceled.) The redirectFlags parameter consists of the flag values
165 // defined on nsIChannelEventSink.
166 nsresult
Redirect(nsIChannel
* newChannel
, uint32_t redirectFlags
,
167 bool openNewChannel
);
169 // Tests whether a type hint was set. Subclasses can use this to decide
170 // whether to call SetContentType.
171 // NOTE: This is only reliable if the subclass didn't itself call
172 // SetContentType, and should also not be called after OpenContentStream.
173 bool HasContentTypeHint() const;
175 // The URI member should be initialized before the channel is used, and then
176 // it should never be changed again until the channel is destroyed.
177 nsIURI
* URI() { return mURI
; }
178 void SetURI(nsIURI
* uri
) {
179 NS_ASSERTION(uri
, "must specify a non-null URI");
180 NS_ASSERTION(!mURI
, "must not modify URI");
181 NS_ASSERTION(!mOriginalURI
, "how did that get set so early?");
185 nsIURI
* OriginalURI() { return mOriginalURI
; }
187 // The security info is a property of the transport-layer, which should be
188 // assigned by the subclass.
189 nsITransportSecurityInfo
* SecurityInfo() { return mSecurityInfo
; }
190 void SetSecurityInfo(nsITransportSecurityInfo
* info
) { mSecurityInfo
= info
; }
192 // Test the load flags
193 bool HasLoadFlag(uint32_t flag
) { return (mLoadFlags
& flag
) != 0; }
195 // This is a short-cut to calling nsIRequest::IsPending()
196 virtual bool Pending() const {
197 return mPumpingData
|| mWaitingOnAsyncRedirect
;
200 // Blob requests may specify a range header. We must parse, validate, and
201 // store that info in a place where BlobURLInputStream::StoreBlobImplStream
202 // can access it. This class helps to encapsulate that logic.
210 uint64_t Start() const { return mStart
; }
211 uint64_t End() const { return mEnd
; }
212 uint64_t Size() const { return mSize
; }
213 bool IsValid() const { return mStart
< mSize
; }
214 ContentRange() : mStart(0), mEnd(0), mSize(0) {}
215 ContentRange(uint64_t aStart
, uint64_t aEnd
, uint64_t aSize
)
216 : mStart(aStart
), mEnd(aEnd
), mSize(aSize
) {}
217 ContentRange(const nsACString
& aRangeHeader
, uint64_t aSize
);
218 void AsHeader(nsACString
& aOutString
) const;
221 const mozilla::Maybe
<ContentRange
>& GetContentRange() const {
222 return mContentRange
;
225 void SetContentRange(uint64_t aStart
, uint64_t aEnd
, uint64_t aSize
) {
226 mContentRange
.emplace(ContentRange(aStart
, aEnd
, aSize
));
229 bool SetContentRange(const nsACString
& aRangeHeader
, uint64_t aSize
) {
230 auto range
= ContentRange(aRangeHeader
, aSize
);
231 if (!range
.IsValid()) {
234 mContentRange
.emplace(range
);
238 // Helper function for querying the channel's notification callbacks.
240 void GetCallback(nsCOMPtr
<T
>& result
) {
241 GetInterface(NS_GET_TEMPLATE_IID(T
), getter_AddRefs(result
));
244 // If a subclass does not want to feed transport-layer progress events to the
245 // base channel via nsITransportEventSink, then it may set this flag to cause
246 // the base channel to synthesize progress events when it receives data from
247 // the content stream. By default, progress events are not synthesized.
248 void EnableSynthesizedProgressEvents(bool enable
) {
249 mSynthProgressEvents
= enable
;
252 // Some subclasses may wish to manually insert a stream listener between this
253 // and the channel's listener. The following methods make that possible.
254 void SetStreamListener(nsIStreamListener
* listener
) { mListener
= listener
; }
255 nsIStreamListener
* StreamListener() { return mListener
; }
258 void DisallowThreadRetargeting() { mAllowThreadRetargeting
= false; }
260 virtual void SetupNeckoTarget();
263 NS_DECL_NSISTREAMLISTENER
264 NS_DECL_NSIREQUESTOBSERVER
266 // Called to setup mPump and call AsyncRead on it.
267 nsresult
BeginPumpingData();
269 // Called when the callbacks available to this channel may have changed.
270 void CallbacksChanged() {
271 mProgressSink
= nullptr;
272 mQueriedProgressSink
= false;
273 OnCallbacksChanged();
276 // Called when our channel is done. This should drop no-longer-needed
283 // Handle an async redirect callback. This will only be called if we
284 // returned success from AsyncOpen while posting a redirect runnable.
285 void HandleAsyncRedirect(nsIChannel
* newChannel
);
286 void ContinueHandleAsyncRedirect(nsresult result
);
287 nsresult
ContinueRedirect();
289 // start URI classifier if requested
292 class RedirectRunnable
: public mozilla::Runnable
{
294 RedirectRunnable(nsBaseChannel
* chan
, nsIChannel
* newChannel
)
295 : mozilla::Runnable("nsBaseChannel::RedirectRunnable"),
297 mNewChannel(newChannel
) {
298 MOZ_ASSERT(newChannel
, "Must have channel to redirect to");
301 NS_IMETHOD
Run() override
{
302 mChannel
->HandleAsyncRedirect(mNewChannel
);
307 RefPtr
<nsBaseChannel
> mChannel
;
308 nsCOMPtr
<nsIChannel
> mNewChannel
;
310 friend class RedirectRunnable
;
312 RefPtr
<nsInputStreamPump
> mPump
;
313 RefPtr
<nsIRequest
> mRequest
;
314 nsCOMPtr
<nsICancelable
> mCancelableAsyncRequest
;
315 bool mPumpingData
{false};
316 nsCOMPtr
<nsIProgressEventSink
> mProgressSink
;
317 nsCOMPtr
<nsIURI
> mOriginalURI
;
318 nsCOMPtr
<nsISupports
> mOwner
;
319 nsCOMPtr
<nsITransportSecurityInfo
> mSecurityInfo
;
320 nsCOMPtr
<nsIChannel
> mRedirectChannel
;
321 uint32_t mLoadFlags
{LOAD_NORMAL
};
322 bool mQueriedProgressSink
{true};
323 bool mSynthProgressEvents
{false};
324 bool mAllowThreadRetargeting
{true};
325 bool mWaitingOnAsyncRedirect
{false};
326 bool mOpenRedirectChannel
{false};
327 uint32_t mRedirectFlags
{0};
328 mozilla::Maybe
<ContentRange
> mContentRange
;
331 nsCString mContentType
;
332 nsCString mContentCharset
;
333 nsCOMPtr
<nsIURI
> mURI
;
334 nsCOMPtr
<nsILoadGroup
> mLoadGroup
;
335 nsCOMPtr
<nsILoadInfo
> mLoadInfo
;
336 nsCOMPtr
<nsIInterfaceRequestor
> mCallbacks
;
337 nsCOMPtr
<nsIStreamListener
> mListener
;
338 nsresult mStatus
{NS_OK
};
339 uint32_t mContentDispositionHint
{UINT32_MAX
};
340 mozilla::UniquePtr
<nsString
> mContentDispositionFilename
;
341 int64_t mContentLength
{-1};
342 bool mWasOpened
{false};
343 bool mCanceled
{false};
345 friend class mozilla::net::PrivateBrowsingChannel
<nsBaseChannel
>;
348 #endif // !nsBaseChannel_h__