Bug 1909986 - For sidebar revamp, only show chatbot entrypoints (context menu, shortc...
[gecko.git] / netwerk / protocol / http / nsHttpConnection.h
blob4f0487313f99927d789fc9f21088a04aeb024318
1 /* -*- Mode: C++; tab-width: 4; 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 nsHttpConnection_h__
7 #define nsHttpConnection_h__
9 #include <functional>
10 #include "HttpConnectionBase.h"
11 #include "nsHttpConnectionInfo.h"
12 #include "nsHttpResponseHead.h"
13 #include "nsAHttpTransaction.h"
14 #include "nsCOMPtr.h"
15 #include "nsProxyRelease.h"
16 #include "prinrval.h"
17 #include "mozilla/Mutex.h"
18 #include "ARefBase.h"
19 #include "TimingStruct.h"
20 #include "HttpTrafficAnalyzer.h"
21 #include "TlsHandshaker.h"
23 #include "nsIAsyncInputStream.h"
24 #include "nsIAsyncOutputStream.h"
25 #include "nsIInterfaceRequestor.h"
26 #include "nsISocketTransport.h"
27 #include "nsISupportsPriority.h"
28 #include "nsITimer.h"
29 #include "nsITlsHandshakeListener.h"
31 class nsISocketTransport;
32 class nsITLSSocketControl;
34 namespace mozilla {
35 namespace net {
37 class nsHttpHandler;
38 class ASpdySession;
40 // 1dcc863e-db90-4652-a1fe-13fea0b54e46
41 #define NS_HTTPCONNECTION_IID \
42 { \
43 0x1dcc863e, 0xdb90, 0x4652, { \
44 0xa1, 0xfe, 0x13, 0xfe, 0xa0, 0xb5, 0x4e, 0x46 \
45 } \
48 //-----------------------------------------------------------------------------
49 // nsHttpConnection - represents a connection to a HTTP server (or proxy)
51 // NOTE: this objects lives on the socket thread only. it should not be
52 // accessed from any other thread.
53 //-----------------------------------------------------------------------------
55 class nsHttpConnection final : public HttpConnectionBase,
56 public nsAHttpSegmentReader,
57 public nsAHttpSegmentWriter,
58 public nsIInputStreamCallback,
59 public nsIOutputStreamCallback,
60 public nsITransportEventSink,
61 public nsIInterfaceRequestor {
62 private:
63 virtual ~nsHttpConnection();
65 public:
66 NS_DECLARE_STATIC_IID_ACCESSOR(NS_HTTPCONNECTION_IID)
67 NS_DECL_HTTPCONNECTIONBASE
68 NS_DECL_THREADSAFE_ISUPPORTS
69 NS_DECL_NSAHTTPSEGMENTREADER
70 NS_DECL_NSAHTTPSEGMENTWRITER
71 NS_DECL_NSIINPUTSTREAMCALLBACK
72 NS_DECL_NSIOUTPUTSTREAMCALLBACK
73 NS_DECL_NSITRANSPORTEVENTSINK
74 NS_DECL_NSIINTERFACEREQUESTOR
76 nsHttpConnection();
78 // Initialize the connection:
79 // info - specifies the connection parameters.
80 // maxHangTime - limits the amount of time this connection can spend on a
81 // single transaction before it should no longer be kept
82 // alive. a value of 0xffff indicates no limit.
83 [[nodiscard]] virtual nsresult Init(nsHttpConnectionInfo* info,
84 uint16_t maxHangTime, nsISocketTransport*,
85 nsIAsyncInputStream*,
86 nsIAsyncOutputStream*,
87 bool connectedTransport, nsresult status,
88 nsIInterfaceRequestor*, PRIntervalTime,
89 bool forWebSocket);
91 //-------------------------------------------------------------------------
92 // XXX document when these are ok to call
94 bool IsKeepAlive() {
95 return (mUsingSpdyVersion != SpdyVersion::NONE) ||
96 (mKeepAliveMask && mKeepAlive);
99 // Returns time in seconds for how long connection can be reused.
100 uint32_t TimeToLive();
102 bool NeedSpdyTunnel() {
103 return mConnInfo->UsingHttpsProxy() && !mHasTLSTransportLayer &&
104 mConnInfo->UsingConnect();
107 // A connection is forced into plaintext when it is intended to be used as a
108 // CONNECT tunnel but the setup fails. The plaintext only carries the CONNECT
109 // error.
110 void ForcePlainText() { mForcePlainText = true; }
112 bool IsUrgentStartPreferred() const {
113 return mUrgentStartPreferredKnown && mUrgentStartPreferred;
115 void SetUrgentStartPreferred(bool urgent);
117 void SetIsReusedAfter(uint32_t afterMilliseconds);
119 int64_t MaxBytesRead() { return mMaxBytesRead; }
120 HttpVersion GetLastHttpResponseVersion() { return mLastHttpResponseVersion; }
122 friend class HttpConnectionForceIO;
123 friend class TlsHandshaker;
125 // When a persistent connection is in the connection manager idle
126 // connection pool, the nsHttpConnection still reads errors and hangups
127 // on the socket so that it can be proactively released if the server
128 // initiates a termination. Only call on socket thread.
129 void BeginIdleMonitoring();
130 void EndIdleMonitoring();
132 bool UsingSpdy() override { return (mUsingSpdyVersion != SpdyVersion::NONE); }
133 SpdyVersion GetSpdyVersion() { return mUsingSpdyVersion; }
134 bool EverUsedSpdy() { return mEverUsedSpdy; }
135 bool UsingHttp3() override { return false; }
137 // true when connection SSL NPN phase is complete and we know
138 // authoritatively whether UsingSpdy() or not.
139 bool ReportedNPN() { return mReportedSpdy; }
141 // When the connection is active this is called up to once every 1 second
142 // return the interval (in seconds) that the connection next wants to
143 // have this invoked. It might happen sooner depending on the needs of
144 // other connections.
145 uint32_t ReadTimeoutTick(PRIntervalTime now);
147 // For Active and Idle connections, this will be called when
148 // mTCPKeepaliveTransitionTimer fires, to check if the TCP keepalive config
149 // should move from short-lived (fast-detect) to long-lived.
150 static void UpdateTCPKeepalive(nsITimer* aTimer, void* aClosure);
152 // When the connection is active this is called every second
153 void ReadTimeoutTick();
155 int64_t ContentBytesWritten() { return mContentBytesWritten; }
157 void SetupSecondaryTLS();
158 void SetInSpdyTunnel();
160 // Check active connections for traffic (or not). SPDY connections send a
161 // ping, ordinary HTTP connections get some time to get traffic to be
162 // considered alive.
163 void CheckForTraffic(bool check);
165 // NoTraffic() returns true if there's been no traffic on the (non-spdy)
166 // connection since CheckForTraffic() was called.
167 bool NoTraffic() {
168 return mTrafficStamp &&
169 (mTrafficCount == (mTotalBytesWritten + mTotalBytesRead));
172 // Return true when the socket this connection is using has not been
173 // authenticated using a client certificate. Before SSL negotiation
174 // has finished this returns false.
175 bool NoClientCertAuth() const override;
177 WebSocketSupport GetWebSocketSupport() override;
179 int64_t BytesWritten() override { return mTotalBytesWritten; }
181 nsISocketTransport* Transport() override { return mSocketTransport; }
183 nsresult GetSelfAddr(NetAddr* addr) override;
184 nsresult GetPeerAddr(NetAddr* addr) override;
185 bool ResolvedByTRR() override;
186 bool GetEchConfigUsed() override;
187 nsIRequest::TRRMode EffectiveTRRMode() override;
188 TRRSkippedReason TRRSkipReason() override;
189 bool IsForWebSocket() { return mForWebSocket; }
191 // The following functions are related to setting up a tunnel.
192 [[nodiscard]] static nsresult MakeConnectString(
193 nsAHttpTransaction* trans, nsHttpRequestHead* request, nsACString& result,
194 bool h2ws, bool aShouldResistFingerprinting);
195 [[nodiscard]] static nsresult ReadFromStream(nsIInputStream*, void*,
196 const char*, uint32_t, uint32_t,
197 uint32_t*);
199 nsresult CreateTunnelStream(nsAHttpTransaction* httpTransaction,
200 nsHttpConnection** aHttpConnection,
201 bool aIsWebSocket = false);
203 bool RequestDone() { return mRequestDone; }
205 private:
206 enum HttpConnectionState {
207 UNINITIALIZED,
208 SETTING_UP_TUNNEL,
209 REQUEST,
210 } mState{HttpConnectionState::UNINITIALIZED};
211 void ChangeState(HttpConnectionState newState);
213 // Tunnel retated functions:
214 bool TunnelSetupInProgress() { return mState == SETTING_UP_TUNNEL; }
215 void SetTunnelSetupDone();
216 nsresult CheckTunnelIsNeeded();
217 nsresult SetupProxyConnectStream();
218 nsresult SendConnectRequest(void* closure, uint32_t* transactionBytes);
220 void HandleTunnelResponse(uint16_t responseStatus, bool* reset);
221 void HandleWebSocketResponse(nsHttpRequestHead* requestHead,
222 nsHttpResponseHead* responseHead,
223 uint16_t responseStatus);
224 void ResetTransaction(RefPtr<nsAHttpTransaction>&& trans);
226 // Value (set in mTCPKeepaliveConfig) indicates which set of prefs to use.
227 enum TCPKeepaliveConfig {
228 kTCPKeepaliveDisabled = 0,
229 kTCPKeepaliveShortLivedConfig,
230 kTCPKeepaliveLongLivedConfig
233 [[nodiscard]] nsresult OnTransactionDone(nsresult reason);
234 [[nodiscard]] nsresult OnSocketWritable();
235 [[nodiscard]] nsresult OnSocketReadable();
237 PRIntervalTime IdleTime();
238 bool IsAlive();
240 // Start the Spdy transaction handler when NPN indicates spdy/*
241 void StartSpdy(nsITLSSocketControl* ssl, SpdyVersion spdyVersion);
242 // Like the above, but do the bare minimum to do 0RTT data, so we can back
243 // it out, if necessary
244 void Start0RTTSpdy(SpdyVersion spdyVersion);
246 // Helpers for Start*Spdy
247 nsresult TryTakeSubTransactions(nsTArray<RefPtr<nsAHttpTransaction> >& list);
248 nsresult MoveTransactionsToSpdy(nsresult status,
249 nsTArray<RefPtr<nsAHttpTransaction> >& list);
251 // Directly Add a transaction to an active connection for SPDY
252 [[nodiscard]] nsresult AddTransaction(nsAHttpTransaction*, int32_t);
254 // Used to set TCP keepalives for fast detection of dead connections during
255 // an initial period, and slower detection for long-lived connections.
256 [[nodiscard]] nsresult StartShortLivedTCPKeepalives();
257 [[nodiscard]] nsresult StartLongLivedTCPKeepalives();
258 [[nodiscard]] nsresult DisableTCPKeepalives();
260 bool CheckCanWrite0RTTData();
261 void PostProcessNPNSetup(bool handshakeSucceeded, bool hasSecurityInfo,
262 bool earlyDataUsed);
263 void Reset0RttForSpdy();
264 void HandshakeDoneInternal();
265 uint32_t TransactionCaps() const { return mTransactionCaps; }
267 void MarkAsDontReuse();
269 private:
270 // mTransaction only points to the HTTP Transaction callbacks if the
271 // transaction is open, otherwise it is null.
272 RefPtr<nsAHttpTransaction> mTransaction;
274 RefPtr<TlsHandshaker> mTlsHandshaker;
276 nsCOMPtr<nsIAsyncInputStream> mSocketIn;
277 nsCOMPtr<nsIAsyncOutputStream> mSocketOut;
279 nsresult mSocketInCondition{NS_ERROR_NOT_INITIALIZED};
280 nsresult mSocketOutCondition{NS_ERROR_NOT_INITIALIZED};
282 RefPtr<nsHttpHandler> mHttpHandler; // keep gHttpHandler alive
284 PRIntervalTime mLastReadTime{0};
285 PRIntervalTime mLastWriteTime{0};
286 // max download time before dropping keep-alive status
287 PRIntervalTime mMaxHangTime{0};
288 PRIntervalTime mIdleTimeout; // value of keep-alive: timeout=
289 PRIntervalTime mConsiderReusedAfterInterval{0};
290 PRIntervalTime mConsiderReusedAfterEpoch{0};
291 int64_t mCurrentBytesRead{0}; // data read per activation
292 int64_t mMaxBytesRead{0}; // max read in 1 activation
293 int64_t mTotalBytesRead{0}; // total data read
294 int64_t mContentBytesWritten{0}; // does not include CONNECT tunnel or TLS
296 RefPtr<nsIAsyncInputStream> mInputOverflow;
298 // Whether the first non-null transaction dispatched on this connection was
299 // urgent-start or not
300 bool mUrgentStartPreferred{false};
301 // A flag to prevent reset of mUrgentStartPreferred by subsequent transactions
302 bool mUrgentStartPreferredKnown{false};
303 bool mConnectedTransport{false};
304 // assume to keep-alive by default
305 bool mKeepAlive{true};
306 bool mKeepAliveMask{true};
307 bool mDontReuse{false};
308 bool mIsReused{false};
309 bool mLastTransactionExpectedNoContent{false};
310 bool mIdleMonitoring{false};
311 bool mInSpdyTunnel{false};
312 bool mForcePlainText{false};
314 // A snapshot of current number of transfered bytes
315 int64_t mTrafficCount{0};
316 bool mTrafficStamp{false}; // true then the above is set
318 // The number of <= HTTP/1.1 transactions performed on this connection. This
319 // excludes spdy transactions.
320 uint32_t mHttp1xTransactionCount{0};
322 // Keep-Alive: max="mRemainingConnectionUses" provides the number of future
323 // transactions (including the current one) that the server expects to allow
324 // on this persistent connection.
325 uint32_t mRemainingConnectionUses{0xffffffff};
327 // version level in use, 0 if unused
328 SpdyVersion mUsingSpdyVersion{SpdyVersion::NONE};
330 RefPtr<ASpdySession> mSpdySession;
331 RefPtr<ASpdySession> mWebSocketHttp2Session;
332 int32_t mPriority{nsISupportsPriority::PRIORITY_NORMAL};
333 bool mReportedSpdy{false};
335 // mUsingSpdyVersion is cleared when mSpdySession is freed, this is permanent
336 bool mEverUsedSpdy{false};
338 // mLastHttpResponseVersion stores the last response's http version seen.
339 HttpVersion mLastHttpResponseVersion{HttpVersion::v1_1};
341 // If a large keepalive has been requested for any trans,
342 // scale the default by this factor
343 uint32_t mDefaultTimeoutFactor{1};
345 bool mResponseTimeoutEnabled{false};
347 // Flag to indicate connection is in inital keepalive period (fast detect).
348 uint32_t mTCPKeepaliveConfig{kTCPKeepaliveDisabled};
349 nsCOMPtr<nsITimer> mTCPKeepaliveTransitionTimer;
351 private:
352 // For ForceSend()
353 static void ForceSendIO(nsITimer* aTimer, void* aClosure);
354 [[nodiscard]] nsresult MaybeForceSendIO();
355 bool mForceSendPending{false};
356 nsCOMPtr<nsITimer> mForceSendTimer;
358 int64_t mContentBytesWritten0RTT{0};
359 bool mDid0RTTSpdy{false};
361 nsresult mErrorBeforeConnect = NS_OK;
363 nsCOMPtr<nsISocketTransport> mSocketTransport;
365 // This flag indicates if the connection is used for WebSocket.
366 // - When true and mInSpdyTunnel is also true: WebSocket over HTTP/2.
367 // - When true and mInSpdyTunnel is false: WebSocket over HTTP/1.1.
368 bool mForWebSocket{false};
370 std::function<void()> mContinueHandshakeDone{nullptr};
372 private:
373 int64_t mTotalBytesWritten = 0; // does not include CONNECT tunnel
375 nsCOMPtr<nsIInputStream> mProxyConnectStream;
377 bool mRequestDone{false};
378 bool mHasTLSTransportLayer{false};
379 bool mTransactionDisallowHttp3{false};
382 NS_DEFINE_STATIC_IID_ACCESSOR(nsHttpConnection, NS_HTTPCONNECTION_IID)
384 } // namespace net
385 } // namespace mozilla
387 #endif // nsHttpConnection_h__