1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=4 sw=2 sts=2 et cin: */
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/. */
6
7 // HttpLog.h should generally be included first
8 #include "HttpLog.h"
9
10 // Log on level :5, instead of default :4.
11 #undef LOG
12 #define LOG(args) LOG5(args)
13 #undef LOG_ENABLED
14 #define LOG_ENABLED() LOG5_ENABLED()
15
16 #define TLS_EARLY_DATA_NOT_AVAILABLE 0
17 #define TLS_EARLY_DATA_AVAILABLE_BUT_NOT_USED 1
18 #define TLS_EARLY_DATA_AVAILABLE_AND_USED 2
19
20 #include "ASpdySession.h"
21 #include "mozilla/ChaosMode.h"
22 #include "mozilla/Telemetry.h"
23 #include "nsHttpConnection.h"
24 #include "nsHttpHandler.h"
25 #include "nsHttpRequestHead.h"
26 #include "nsHttpResponseHead.h"
27 #include "nsIClassOfService.h"
28 #include "nsIOService.h"
29 #include "nsISocketTransport.h"
30 #include "nsSocketTransportService2.h"
31 #include "nsISSLSocketControl.h"
32 #include "nsISupportsPriority.h"
33 #include "nsITransportSecurityInfo.h"
34 #include "nsCRT.h"
35 #include "nsPreloadedStream.h"
36 #include "nsProxyRelease.h"
37 #include "nsSocketTransport2.h"
38 #include "nsStringStream.h"
39 #include "nsITransportSecurityInfo.h"
40 #include "mozpkix/pkixnss.h"
41 #include "sslt.h"
42 #include "NSSErrorsService.h"
43 #include "TunnelUtils.h"
44
45 namespace mozilla {
46 namespace net {
47
48 enum TlsHandshakeResult : uint32_t {
49 EchConfigSuccessful = 0,
50 EchConfigFailed,
51 NoEchConfigSuccessful,
52 NoEchConfigFailed,
53 };
54
55 //-----------------------------------------------------------------------------
56 // nsHttpConnection <public>
57 //-----------------------------------------------------------------------------
58
nsHttpConnection()59 nsHttpConnection::nsHttpConnection() : mHttpHandler(gHttpHandler) {
60 LOG(("Creating nsHttpConnection @%p\n", this));
61
62 // the default timeout is for when this connection has not yet processed a
63 // transaction
64 static const PRIntervalTime k5Sec = PR_SecondsToInterval(5);
65 mIdleTimeout = (k5Sec < gHttpHandler->IdleTimeout())
66 ? k5Sec
67 : gHttpHandler->IdleTimeout();
68
69 mThroughCaptivePortal = gHttpHandler->GetThroughCaptivePortal();
70 }
71
~nsHttpConnection()72 nsHttpConnection::~nsHttpConnection() {
73 LOG(("Destroying nsHttpConnection @%p\n", this));
74
75 if (!mEverUsedSpdy) {
76 LOG(("nsHttpConnection %p performed %d HTTP/1.x transactions\n", this,
77 mHttp1xTransactionCount));
78 Telemetry::Accumulate(Telemetry::HTTP_REQUEST_PER_CONN,
79 mHttp1xTransactionCount);
80 nsHttpConnectionInfo* ci = nullptr;
81 if (mTransaction) {
82 ci = mTransaction->ConnectionInfo();
83 }
84 if (!ci) {
85 ci = mConnInfo;
86 }
87
88 MOZ_ASSERT(ci);
89 if (ci->GetIsTrrServiceChannel()) {
90 Telemetry::Accumulate(Telemetry::DNS_TRR_REQUEST_PER_CONN,
91 mHttp1xTransactionCount);
92 }
93 }
94
95 if (mTotalBytesRead) {
96 uint32_t totalKBRead = static_cast<uint32_t>(mTotalBytesRead >> 10);
97 LOG(("nsHttpConnection %p read %dkb on connection spdy=%d\n", this,
98 totalKBRead, mEverUsedSpdy));
99 Telemetry::Accumulate(mEverUsedSpdy ? Telemetry::SPDY_KBREAD_PER_CONN2
100 : Telemetry::HTTP_KBREAD_PER_CONN2,
101 totalKBRead);
102 }
103
104 if (mThroughCaptivePortal) {
105 if (mTotalBytesRead || mTotalBytesWritten) {
106 auto total =
107 Clamp<uint32_t>((mTotalBytesRead >> 10) + (mTotalBytesWritten >> 10),
108 0, std::numeric_limits<uint32_t>::max());
109 Telemetry::ScalarAdd(
110 Telemetry::ScalarID::NETWORKING_DATA_TRANSFERRED_CAPTIVE_PORTAL,
111 total);
112 }
113
114 Telemetry::ScalarAdd(
115 Telemetry::ScalarID::NETWORKING_HTTP_CONNECTIONS_CAPTIVE_PORTAL, 1);
116 }
117
118 if (mForceSendTimer) {
119 mForceSendTimer->Cancel();
120 mForceSendTimer = nullptr;
121 }
122 }
123
Init(nsHttpConnectionInfo * info,uint16_t maxHangTime,nsISocketTransport * transport,nsIAsyncInputStream * instream,nsIAsyncOutputStream * outstream,bool connectedTransport,nsresult status,nsIInterfaceRequestor * callbacks,PRIntervalTime rtt,bool forWebSocket)124 nsresult nsHttpConnection::Init(
125 nsHttpConnectionInfo* info, uint16_t maxHangTime,
126 nsISocketTransport* transport, nsIAsyncInputStream* instream,
127 nsIAsyncOutputStream* outstream, bool connectedTransport, nsresult status,
128 nsIInterfaceRequestor* callbacks, PRIntervalTime rtt, bool forWebSocket) {
129 LOG1(("nsHttpConnection::Init this=%p sockettransport=%p forWebSocket=%d",
130 this, transport, forWebSocket));
131 NS_ENSURE_ARG_POINTER(info);
132 NS_ENSURE_TRUE(!mConnInfo, NS_ERROR_ALREADY_INITIALIZED);
133 MOZ_ASSERT(NS_SUCCEEDED(status) || !connectedTransport);
134
135 mConnectedTransport = connectedTransport;
136 mConnInfo = info;
137 MOZ_ASSERT(mConnInfo);
138
139 mLastWriteTime = mLastReadTime = PR_IntervalNow();
140 mRtt = rtt;
141 mMaxHangTime = PR_SecondsToInterval(maxHangTime);
142
143 mSocketTransport = transport;
144 mSocketIn = instream;
145 mSocketOut = outstream;
146 mForWebSocket = forWebSocket;
147
148 // See explanation for non-strictness of this operation in
149 // SetSecurityCallbacks.
150 mCallbacks = new nsMainThreadPtrHolder<nsIInterfaceRequestor>(
151 "nsHttpConnection::mCallbacks", callbacks, false);
152
153 mErrorBeforeConnect = status;
154 if (NS_SUCCEEDED(mErrorBeforeConnect)) {
155 mSocketTransport->SetEventSink(this, nullptr);
156 mSocketTransport->SetSecurityCallbacks(this);
157 }
158
159 return NS_OK;
160 }
161
TryTakeSubTransactions(nsTArray<RefPtr<nsAHttpTransaction>> & list)162 nsresult nsHttpConnection::TryTakeSubTransactions(
163 nsTArray<RefPtr<nsAHttpTransaction> >& list) {
164 nsresult rv = mTransaction->TakeSubTransactions(list);
165
166 if (rv == NS_ERROR_ALREADY_OPENED) {
167 // Has the interface for TakeSubTransactions() changed?
168 LOG(
169 ("TakeSubTransactions somehow called after "
170 "nsAHttpTransaction began processing\n"));
171 MOZ_ASSERT(false,
172 "TakeSubTransactions somehow called after "
173 "nsAHttpTransaction began processing");
174 mTransaction->Close(NS_ERROR_ABORT);
175 return rv;
176 }
177
178 if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) {
179 // Has the interface for TakeSubTransactions() changed?
180 LOG(("unexpected rv from nnsAHttpTransaction::TakeSubTransactions()"));
181 MOZ_ASSERT(false,
182 "unexpected result from "
183 "nsAHttpTransaction::TakeSubTransactions()");
184 mTransaction->Close(NS_ERROR_ABORT);
185 return rv;
186 }
187
188 return rv;
189 }
190
MoveTransactionsToSpdy(nsresult status,nsTArray<RefPtr<nsAHttpTransaction>> & list)191 nsresult nsHttpConnection::MoveTransactionsToSpdy(
192 nsresult status, nsTArray<RefPtr<nsAHttpTransaction> >& list) {
193 if (NS_FAILED(status)) { // includes NS_ERROR_NOT_IMPLEMENTED
194 MOZ_ASSERT(list.IsEmpty(), "sub transaction list not empty");
195
196 // This is ok - treat mTransaction as a single real request.
197 // Wrap the old http transaction into the new spdy session
198 // as the first stream.
199 LOG(
200 ("nsHttpConnection::MoveTransactionsToSpdy moves single transaction %p "
201 "into SpdySession %p\n",
202 mTransaction.get(), mSpdySession.get()));
203 nsresult rv = AddTransaction(mTransaction, mPriority);
204 if (NS_FAILED(rv)) {
205 return rv;
206 }
207 } else {
208 int32_t count = list.Length();
209
210 LOG(
211 ("nsHttpConnection::MoveTransactionsToSpdy moving transaction list "
212 "len=%d "
213 "into SpdySession %p\n",
214 count, mSpdySession.get()));
215
216 if (!count) {
217 mTransaction->Close(NS_ERROR_ABORT);
218 return NS_ERROR_ABORT;
219 }
220
221 for (int32_t index = 0; index < count; ++index) {
222 nsresult rv = AddTransaction(list[index], mPriority);
223 if (NS_FAILED(rv)) {
224 return rv;
225 }
226 }
227 }
228
229 return NS_OK;
230 }
231
Start0RTTSpdy(SpdyVersion spdyVersion)232 void nsHttpConnection::Start0RTTSpdy(SpdyVersion spdyVersion) {
233 LOG(("nsHttpConnection::Start0RTTSpdy [this=%p]", this));
234
235 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
236
237 mDid0RTTSpdy = true;
238 mUsingSpdyVersion = spdyVersion;
239 mSpdySession =
240 ASpdySession::NewSpdySession(spdyVersion, mSocketTransport, true);
241
242 nsTArray<RefPtr<nsAHttpTransaction> > list;
243 nsresult rv = TryTakeSubTransactions(list);
244 if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) {
245 LOG(
246 ("nsHttpConnection::Start0RTTSpdy [this=%p] failed taking "
247 "subtransactions rv=%" PRIx32,
248 this, static_cast<uint32_t>(rv)));
249 return;
250 }
251
252 rv = MoveTransactionsToSpdy(rv, list);
253 if (NS_FAILED(rv)) {
254 LOG(
255 ("nsHttpConnection::Start0RTTSpdy [this=%p] failed moving "
256 "transactions rv=%" PRIx32,
257 this, static_cast<uint32_t>(rv)));
258 return;
259 }
260
261 mTransaction = mSpdySession;
262 }
263
StartSpdy(nsISSLSocketControl * sslControl,SpdyVersion spdyVersion)264 void nsHttpConnection::StartSpdy(nsISSLSocketControl* sslControl,
265 SpdyVersion spdyVersion) {
266 LOG(("nsHttpConnection::StartSpdy [this=%p, mDid0RTTSpdy=%d]\n", this,
267 mDid0RTTSpdy));
268
269 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
270 MOZ_ASSERT(!mSpdySession || mDid0RTTSpdy);
271
272 mUsingSpdyVersion = spdyVersion;
273 mEverUsedSpdy = true;
274 if (sslControl) {
275 sslControl->SetDenyClientCert(true);
276 }
277
278 if (!mDid0RTTSpdy) {
279 mSpdySession =
280 ASpdySession::NewSpdySession(spdyVersion, mSocketTransport, false);
281 }
282
283 if (!mReportedSpdy) {
284 mReportedSpdy = true;
285 gHttpHandler->ConnMgr()->ReportSpdyConnection(this, true);
286 }
287
288 // Setting the connection as reused allows some transactions that fail
289 // with NS_ERROR_NET_RESET to be restarted and SPDY uses that code
290 // to handle clean rejections (such as those that arrived after
291 // a server goaway was generated).
292 mIsReused = true;
293
294 // If mTransaction is a muxed object it might represent
295 // several requests. If so, we need to unpack that and
296 // pack them all into a new spdy session.
297
298 nsTArray<RefPtr<nsAHttpTransaction> > list;
299 nsresult status = NS_OK;
300 if (!mDid0RTTSpdy) {
301 status = TryTakeSubTransactions(list);
302
303 if (NS_FAILED(status) && status != NS_ERROR_NOT_IMPLEMENTED) {
304 return;
305 }
306 }
307
308 if (NeedSpdyTunnel()) {
309 LOG3(
310 ("nsHttpConnection::StartSpdy %p Connecting To a HTTP/2 "
311 "Proxy and Need Connect",
312 this));
313 MOZ_ASSERT(mProxyConnectStream);
314
315 mProxyConnectStream = nullptr;
316 mCompletedProxyConnect = true;
317 mProxyConnectInProgress = false;
318 }
319
320 nsresult rv = NS_OK;
321 bool spdyProxy = mConnInfo->UsingHttpsProxy() && !mTLSFilter;
322 if (spdyProxy) {
323 RefPtr<nsHttpConnectionInfo> wildCardProxyCi;
324 rv = mConnInfo->CreateWildCard(getter_AddRefs(wildCardProxyCi));
325 MOZ_ASSERT(NS_SUCCEEDED(rv));
326 gHttpHandler->ConnMgr()->MoveToWildCardConnEntry(mConnInfo, wildCardProxyCi,
327 this);
328 mConnInfo = wildCardProxyCi;
329 MOZ_ASSERT(mConnInfo);
330 }
331
332 if (!mDid0RTTSpdy) {
333 rv = MoveTransactionsToSpdy(status, list);
334 if (NS_FAILED(rv)) {
335 return;
336 }
337 }
338
339 // Disable TCP Keepalives - use SPDY ping instead.
340 rv = DisableTCPKeepalives();
341 if (NS_FAILED(rv)) {
342 LOG(
343 ("nsHttpConnection::StartSpdy [%p] DisableTCPKeepalives failed "
344 "rv[0x%" PRIx32 "]",
345 this, static_cast<uint32_t>(rv)));
346 }
347
348 mIdleTimeout = gHttpHandler->SpdyTimeout() * mDefaultTimeoutFactor;
349
350 if (!mTLSFilter) {
351 mTransaction = mSpdySession;
352 } else {
353 rv = mTLSFilter->SetProxiedTransaction(mSpdySession);
354 if (NS_FAILED(rv)) {
355 LOG(
356 ("nsHttpConnection::StartSpdy [%p] SetProxiedTransaction failed"
357 " rv[0x%x]",
358 this, static_cast<uint32_t>(rv)));
359 }
360 }
361 if (mDontReuse) {
362 mSpdySession->DontReuse();
363 }
364 }
365
EnsureNPNComplete(nsresult & aOut0RTTWriteHandshakeValue,uint32_t & aOut0RTTBytesWritten)366 bool nsHttpConnection::EnsureNPNComplete(nsresult& aOut0RTTWriteHandshakeValue,
367 uint32_t& aOut0RTTBytesWritten) {
368 // If for some reason the components to check on NPN aren't available,
369 // this function will just return true to continue on and disable SPDY
370
371 aOut0RTTWriteHandshakeValue = NS_OK;
372 aOut0RTTBytesWritten = 0;
373
374 MOZ_ASSERT(mSocketTransport);
375 if (!mSocketTransport) {
376 // this cannot happen
377 mNPNComplete = true;
378 return true;
379 }
380
381 if (mNPNComplete) {
382 return true;
383 }
384
385 nsresult rv = NS_OK;
386 nsCOMPtr<nsISupports> securityInfo;
387 nsCOMPtr<nsITransportSecurityInfo> info;
388 nsCOMPtr<nsISSLSocketControl> ssl;
389 nsAutoCString negotiatedNPN;
390 // This is needed for telemetry
391 bool handshakeSucceeded = false;
392
393 GetSecurityInfo(getter_AddRefs(securityInfo));
394 if (!securityInfo) {
395 goto npnComplete;
396 }
397
398 ssl = do_QueryInterface(securityInfo, &rv);
399 if (NS_FAILED(rv)) goto npnComplete;
400
401 info = do_QueryInterface(securityInfo, &rv);
402 if (NS_FAILED(rv)) goto npnComplete;
403
404 if (!m0RTTChecked) {
405 // We reuse m0RTTChecked. We want to send this status only once.
406 mTransaction->OnTransportStatus(mSocketTransport,
407 NS_NET_STATUS_TLS_HANDSHAKE_STARTING, 0);
408 }
409
410 rv = info->GetNegotiatedNPN(negotiatedNPN);
411 if (!m0RTTChecked && (rv == NS_ERROR_NOT_CONNECTED) &&
412 !mConnInfo->UsingProxy()) {
413 // There is no ALPN info (yet!). We need to consider doing 0RTT. We
414 // will do so if there is ALPN information from a previous session
415 // (AlpnEarlySelection), we are using HTTP/1, and the request data can
416 // be safely retried.
417 m0RTTChecked = true;
418 nsresult rvEarlyAlpn = ssl->GetAlpnEarlySelection(mEarlyNegotiatedALPN);
419 if (NS_FAILED(rvEarlyAlpn)) {
420 // if ssl->DriveHandshake() has never been called the value
421 // for AlpnEarlySelection is still not set. So call it here and
422 // check again.
423 LOG1(
424 ("nsHttpConnection::EnsureNPNComplete %p - "
425 "early selected alpn not available, we will try one more time.",
426 this));
427 // Let's do DriveHandshake again.
428 rv = ssl->DriveHandshake();
429 if (NS_FAILED(rv) && rv != NS_BASE_STREAM_WOULD_BLOCK) {
430 goto npnComplete;
431 }
432
433 // Check NegotiatedNPN first.
434 rv = info->GetNegotiatedNPN(negotiatedNPN);
435 if (rv == NS_ERROR_NOT_CONNECTED) {
436 rvEarlyAlpn = ssl->GetAlpnEarlySelection(mEarlyNegotiatedALPN);
437 }
438 }
439
440 if (NS_FAILED(rvEarlyAlpn)) {
441 LOG1(
442 ("nsHttpConnection::EnsureNPNComplete %p - "
443 "early selected alpn not available",
444 this));
445 mEarlyDataNegotiated = false;
446 } else {
447 LOG1(
448 ("nsHttpConnection::EnsureNPNComplete %p -"
449 "early selected alpn: %s",
450 this, mEarlyNegotiatedALPN.get()));
451 uint32_t infoIndex;
452 const SpdyInformation* info = gHttpHandler->SpdyInfo();
453 if (NS_FAILED(info->GetNPNIndex(mEarlyNegotiatedALPN, &infoIndex))) {
454 // This is the HTTP/1 case.
455 // Check if early-data is allowed for this transaction.
456 if (mTransaction->Do0RTT()) {
457 LOG(
458 ("nsHttpConnection::EnsureNPNComplete [this=%p] - We "
459 "can do 0RTT (http/1)!",
460 this));
461 mWaitingFor0RTTResponse = true;
462 }
463 } else {
464 // We have h2, we can at least 0-RTT the preamble and opening
465 // SETTINGS, etc, and maybe some of the first request
466 LOG(
467 ("nsHttpConnection::EnsureNPNComplete [this=%p] - Starting "
468 "0RTT for h2!",
469 this));
470 mWaitingFor0RTTResponse = true;
471 Start0RTTSpdy(info->Version[infoIndex]);
472 }
473 mEarlyDataNegotiated = true;
474 }
475 }
476
477 if (rv == NS_ERROR_NOT_CONNECTED) {
478 if (mWaitingFor0RTTResponse) {
479 aOut0RTTWriteHandshakeValue = mTransaction->ReadSegments(
480 this, nsIOService::gDefaultSegmentSize, &aOut0RTTBytesWritten);
481 if (NS_FAILED(aOut0RTTWriteHandshakeValue) &&
482 aOut0RTTWriteHandshakeValue != NS_BASE_STREAM_WOULD_BLOCK) {
483 goto npnComplete;
484 }
485 LOG(
486 ("nsHttpConnection::EnsureNPNComplete [this=%p] - written %d "
487 "bytes during 0RTT",
488 this, aOut0RTTBytesWritten));
489 mContentBytesWritten0RTT += aOut0RTTBytesWritten;
490 }
491
492 rv = ssl->DriveHandshake();
493 if (NS_FAILED(rv) && rv != NS_BASE_STREAM_WOULD_BLOCK) {
494 goto npnComplete;
495 }
496
497 return false;
498 }
499
500 if (NS_SUCCEEDED(rv)) {
501 LOG1(("nsHttpConnection::EnsureNPNComplete %p [%s] negotiated to '%s'%s\n",
502 this, mConnInfo->HashKey().get(), negotiatedNPN.get(),
503 mTLSFilter ? " [Double Tunnel]" : ""));
504
505 handshakeSucceeded = true;
506
507 int16_t tlsVersion;
508 ssl->GetSSLVersionUsed(&tlsVersion);
509 mConnInfo->SetLessThanTls13(
510 (tlsVersion < nsISSLSocketControl::TLS_VERSION_1_3) &&
511 (tlsVersion != nsISSLSocketControl::SSL_VERSION_UNKNOWN));
512
513 bool earlyDataAccepted = false;
514 if (mWaitingFor0RTTResponse) {
515 // Check if early data has been accepted.
516 nsresult rvEarlyData = ssl->GetEarlyDataAccepted(&earlyDataAccepted);
517 LOG(
518 ("nsHttpConnection::EnsureNPNComplete [this=%p] - early data "
519 "that was sent during 0RTT %s been accepted [rv=%" PRIx32 "].",
520 this, earlyDataAccepted ? "has" : "has not",
521 static_cast<uint32_t>(rv)));
522
523 if (NS_FAILED(rvEarlyData) ||
524 NS_FAILED(mTransaction->Finish0RTT(
525 !earlyDataAccepted, negotiatedNPN != mEarlyNegotiatedALPN))) {
526 LOG(
527 ("nsHttpConection::EnsureNPNComplete [this=%p] closing transaction "
528 "%p",
529 this, mTransaction.get()));
530 mTransaction->Close(NS_ERROR_NET_RESET);
531 goto npnComplete;
532 }
533 }
534
535 // Send the 0RTT telemetry only for tls1.3
536 if (tlsVersion > nsISSLSocketControl::TLS_VERSION_1_2) {
537 Telemetry::Accumulate(
538 Telemetry::TLS_EARLY_DATA_NEGOTIATED,
539 (!mEarlyDataNegotiated)
540 ? TLS_EARLY_DATA_NOT_AVAILABLE
541 : ((mWaitingFor0RTTResponse)
542 ? TLS_EARLY_DATA_AVAILABLE_AND_USED
543 : TLS_EARLY_DATA_AVAILABLE_BUT_NOT_USED));
544 if (mWaitingFor0RTTResponse) {
545 Telemetry::Accumulate(Telemetry::TLS_EARLY_DATA_ACCEPTED,
546 earlyDataAccepted);
547 }
548 if (earlyDataAccepted) {
549 Telemetry::Accumulate(Telemetry::TLS_EARLY_DATA_BYTES_WRITTEN,
550 mContentBytesWritten0RTT);
551 }
552 }
553 mWaitingFor0RTTResponse = false;
554
555 if (!earlyDataAccepted) {
556 LOG(
557 ("nsHttpConnection::EnsureNPNComplete [this=%p] early data not "
558 "accepted",
559 this));
560 if (mTransaction->QueryNullTransaction() &&
561 (mBootstrappedTimings.secureConnectionStart.IsNull() ||
562 mBootstrappedTimings.tcpConnectEnd.IsNull())) {
563 mBootstrappedTimings.secureConnectionStart =
564 mTransaction->QueryNullTransaction()->GetSecureConnectionStart();
565 mBootstrappedTimings.tcpConnectEnd =
566 mTransaction->QueryNullTransaction()->GetTcpConnectEnd();
567 }
568 uint32_t infoIndex;
569 const SpdyInformation* info = gHttpHandler->SpdyInfo();
570 if (NS_SUCCEEDED(info->GetNPNIndex(negotiatedNPN, &infoIndex))) {
571 StartSpdy(ssl, info->Version[infoIndex]);
572 }
573 } else {
574 LOG(("nsHttpConnection::EnsureNPNComplete [this=%p] - %" PRId64 " bytes "
575 "has been sent during 0RTT.",
576 this, mContentBytesWritten0RTT));
577 mContentBytesWritten = mContentBytesWritten0RTT;
578 if (mSpdySession) {
579 // We had already started 0RTT-spdy, now we need to fully set up
580 // spdy, since we know we're sticking with it.
581 LOG(
582 ("nsHttpConnection::EnsureNPNComplete [this=%p] - finishing "
583 "StartSpdy for 0rtt spdy session %p",
584 this, mSpdySession.get()));
585 StartSpdy(ssl, mSpdySession->SpdyVersion());
586 }
587 }
588
589 Telemetry::Accumulate(Telemetry::SPDY_NPN_CONNECT, UsingSpdy());
590 }
591
592 npnComplete:
593 LOG(("nsHttpConnection::EnsureNPNComplete [this=%p] setting complete to true",
594 this));
595 mNPNComplete = true;
596
597 mTransaction->OnTransportStatus(mSocketTransport,
598 NS_NET_STATUS_TLS_HANDSHAKE_ENDED, 0);
599
600 // this is happening after the bootstrap was originally written to. so update
601 // it.
602 if (mTransaction->QueryNullTransaction() &&
603 (mBootstrappedTimings.secureConnectionStart.IsNull() ||
604 mBootstrappedTimings.tcpConnectEnd.IsNull())) {
605 mBootstrappedTimings.secureConnectionStart =
606 mTransaction->QueryNullTransaction()->GetSecureConnectionStart();
607 mBootstrappedTimings.tcpConnectEnd =
608 mTransaction->QueryNullTransaction()->GetTcpConnectEnd();
609 }
610
611 if (securityInfo) {
612 mBootstrappedTimings.connectEnd = TimeStamp::Now();
613 }
614
615 if (mWaitingFor0RTTResponse) {
616 // Didn't get 0RTT OK, back out of the "attempting 0RTT" state
617 mWaitingFor0RTTResponse = false;
618 LOG(("nsHttpConnection::EnsureNPNComplete [this=%p] 0rtt failed", this));
619 if (NS_FAILED(mTransaction->Finish0RTT(
620 true, negotiatedNPN != mEarlyNegotiatedALPN))) {
621 mTransaction->Close(NS_ERROR_NET_RESET);
622 }
623 mContentBytesWritten0RTT = 0;
624 }
625
626 if (mDid0RTTSpdy && negotiatedNPN != mEarlyNegotiatedALPN) {
627 // Reset the work done by Start0RTTSpdy
628 LOG((
629 "nsHttpConnection::EnsureNPNComplete [this=%p] resetting Start0RTTSpdy",
630 this));
631 mUsingSpdyVersion = SpdyVersion::NONE;
632 mTransaction = nullptr;
633 mSpdySession = nullptr;
634 // We have to reset this here, just in case we end up starting spdy again,
635 // so it can actually do everything it needs to do.
636 mDid0RTTSpdy = false;
637 }
638
639 if (ssl) {
640 // Telemetry for tls failure rate with and without esni;
641 bool echConfigUsed = false;
642 mSocketTransport->GetEchConfigUsed(&echConfigUsed);
643 TlsHandshakeResult result =
644 echConfigUsed
645 ? (handshakeSucceeded ? TlsHandshakeResult::EchConfigSuccessful
646 : TlsHandshakeResult::EchConfigFailed)
647 : (handshakeSucceeded ? TlsHandshakeResult::NoEchConfigSuccessful
648 : TlsHandshakeResult::NoEchConfigFailed);
649 Telemetry::Accumulate(Telemetry::ECHCONFIG_SUCCESS_RATE, result);
650 }
651
652 if (rv == psm::GetXPCOMFromNSSError(
653 mozilla::pkix::MOZILLA_PKIX_ERROR_MITM_DETECTED)) {
654 gSocketTransportService->SetNotTrustedMitmDetected();
655 }
656 return true;
657 }
658
OnTunnelNudged(TLSFilterTransaction * trans)659 nsresult nsHttpConnection::OnTunnelNudged(TLSFilterTransaction* trans) {
660 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
661 LOG(("nsHttpConnection::OnTunnelNudged %p\n", this));
662 if (trans != mTLSFilter) {
663 return NS_OK;
664 }
665 LOG(("nsHttpConnection::OnTunnelNudged %p Calling OnSocketWritable\n", this));
666 return OnSocketWritable();
667 }
668
669 // called on the socket thread
Activate(nsAHttpTransaction * trans,uint32_t caps,int32_t pri)670 nsresult nsHttpConnection::Activate(nsAHttpTransaction* trans, uint32_t caps,
671 int32_t pri) {
672 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
673 LOG1(("nsHttpConnection::Activate [this=%p trans=%p caps=%x]\n", this, trans,
674 caps));
675
676 if (!mExperienced && !trans->IsNullTransaction()) {
677 if (mNPNComplete) {
678 mExperienced = true;
679 }
680 if (mBootstrappedTimingsSet) {
681 mBootstrappedTimingsSet = false;
682 nsHttpTransaction* hTrans = trans->QueryHttpTransaction();
683 if (hTrans) {
684 hTrans->BootstrapTimings(mBootstrappedTimings);
685 SetUrgentStartPreferred(hTrans->ClassOfService() &
686 nsIClassOfService::UrgentStart);
687 }
688 }
689 mBootstrappedTimings = TimingStruct();
690 }
691
692 if (caps & NS_HTTP_LARGE_KEEPALIVE) {
693 mDefaultTimeoutFactor = 10; // don't ever lower
694 }
695
696 mTransactionCaps = caps;
697 mPriority = pri;
698 if (mTransaction && (mUsingSpdyVersion != SpdyVersion::NONE)) {
699 return AddTransaction(trans, pri);
700 }
701
702 NS_ENSURE_ARG_POINTER(trans);
703 NS_ENSURE_TRUE(!mTransaction, NS_ERROR_IN_PROGRESS);
704
705 // reset the read timers to wash away any idle time
706 mLastWriteTime = mLastReadTime = PR_IntervalNow();
707
708 // Connection failures are Activated() just like regular transacions.
709 // If we don't have a confirmation of a connected socket then test it
710 // with a write() to get relevant error code.
711 if (NS_FAILED(mErrorBeforeConnect)) {
712 mSocketOutCondition = mErrorBeforeConnect;
713 mTransaction = trans;
714 CloseTransaction(mTransaction, mSocketOutCondition);
715 return mSocketOutCondition;
716 }
717
718 if (!mConnectedTransport) {
719 uint32_t count;
720 mSocketOutCondition = NS_ERROR_FAILURE;
721 if (mSocketOut) {
722 mSocketOutCondition = mSocketOut->Write("", 0, &count);
723 }
724 if (NS_FAILED(mSocketOutCondition) &&
725 mSocketOutCondition != NS_BASE_STREAM_WOULD_BLOCK) {
726 LOG(("nsHttpConnection::Activate [this=%p] Bad Socket %" PRIx32 "\n",
727 this, static_cast<uint32_t>(mSocketOutCondition)));
728 mSocketOut->AsyncWait(nullptr, 0, 0, nullptr);
729 mTransaction = trans;
730 CloseTransaction(mTransaction, mSocketOutCondition);
731 return mSocketOutCondition;
732 }
733 }
734
735 // Update security callbacks
736 nsCOMPtr<nsIInterfaceRequestor> callbacks;
737 trans->GetSecurityCallbacks(getter_AddRefs(callbacks));
738 SetSecurityCallbacks(callbacks);
739 SetupSSL();
740
741 // take ownership of the transaction
742 mTransaction = trans;
743
744 MOZ_ASSERT(!mIdleMonitoring, "Activating a connection with an Idle Monitor");
745 mIdleMonitoring = false;
746
747 // set mKeepAlive according to what will be requested
748 mKeepAliveMask = mKeepAlive = (caps & NS_HTTP_ALLOW_KEEPALIVE);
749
750 // need to handle HTTP CONNECT tunnels if this is the first time if
751 // we are tunneling through a proxy
752 nsresult rv = NS_OK;
753 if (mTransaction->ConnectionInfo()->UsingConnect() &&
754 !mCompletedProxyConnect) {
755 rv = SetupProxyConnect();
756 if (NS_FAILED(rv)) goto failed_activation;
757 mProxyConnectInProgress = true;
758 }
759
760 // Clear the per activation counter
761 mCurrentBytesRead = 0;
762
763 // The overflow state is not needed between activations
764 mInputOverflow = nullptr;
765
766 mResponseTimeoutEnabled = gHttpHandler->ResponseTimeoutEnabled() &&
767 mTransaction->ResponseTimeout() > 0 &&
768 mTransaction->ResponseTimeoutEnabled();
769
770 rv = StartShortLivedTCPKeepalives();
771 if (NS_FAILED(rv)) {
772 LOG(
773 ("nsHttpConnection::Activate [%p] "
774 "StartShortLivedTCPKeepalives failed rv[0x%" PRIx32 "]",
775 this, static_cast<uint32_t>(rv)));
776 }
777
778 if (mTLSFilter) {
779 RefPtr<NullHttpTransaction> baseTrans(do_QueryReferent(mWeakTrans));
780 rv = mTLSFilter->SetProxiedTransaction(trans, baseTrans);
781 NS_ENSURE_SUCCESS(rv, rv);
782 if (mTransaction->ConnectionInfo()->UsingConnect()) {
783 SpdyConnectTransaction* trans =
784 baseTrans ? baseTrans->QuerySpdyConnectTransaction() : nullptr;
785 if (trans && !trans->IsWebsocket()) {
786 // If we are here, the tunnel is already established. Let the
787 // transaction know that proxy connect is successful.
788 mTransaction->OnProxyConnectComplete(200);
789 }
790 }
791 mTransaction = mTLSFilter;
792 }
793
794 trans->OnActivated();
795
796 rv = OnOutputStreamReady(mSocketOut);
797
798 failed_activation:
799 if (NS_FAILED(rv)) {
800 mTransaction = nullptr;
801 }
802
803 return rv;
804 }
805
SetupSSL()806 void nsHttpConnection::SetupSSL() {
807 LOG1(("nsHttpConnection::SetupSSL %p caps=0x%X %s\n", this, mTransactionCaps,
808 mConnInfo->HashKey().get()));
809
810 if (mSetupSSLCalled) { // do only once
811 return;
812 }
813 mSetupSSLCalled = true;
814
815 if (mNPNComplete) return;
816
817 // we flip this back to false if SetNPNList succeeds at the end
818 // of this function
819 mNPNComplete = true;
820
821 if (!mConnInfo->FirstHopSSL() || mForcePlainText) {
822 return;
823 }
824
825 // if we are connected to the proxy with TLS, start the TLS
826 // flow immediately without waiting for a CONNECT sequence.
827 DebugOnly<nsresult> rv{};
828 if (mInSpdyTunnel) {
829 rv = InitSSLParams(false, true);
830 } else {
831 bool usingHttpsProxy = mConnInfo->UsingHttpsProxy();
832 rv = InitSSLParams(usingHttpsProxy, usingHttpsProxy);
833 }
834 MOZ_ASSERT(NS_SUCCEEDED(rv));
835 }
836
837 // The naming of NPN is historical - this function creates the basic
838 // offer list for both NPN and ALPN. ALPN validation callbacks are made
839 // now before the handshake is complete, and NPN validation callbacks
840 // are made during the handshake.
SetupNPNList(nsISSLSocketControl * ssl,uint32_t caps)841 nsresult nsHttpConnection::SetupNPNList(nsISSLSocketControl* ssl,
842 uint32_t caps) {
843 nsTArray<nsCString> protocolArray;
844
845 nsCString npnToken = mConnInfo->GetNPNToken();
846 if (npnToken.IsEmpty()) {
847 // The first protocol is used as the fallback if none of the
848 // protocols supported overlap with the server's list.
849 // When using ALPN the advertised preferences are protocolArray indicies
850 // {1, .., N, 0} in decreasing order.
851 // For NPN, In the case of overlap, matching priority is driven by
852 // the order of the server's advertisement - with index 0 used when
853 // there is no match.
854 protocolArray.AppendElement("http/1.1"_ns);
855
856 if (gHttpHandler->IsSpdyEnabled() && !(caps & NS_HTTP_DISALLOW_SPDY)) {
857 LOG(("nsHttpConnection::SetupSSL Allow SPDY NPN selection"));
858 const SpdyInformation* info = gHttpHandler->SpdyInfo();
859 for (uint32_t index = SpdyInformation::kCount; index > 0; --index) {
860 if (info->ProtocolEnabled(index - 1) &&
861 info->ALPNCallbacks[index - 1](ssl)) {
862 protocolArray.AppendElement(info->VersionString[index - 1]);
863 }
864 }
865 }
866 } else {
867 LOG(("nsHttpConnection::SetupSSL limiting NPN selection to %s",
868 npnToken.get()));
869 protocolArray.AppendElement(npnToken);
870 }
871
872 nsresult rv = ssl->SetNPNList(protocolArray);
873 LOG(("nsHttpConnection::SetupNPNList %p %" PRIx32 "\n", this,
874 static_cast<uint32_t>(rv)));
875 return rv;
876 }
877
AddTransaction(nsAHttpTransaction * httpTransaction,int32_t priority)878 nsresult nsHttpConnection::AddTransaction(nsAHttpTransaction* httpTransaction,
879 int32_t priority) {
880 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
881 MOZ_ASSERT(mSpdySession && (mUsingSpdyVersion != SpdyVersion::NONE),
882 "AddTransaction to live http connection without spdy/quic");
883
884 // If this is a wild card nshttpconnection (i.e. a spdy proxy) then
885 // it is important to start the stream using the specific connection
886 // info of the transaction to ensure it is routed on the right tunnel
887
888 nsHttpConnectionInfo* transCI = httpTransaction->ConnectionInfo();
889
890 bool needTunnel = transCI->UsingHttpsProxy();
891 needTunnel = needTunnel && !mTLSFilter;
892 needTunnel = needTunnel && transCI->UsingConnect();
893 needTunnel = needTunnel && httpTransaction->QueryHttpTransaction();
894
895 // Let the transaction know that the tunnel is already established and we
896 // don't need to setup the tunnel again.
897 if (transCI->UsingConnect() && mEverUsedSpdy && mTLSFilter) {
898 httpTransaction->OnProxyConnectComplete(200);
899 }
900
901 bool isWebsocket = false;
902 nsHttpTransaction* trans = httpTransaction->QueryHttpTransaction();
903 if (trans) {
904 isWebsocket = trans->IsWebsocketUpgrade();
905 MOZ_ASSERT(!isWebsocket || !needTunnel, "Websocket and tunnel?!");
906 }
907
908 LOG(("nsHttpConnection::AddTransaction [this=%p] for %s%s", this,
909 mSpdySession ? "SPDY" : "QUIC",
910 needTunnel ? " over tunnel" : (isWebsocket ? " websocket" : "")));
911
912 if (mSpdySession) {
913 if (!mSpdySession->AddStream(httpTransaction, priority, needTunnel,
914 isWebsocket, mCallbacks)) {
915 MOZ_ASSERT(false); // this cannot happen!
916 httpTransaction->Close(NS_ERROR_ABORT);
917 return NS_ERROR_FAILURE;
918 }
919 }
920
921 Unused << ResumeSend();
922 return NS_OK;
923 }
924
Close(nsresult reason,bool aIsShutdown)925 void nsHttpConnection::Close(nsresult reason, bool aIsShutdown) {
926 LOG(("nsHttpConnection::Close [this=%p reason=%" PRIx32 "]\n", this,
927 static_cast<uint32_t>(reason)));
928
929 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
930
931 // Ensure TCP keepalive timer is stopped.
932 if (mTCPKeepaliveTransitionTimer) {
933 mTCPKeepaliveTransitionTimer->Cancel();
934 mTCPKeepaliveTransitionTimer = nullptr;
935 }
936 if (mForceSendTimer) {
937 mForceSendTimer->Cancel();
938 mForceSendTimer = nullptr;
939 }
940
941 if (!mTrafficCategory.IsEmpty()) {
942 HttpTrafficAnalyzer* hta = gHttpHandler->GetHttpTrafficAnalyzer();
943 if (hta) {
944 hta->IncrementHttpConnection(std::move(mTrafficCategory));
945 MOZ_ASSERT(mTrafficCategory.IsEmpty());
946 }
947 }
948
949 if (NS_FAILED(reason)) {
950 if (mIdleMonitoring) EndIdleMonitoring();
951
952 mTLSFilter = nullptr;
953
954 // The connection and security errors clear out alt-svc mappings
955 // in case any previously validated ones are now invalid
956 if (((reason == NS_ERROR_NET_RESET) ||
957 (NS_ERROR_GET_MODULE(reason) == NS_ERROR_MODULE_SECURITY)) &&
958 mConnInfo && !(mTransactionCaps & NS_HTTP_ERROR_SOFTLY)) {
959 gHttpHandler->ClearHostMapping(mConnInfo);
960 }
961
962 if (mSocketTransport) {
963 mSocketTransport->SetEventSink(nullptr, nullptr);
964
965 // If there are bytes sitting in the input queue then read them
966 // into a junk buffer to avoid generating a tcp rst by closing a
967 // socket with data pending. TLS is a classic case of this where
968 // a Alert record might be superfulous to a clean HTTP/SPDY shutdown.
969 // Never block to do this and limit it to a small amount of data.
970 // During shutdown just be fast!
971 if (mSocketIn && !aIsShutdown) {
972 char buffer[4000];
973 uint32_t count, total = 0;
974 nsresult rv;
975 do {
976 rv = mSocketIn->Read(buffer, 4000, &count);
977 if (NS_SUCCEEDED(rv)) total += count;
978 } while (NS_SUCCEEDED(rv) && count > 0 && total < 64000);
979 LOG(("nsHttpConnection::Close drained %d bytes\n", total));
980 }
981
982 mSocketTransport->SetSecurityCallbacks(nullptr);
983 mSocketTransport->Close(reason);
984 if (mSocketOut) mSocketOut->AsyncWait(nullptr, 0, 0, nullptr);
985 }
986 mKeepAlive = false;
987 }
988 }
989
990 // called on the socket thread
InitSSLParams(bool connectingToProxy,bool proxyStartSSL)991 nsresult nsHttpConnection::InitSSLParams(bool connectingToProxy,
992 bool proxyStartSSL) {
993 LOG(("nsHttpConnection::InitSSLParams [this=%p] connectingToProxy=%d\n", this,
994 connectingToProxy));
995 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
996
997 nsresult rv;
998 nsCOMPtr<nsISupports> securityInfo;
999 GetSecurityInfo(getter_AddRefs(securityInfo));
1000 if (!securityInfo) {
1001 return NS_ERROR_FAILURE;
1002 }
1003
1004 nsCOMPtr<nsISSLSocketControl> ssl = do_QueryInterface(securityInfo, &rv);
1005 if (NS_FAILED(rv)) {
1006 return rv;
1007 }
1008
1009 if (proxyStartSSL) {
1010 rv = ssl->ProxyStartSSL();
1011 if (NS_FAILED(rv)) {
1012 return rv;
1013 }
1014 }
1015
1016 if (NS_SUCCEEDED(SetupNPNList(ssl, mTransactionCaps))) {
1017 LOG(("InitSSLParams Setting up SPDY Negotiation OK"));
1018 mNPNComplete = false;
1019 }
1020
1021 return NS_OK;
1022 }
1023
DontReuse()1024 void nsHttpConnection::DontReuse() {
1025 LOG(("nsHttpConnection::DontReuse %p spdysession=%p\n", this,
1026 mSpdySession.get()));
1027 mKeepAliveMask = false;
1028 mKeepAlive = false;
1029 mDontReuse = true;
1030 mIdleTimeout = 0;
1031 if (mSpdySession) {
1032 mSpdySession->DontReuse();
1033 }
1034 }
1035
TestJoinConnection(const nsACString & hostname,int32_t port)1036 bool nsHttpConnection::TestJoinConnection(const nsACString& hostname,
1037 int32_t port) {
1038 if (mSpdySession && CanDirectlyActivate()) {
1039 return mSpdySession->TestJoinConnection(hostname, port);
1040 }
1041
1042 return false;
1043 }
1044
JoinConnection(const nsACString & hostname,int32_t port)1045 bool nsHttpConnection::JoinConnection(const nsACString& hostname,
1046 int32_t port) {
1047 if (mSpdySession && CanDirectlyActivate()) {
1048 return mSpdySession->JoinConnection(hostname, port);
1049 }
1050
1051 return false;
1052 }
1053
CanReuse()1054 bool nsHttpConnection::CanReuse() {
1055 if (mDontReuse || !mRemainingConnectionUses) {
1056 return false;
1057 }
1058
1059 if ((mTransaction ? (mTransaction->IsDone() ? 0U : 1U) : 0U) >=
1060 mRemainingConnectionUses) {
1061 return false;
1062 }
1063
1064 bool canReuse;
1065 if (mSpdySession) {
1066 canReuse = mSpdySession->CanReuse();
1067 } else {
1068 canReuse = IsKeepAlive();
1069 }
1070
1071 canReuse = canReuse && (IdleTime() < mIdleTimeout) && IsAlive();
1072
1073 // An idle persistent connection should not have data waiting to be read
1074 // before a request is sent. Data here is likely a 408 timeout response
1075 // which we would deal with later on through the restart logic, but that
1076 // path is more expensive than just closing the socket now.
1077
1078 uint64_t dataSize;
1079 if (canReuse && mSocketIn && (mUsingSpdyVersion == SpdyVersion::NONE) &&
1080 mHttp1xTransactionCount &&
1081 NS_SUCCEEDED(mSocketIn->Available(&dataSize)) && dataSize) {
1082 LOG(
1083 ("nsHttpConnection::CanReuse %p %s"
1084 "Socket not reusable because read data pending (%" PRIu64 ") on it.\n",
1085 this, mConnInfo->Origin(), dataSize));
1086 canReuse = false;
1087 }
1088 return canReuse;
1089 }
1090
CanDirectlyActivate()1091 bool nsHttpConnection::CanDirectlyActivate() {
1092 // return true if a new transaction can be addded to ths connection at any
1093 // time through Activate(). In practice this means this is a healthy SPDY
1094 // connection with room for more concurrent streams.
1095
1096 return UsingSpdy() && CanReuse() && mSpdySession &&
1097 mSpdySession->RoomForMoreStreams();
1098 }
1099
IdleTime()1100 PRIntervalTime nsHttpConnection::IdleTime() {
1101 return mSpdySession ? mSpdySession->IdleTime()
1102 : (PR_IntervalNow() - mLastReadTime);
1103 }
1104
1105 // returns the number of seconds left before the allowable idle period
1106 // expires, or 0 if the period has already expied.
TimeToLive()1107 uint32_t nsHttpConnection::TimeToLive() {
1108 LOG(("nsHttpConnection::TTL: %p %s idle %d timeout %d\n", this,
1109 mConnInfo->Origin(), IdleTime(), mIdleTimeout));
1110
1111 if (IdleTime() >= mIdleTimeout) {
1112 return 0;
1113 }
1114
1115 uint32_t timeToLive = PR_IntervalToSeconds(mIdleTimeout - IdleTime());
1116
1117 // a positive amount of time can be rounded to 0. Because 0 is used
1118 // as the expiration signal, round all values from 0 to 1 up to 1.
1119 if (!timeToLive) {
1120 timeToLive = 1;
1121 }
1122 return timeToLive;
1123 }
1124
IsAlive()1125 bool nsHttpConnection::IsAlive() {
1126 if (!mSocketTransport || !mConnectedTransport) return false;
1127
1128 // SocketTransport::IsAlive can run the SSL state machine, so make sure
1129 // the NPN options are set before that happens.
1130 SetupSSL();
1131
1132 bool alive;
1133 nsresult rv = mSocketTransport->IsAlive(&alive);
1134 if (NS_FAILED(rv)) alive = false;
1135
1136 //#define TEST_RESTART_LOGIC
1137 #ifdef TEST_RESTART_LOGIC
1138 if (!alive) {
1139 LOG(("pretending socket is still alive to test restart logic\n"));
1140 alive = true;
1141 }
1142 #endif
1143
1144 return alive;
1145 }
1146
SetUrgentStartPreferred(bool urgent)1147 void nsHttpConnection::SetUrgentStartPreferred(bool urgent) {
1148 if (mExperienced && !mUrgentStartPreferredKnown) {
1149 // Set only according the first ever dispatched non-null transaction
1150 mUrgentStartPreferredKnown = true;
1151 mUrgentStartPreferred = urgent;
1152 LOG(("nsHttpConnection::SetUrgentStartPreferred [this=%p urgent=%d]", this,
1153 urgent));
1154 }
1155 }
1156
1157 //----------------------------------------------------------------------------
1158 // nsHttpConnection::nsAHttpConnection compatible methods
1159 //----------------------------------------------------------------------------
1160
OnHeadersAvailable(nsAHttpTransaction * trans,nsHttpRequestHead * requestHead,nsHttpResponseHead * responseHead,bool * reset)1161 nsresult nsHttpConnection::OnHeadersAvailable(nsAHttpTransaction* trans,
1162 nsHttpRequestHead* requestHead,
1163 nsHttpResponseHead* responseHead,
1164 bool* reset) {
1165 LOG(
1166 ("nsHttpConnection::OnHeadersAvailable [this=%p trans=%p "
1167 "response-head=%p]\n",
1168 this, trans, responseHead));
1169
1170 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1171 NS_ENSURE_ARG_POINTER(trans);
1172 MOZ_ASSERT(responseHead, "No response head?");
1173
1174 if (mInSpdyTunnel) {
1175 DebugOnly<nsresult> rv =
1176 responseHead->SetHeader(nsHttp::X_Firefox_Spdy_Proxy, "true"_ns);
1177 MOZ_ASSERT(NS_SUCCEEDED(rv));
1178 }
1179
1180 // we won't change our keep-alive policy unless the server has explicitly
1181 // told us to do so.
1182
1183 // inspect the connection headers for keep-alive info provided the
1184 // transaction completed successfully. In the case of a non-sensical close
1185 // and keep-alive favor the close out of conservatism.
1186
1187 bool explicitKeepAlive = false;
1188 bool explicitClose =
1189 responseHead->HasHeaderValue(nsHttp::Connection, "close") ||
1190 responseHead->HasHeaderValue(nsHttp::Proxy_Connection, "close");
1191 if (!explicitClose) {
1192 explicitKeepAlive =
1193 responseHead->HasHeaderValue(nsHttp::Connection, "keep-alive") ||
1194 responseHead->HasHeaderValue(nsHttp::Proxy_Connection, "keep-alive");
1195 }
1196
1197 // deal with 408 Server Timeouts
1198 uint16_t responseStatus = responseHead->Status();
1199 static const PRIntervalTime k1000ms = PR_MillisecondsToInterval(1000);
1200 if (responseStatus == 408) {
1201 // If this error could be due to a persistent connection reuse then
1202 // we pass an error code of NS_ERROR_NET_RESET to
1203 // trigger the transaction 'restart' mechanism. We tell it to reset its
1204 // response headers so that it will be ready to receive the new response.
1205 if (mIsReused && ((PR_IntervalNow() - mLastWriteTime) < k1000ms)) {
1206 Close(NS_ERROR_NET_RESET);
1207 *reset = true;
1208 return NS_OK;
1209 }
1210
1211 // timeouts that are not caused by persistent connection reuse should
1212 // not be retried for browser compatibility reasons. bug 907800. The
1213 // server driven close is implicit in the 408.
1214 explicitClose = true;
1215 explicitKeepAlive = false;
1216 }
1217
1218 if ((responseHead->Version() < HttpVersion::v1_1) ||
1219 (requestHead->Version() < HttpVersion::v1_1)) {
1220 // HTTP/1.0 connections are by default NOT persistent
1221 mKeepAlive = explicitKeepAlive;
1222 } else {
1223 // HTTP/1.1 connections are by default persistent
1224 mKeepAlive = !explicitClose;
1225 }
1226 mKeepAliveMask = mKeepAlive;
1227
1228 // if this connection is persistent, then the server may send a "Keep-Alive"
1229 // header specifying the maximum number of times the connection can be
1230 // reused as well as the maximum amount of time the connection can be idle
1231 // before the server will close it. we ignore the max reuse count, because
1232 // a "keep-alive" connection is by definition capable of being reused, and
1233 // we only care about being able to reuse it once. if a timeout is not
1234 // specified then we use our advertized timeout value.
1235 bool foundKeepAliveMax = false;
1236 if (mKeepAlive) {
1237 nsAutoCString keepAlive;
1238 Unused << responseHead->GetHeader(nsHttp::Keep_Alive, keepAlive);
1239
1240 if (mUsingSpdyVersion == SpdyVersion::NONE) {
1241 const char* cp = nsCRT::strcasestr(keepAlive.get(), "timeout=");
1242 if (cp) {
1243 mIdleTimeout = PR_SecondsToInterval((uint32_t)atoi(cp + 8));
1244 } else {
1245 mIdleTimeout = gHttpHandler->IdleTimeout() * mDefaultTimeoutFactor;
1246 }
1247
1248 cp = nsCRT::strcasestr(keepAlive.get(), "max=");
1249 if (cp) {
1250 int maxUses = atoi(cp + 4);
1251 if (maxUses > 0) {
1252 foundKeepAliveMax = true;
1253 mRemainingConnectionUses = static_cast<uint32_t>(maxUses);
1254 }
1255 }
1256 }
1257
1258 LOG(("Connection can be reused [this=%p idle-timeout=%usec]\n", this,
1259 PR_IntervalToSeconds(mIdleTimeout)));
1260 }
1261
1262 if (!foundKeepAliveMax && mRemainingConnectionUses &&
1263 (mUsingSpdyVersion == SpdyVersion::NONE)) {
1264 --mRemainingConnectionUses;
1265 }
1266
1267 // If we're doing a proxy connect, we need to check whether or not
1268 // it was successful. If so, we have to reset the transaction and step-up
1269 // the socket connection if using SSL. Finally, we have to wake up the
1270 // socket write request.
1271 bool itWasProxyConnect = !!mProxyConnectStream;
1272 if (mProxyConnectStream) {
1273 MOZ_ASSERT(mUsingSpdyVersion == SpdyVersion::NONE,
1274 "SPDY NPN Complete while using proxy connect stream");
1275 mProxyConnectStream = nullptr;
1276 bool isHttps = mTransaction ? mTransaction->ConnectionInfo()->EndToEndSSL()
1277 : mConnInfo->EndToEndSSL();
1278 bool onlyConnect = mTransactionCaps & NS_HTTP_CONNECT_ONLY;
1279
1280 mTransaction->OnProxyConnectComplete(responseStatus);
1281 if (responseStatus == 200) {
1282 LOG(("proxy CONNECT succeeded! endtoendssl=%d onlyconnect=%d\n", isHttps,
1283 onlyConnect));
1284 // If we're only connecting, we don't need to reset the transaction
1285 // state. We need to upgrade the socket now without doing the actual
1286 // http request.
1287 if (!onlyConnect) {
1288 *reset = true;
1289 }
1290 nsresult rv;
1291 // CONNECT only flag doesn't do the tls setup. https here only
1292 // ensures a proxy tunnel was used not that tls is setup.
1293 if (isHttps) {
1294 if (!onlyConnect) {
1295 if (mConnInfo->UsingHttpsProxy()) {
1296 LOG(("%p new TLSFilterTransaction %s %d\n", this,
1297 mConnInfo->Origin(), mConnInfo->OriginPort()));
1298 SetupSecondaryTLS();
1299 }
1300
1301 rv = InitSSLParams(false, true);
1302 LOG(("InitSSLParams [rv=%" PRIx32 "]\n", static_cast<uint32_t>(rv)));
1303 } else {
1304 // We have an https protocol but the CONNECT only flag was
1305 // specified. The consumer only wants a raw socket to the
1306 // proxy. We have to mark this as complete to finish the
1307 // transaction and be upgraded. OnSocketReadable() uses this
1308 // to detect an inactive tunnel and blocks completion.
1309 mNPNComplete = true;
1310 }
1311 }
1312 mCompletedProxyConnect = true;
1313 mProxyConnectInProgress = false;
1314 rv = mSocketOut->AsyncWait(this, 0, 0, nullptr);
1315 // XXX what if this fails -- need to handle this error
1316 MOZ_ASSERT(NS_SUCCEEDED(rv), "mSocketOut->AsyncWait failed");
1317 } else {
1318 LOG(("proxy CONNECT failed! endtoendssl=%d onlyconnect=%d\n", isHttps,
1319 onlyConnect));
1320 mTransaction->SetProxyConnectFailed();
1321 }
1322 }
1323
1324 nsAutoCString upgradeReq;
1325 bool hasUpgradeReq =
1326 NS_SUCCEEDED(requestHead->GetHeader(nsHttp::Upgrade, upgradeReq));
1327 // Don't use persistent connection for Upgrade unless there's an auth failure:
1328 // some proxies expect to see auth response on persistent connection.
1329 // Also allow persistent conn for h2, as we don't want to waste connections
1330 // for multiplexed upgrades.
1331 if (!itWasProxyConnect && hasUpgradeReq && responseStatus != 401 &&
1332 responseStatus != 407 && !mSpdySession) {
1333 LOG(("HTTP Upgrade in play - disable keepalive for http/1.x\n"));
1334 DontReuse();
1335 }
1336
1337 if (responseStatus == 101) {
1338 nsAutoCString upgradeResp;
1339 bool hasUpgradeResp =
1340 NS_SUCCEEDED(responseHead->GetHeader(nsHttp::Upgrade, upgradeResp));
1341 if (!hasUpgradeReq || !hasUpgradeResp ||
1342 !nsHttp::FindToken(upgradeResp.get(), upgradeReq.get(),
1343 HTTP_HEADER_VALUE_SEPS)) {
1344 LOG(("HTTP 101 Upgrade header mismatch req = %s, resp = %s\n",
1345 upgradeReq.get(),
1346 !upgradeResp.IsEmpty() ? upgradeResp.get()
1347 : "RESPONSE's nsHttp::Upgrade is empty"));
1348 Close(NS_ERROR_ABORT);
1349 } else {
1350 LOG(("HTTP Upgrade Response to %s\n", upgradeResp.get()));
1351 }
1352 }
1353
1354 mLastHttpResponseVersion = responseHead->Version();
1355
1356 return NS_OK;
1357 }
1358
IsReused()1359 bool nsHttpConnection::IsReused() {
1360 if (mIsReused) return true;
1361 if (!mConsiderReusedAfterInterval) return false;
1362
1363 // ReusedAfter allows a socket to be consider reused only after a certain
1364 // interval of time has passed
1365 return (PR_IntervalNow() - mConsiderReusedAfterEpoch) >=
1366 mConsiderReusedAfterInterval;
1367 }
1368
SetIsReusedAfter(uint32_t afterMilliseconds)1369 void nsHttpConnection::SetIsReusedAfter(uint32_t afterMilliseconds) {
1370 mConsiderReusedAfterEpoch = PR_IntervalNow();
1371 mConsiderReusedAfterInterval = PR_MillisecondsToInterval(afterMilliseconds);
1372 }
1373
TakeTransport(nsISocketTransport ** aTransport,nsIAsyncInputStream ** aInputStream,nsIAsyncOutputStream ** aOutputStream)1374 nsresult nsHttpConnection::TakeTransport(nsISocketTransport** aTransport,
1375 nsIAsyncInputStream** aInputStream,
1376 nsIAsyncOutputStream** aOutputStream) {
1377 if (mUsingSpdyVersion != SpdyVersion::NONE) return NS_ERROR_FAILURE;
1378 if (mTransaction && !mTransaction->IsDone()) return NS_ERROR_IN_PROGRESS;
1379 if (!(mSocketTransport && mSocketIn && mSocketOut)) {
1380 return NS_ERROR_NOT_INITIALIZED;
1381 }
1382
1383 if (mInputOverflow) mSocketIn = mInputOverflow.forget();
1384
1385 // Change TCP Keepalive frequency to long-lived if currently short-lived.
1386 if (mTCPKeepaliveConfig == kTCPKeepaliveShortLivedConfig) {
1387 if (mTCPKeepaliveTransitionTimer) {
1388 mTCPKeepaliveTransitionTimer->Cancel();
1389 mTCPKeepaliveTransitionTimer = nullptr;
1390 }
1391 nsresult rv = StartLongLivedTCPKeepalives();
1392 LOG(
1393 ("nsHttpConnection::TakeTransport [%p] calling "
1394 "StartLongLivedTCPKeepalives",
1395 this));
1396 if (NS_FAILED(rv)) {
1397 LOG(
1398 ("nsHttpConnection::TakeTransport [%p] "
1399 "StartLongLivedTCPKeepalives failed rv[0x%" PRIx32 "]",
1400 this, static_cast<uint32_t>(rv)));
1401 }
1402 }
1403
1404 mSocketTransport->SetSecurityCallbacks(nullptr);
1405 mSocketTransport->SetEventSink(nullptr, nullptr);
1406
1407 // The nsHttpConnection will go away soon, so if there is a TLS Filter
1408 // being used (e.g. for wss CONNECT tunnel from a proxy connected to
1409 // via https) that filter needs to take direct control of the
1410 // streams
1411 if (mTLSFilter) {
1412 nsCOMPtr<nsIAsyncInputStream> ref1(mSocketIn);
1413 nsCOMPtr<nsIAsyncOutputStream> ref2(mSocketOut);
1414 mTLSFilter->newIODriver(ref1, ref2, getter_AddRefs(mSocketIn),
1415 getter_AddRefs(mSocketOut));
1416 mTLSFilter = nullptr;
1417 }
1418
1419 mSocketTransport.forget(aTransport);
1420 mSocketIn.forget(aInputStream);
1421 mSocketOut.forget(aOutputStream);
1422
1423 return NS_OK;
1424 }
1425
ReadTimeoutTick(PRIntervalTime now)1426 uint32_t nsHttpConnection::ReadTimeoutTick(PRIntervalTime now) {
1427 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1428
1429 // make sure timer didn't tick before Activate()
1430 if (!mTransaction) return UINT32_MAX;
1431
1432 // Spdy implements some timeout handling using the SPDY ping frame.
1433 if (mSpdySession) {
1434 return mSpdySession->ReadTimeoutTick(now);
1435 }
1436
1437 uint32_t nextTickAfter = UINT32_MAX;
1438 // Timeout if the response is taking too long to arrive.
1439 if (mResponseTimeoutEnabled) {
1440 NS_WARNING_ASSERTION(
1441 gHttpHandler->ResponseTimeoutEnabled(),
1442 "Timing out a response, but response timeout is disabled!");
1443
1444 PRIntervalTime initialResponseDelta = now - mLastWriteTime;
1445
1446 if (initialResponseDelta > mTransaction->ResponseTimeout()) {
1447 LOG(("canceling transaction: no response for %ums: timeout is %dms\n",
1448 PR_IntervalToMilliseconds(initialResponseDelta),
1449 PR_IntervalToMilliseconds(mTransaction->ResponseTimeout())));
1450
1451 mResponseTimeoutEnabled = false;
1452
1453 // This will also close the connection
1454 CloseTransaction(mTransaction, NS_ERROR_NET_TIMEOUT);
1455 return UINT32_MAX;
1456 }
1457 nextTickAfter = PR_IntervalToSeconds(mTransaction->ResponseTimeout()) -
1458 PR_IntervalToSeconds(initialResponseDelta);
1459 nextTickAfter = std::max(nextTickAfter, 1U);
1460 }
1461
1462 if (!mNPNComplete) {
1463 // We can reuse mLastWriteTime here, because it is set when the
1464 // connection is activated and only change when a transaction
1465 // succesfullu write to the socket and this can only happen after
1466 // the TLS handshake is done.
1467 PRIntervalTime initialTLSDelta = now - mLastWriteTime;
1468 if (initialTLSDelta >
1469 PR_MillisecondsToInterval(gHttpHandler->TLSHandshakeTimeout())) {
1470 LOG(
1471 ("canceling transaction: tls handshake takes too long: tls handshake "
1472 "last %ums, timeout is %dms.",
1473 PR_IntervalToMilliseconds(initialTLSDelta),
1474 gHttpHandler->TLSHandshakeTimeout()));
1475
1476 // This will also close the connection
1477 CloseTransaction(mTransaction, NS_ERROR_NET_TIMEOUT);
1478 return UINT32_MAX;
1479 }
1480 }
1481
1482 return nextTickAfter;
1483 }
1484
UpdateTCPKeepalive(nsITimer * aTimer,void * aClosure)1485 void nsHttpConnection::UpdateTCPKeepalive(nsITimer* aTimer, void* aClosure) {
1486 MOZ_ASSERT(aTimer);
1487 MOZ_ASSERT(aClosure);
1488
1489 nsHttpConnection* self = static_cast<nsHttpConnection*>(aClosure);
1490
1491 if (NS_WARN_IF(self->mUsingSpdyVersion != SpdyVersion::NONE)) {
1492 return;
1493 }
1494
1495 // Do not reduce keepalive probe frequency for idle connections.
1496 if (self->mIdleMonitoring) {
1497 return;
1498 }
1499
1500 nsresult rv = self->StartLongLivedTCPKeepalives();
1501 if (NS_FAILED(rv)) {
1502 LOG(
1503 ("nsHttpConnection::UpdateTCPKeepalive [%p] "
1504 "StartLongLivedTCPKeepalives failed rv[0x%" PRIx32 "]",
1505 self, static_cast<uint32_t>(rv)));
1506 }
1507 }
1508
GetSecurityInfo(nsISupports ** secinfo)1509 void nsHttpConnection::GetSecurityInfo(nsISupports** secinfo) {
1510 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1511 LOG(("nsHttpConnection::GetSecurityInfo trans=%p tlsfilter=%p socket=%p\n",
1512 mTransaction.get(), mTLSFilter.get(), mSocketTransport.get()));
1513
1514 if (mTransaction &&
1515 NS_SUCCEEDED(mTransaction->GetTransactionSecurityInfo(secinfo))) {
1516 return;
1517 }
1518
1519 if (mTLSFilter &&
1520 NS_SUCCEEDED(mTLSFilter->GetTransactionSecurityInfo(secinfo))) {
1521 return;
1522 }
1523
1524 if (mSocketTransport &&
1525 NS_SUCCEEDED(mSocketTransport->GetSecurityInfo(secinfo))) {
1526 return;
1527 }
1528
1529 *secinfo = nullptr;
1530 }
1531
PushBack(const char * data,uint32_t length)1532 nsresult nsHttpConnection::PushBack(const char* data, uint32_t length) {
1533 LOG(("nsHttpConnection::PushBack [this=%p, length=%d]\n", this, length));
1534
1535 if (mInputOverflow) {
1536 NS_ERROR("nsHttpConnection::PushBack only one buffer supported");
1537 return NS_ERROR_UNEXPECTED;
1538 }
1539
1540 mInputOverflow = new nsPreloadedStream(mSocketIn, data, length);
1541 return NS_OK;
1542 }
1543
1544 class HttpConnectionForceIO : public Runnable {
1545 public:
HttpConnectionForceIO(nsHttpConnection * aConn,bool doRecv)1546 HttpConnectionForceIO(nsHttpConnection* aConn, bool doRecv)
1547 : Runnable("net::HttpConnectionForceIO"), mConn(aConn), mDoRecv(doRecv) {}
1548
Run()1549 NS_IMETHOD Run() override {
1550 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1551
1552 if (mDoRecv) {
1553 if (!mConn->mSocketIn) return NS_OK;
1554 return mConn->OnInputStreamReady(mConn->mSocketIn);
1555 }
1556
1557 MOZ_ASSERT(mConn->mForceSendPending);
1558 mConn->mForceSendPending = false;
1559
1560 if (!mConn->mSocketOut) {
1561 return NS_OK;
1562 }
1563 return mConn->OnOutputStreamReady(mConn->mSocketOut);
1564 }
1565
1566 private:
1567 RefPtr<nsHttpConnection> mConn;
1568 bool mDoRecv;
1569 };
1570
ResumeSend()1571 nsresult nsHttpConnection::ResumeSend() {
1572 LOG(("nsHttpConnection::ResumeSend [this=%p]\n", this));
1573
1574 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1575
1576 if (mSocketOut) {
1577 return mSocketOut->AsyncWait(this, 0, 0, nullptr);
1578 }
1579
1580 MOZ_ASSERT_UNREACHABLE("no socket output stream");
1581 return NS_ERROR_UNEXPECTED;
1582 }
1583
ResumeRecv()1584 nsresult nsHttpConnection::ResumeRecv() {
1585 LOG(("nsHttpConnection::ResumeRecv [this=%p]\n", this));
1586
1587 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1588
1589 // the mLastReadTime timestamp is used for finding slowish readers
1590 // and can be pretty sensitive. For that reason we actually reset it
1591 // when we ask to read (resume recv()) so that when we get called back
1592 // with actual read data in OnSocketReadable() we are only measuring
1593 // the latency between those two acts and not all the processing that
1594 // may get done before the ResumeRecv() call
1595 mLastReadTime = PR_IntervalNow();
1596
1597 if (mSocketIn) {
1598 if (!mTLSFilter || !mTLSFilter->HasDataToRecv() || NS_FAILED(ForceRecv())) {
1599 return mSocketIn->AsyncWait(this, 0, 0, nullptr);
1600 }
1601 return NS_OK;
1602 }
1603
1604 MOZ_ASSERT_UNREACHABLE("no socket input stream");
1605 return NS_ERROR_UNEXPECTED;
1606 }
1607
ForceSendIO(nsITimer * aTimer,void * aClosure)1608 void nsHttpConnection::ForceSendIO(nsITimer* aTimer, void* aClosure) {
1609 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1610 nsHttpConnection* self = static_cast<nsHttpConnection*>(aClosure);
1611 MOZ_ASSERT(aTimer == self->mForceSendTimer);
1612 self->mForceSendTimer = nullptr;
1613 NS_DispatchToCurrentThread(new HttpConnectionForceIO(self, false));
1614 }
1615
MaybeForceSendIO()1616 nsresult nsHttpConnection::MaybeForceSendIO() {
1617 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1618 // due to bug 1213084 sometimes real I/O events do not get serviced when
1619 // NSPR derived I/O events are ready and this can cause a deadlock with
1620 // https over https proxying. Normally we would expect the write callback to
1621 // be invoked before this timer goes off, but set it at the old windows
1622 // tick interval (kForceDelay) as a backup for those circumstances.
1623 static const uint32_t kForceDelay = 17; // ms
1624
1625 if (mForceSendPending) {
1626 return NS_OK;
1627 }
1628 MOZ_ASSERT(!mForceSendTimer);
1629 mForceSendPending = true;
1630 return NS_NewTimerWithFuncCallback(getter_AddRefs(mForceSendTimer),
1631 nsHttpConnection::ForceSendIO, this,
1632 kForceDelay, nsITimer::TYPE_ONE_SHOT,
1633 "net::nsHttpConnection::MaybeForceSendIO");
1634 }
1635
1636 // trigger an asynchronous read
ForceRecv()1637 nsresult nsHttpConnection::ForceRecv() {
1638 LOG(("nsHttpConnection::ForceRecv [this=%p]\n", this));
1639 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1640
1641 return NS_DispatchToCurrentThread(new HttpConnectionForceIO(this, true));
1642 }
1643
1644 // trigger an asynchronous write
ForceSend()1645 nsresult nsHttpConnection::ForceSend() {
1646 LOG(("nsHttpConnection::ForceSend [this=%p]\n", this));
1647 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1648
1649 if (mTLSFilter) {
1650 return mTLSFilter->NudgeTunnel(this);
1651 }
1652 return MaybeForceSendIO();
1653 }
1654
BeginIdleMonitoring()1655 void nsHttpConnection::BeginIdleMonitoring() {
1656 LOG(("nsHttpConnection::BeginIdleMonitoring [this=%p]\n", this));
1657 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1658 MOZ_ASSERT(!mTransaction, "BeginIdleMonitoring() while active");
1659 MOZ_ASSERT(mUsingSpdyVersion == SpdyVersion::NONE,
1660 "Idle monitoring of spdy not allowed");
1661
1662 LOG(("Entering Idle Monitoring Mode [this=%p]", this));
1663 mIdleMonitoring = true;
1664 if (mSocketIn) mSocketIn->AsyncWait(this, 0, 0, nullptr);
1665 }
1666
EndIdleMonitoring()1667 void nsHttpConnection::EndIdleMonitoring() {
1668 LOG(("nsHttpConnection::EndIdleMonitoring [this=%p]\n", this));
1669 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1670 MOZ_ASSERT(!mTransaction, "EndIdleMonitoring() while active");
1671
1672 if (mIdleMonitoring) {
1673 LOG(("Leaving Idle Monitoring Mode [this=%p]", this));
1674 mIdleMonitoring = false;
1675 if (mSocketIn) mSocketIn->AsyncWait(nullptr, 0, 0, nullptr);
1676 }
1677 }
1678
Version()1679 HttpVersion nsHttpConnection::Version() {
1680 if (mUsingSpdyVersion != SpdyVersion::NONE) {
1681 return HttpVersion::v2_0;
1682 }
1683 return mLastHttpResponseVersion;
1684 }
1685
1686 //-----------------------------------------------------------------------------
1687 // nsHttpConnection <private>
1688 //-----------------------------------------------------------------------------
1689
CloseTransaction(nsAHttpTransaction * trans,nsresult reason,bool aIsShutdown)1690 void nsHttpConnection::CloseTransaction(nsAHttpTransaction* trans,
1691 nsresult reason, bool aIsShutdown) {
1692 LOG(("nsHttpConnection::CloseTransaction[this=%p trans=%p reason=%" PRIx32
1693 "]\n",
1694 this, trans, static_cast<uint32_t>(reason)));
1695
1696 MOZ_ASSERT((trans == mTransaction) ||
1697 (mTLSFilter && !mTLSFilter->Transaction()) ||
1698 (mTLSFilter && mTLSFilter->Transaction() == trans));
1699 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
1700
1701 if (mCurrentBytesRead > mMaxBytesRead) mMaxBytesRead = mCurrentBytesRead;
1702
1703 // mask this error code because its not a real error.
1704 if (reason == NS_BASE_STREAM_CLOSED) reason = NS_OK;
1705
1706 if (mUsingSpdyVersion != SpdyVersion::NONE) {
1707 DontReuse();
1708 // if !mSpdySession then mUsingSpdyVersion must be false for canreuse()
1709 mSpdySession->SetCleanShutdown(aIsShutdown);
1710 mUsingSpdyVersion = SpdyVersion::NONE;
1711 mSpdySession = nullptr;
1712 }
1713
1714 if (!mTransaction && mTLSFilter) {
1715 // In case of a race when the transaction is being closed before the tunnel
1716 // is established we need to carry closing status on the proxied
1717 // transaction.
1718 // Not doing this leads to use of this closed connection to activate the
1719 // not closed transaction what will likely lead to a use of a closed ssl
1720 // socket and may cause a crash because of an unexpected use.
1721 //
1722 // There can possibly be two states: the actual transaction is still hanging
1723 // of off the filter, or has not even been assigned on it yet. In the
1724 // latter case we simply must close the transaction given to us via the
1725 // argument.
1726 if (!mTLSFilter->Transaction()) {
1727 if (trans) {
1728 LOG((" closing transaction directly"));
1729 trans->Close(reason);
1730 }
1731 } else {
1732 LOG((" closing transactin hanging of off mTLSFilter"));
1733 mTLSFilter->Close(reason);
1734 }
1735 }
1736
1737 if (mTransaction) {
1738 LOG((" closing associated mTransaction"));
1739 mHttp1xTransactionCount += mTransaction->Http1xTransactionCount();
1740
1741 mTransaction->Close(reason);
1742 mTransaction = nullptr;
1743 }
1744
1745 {
1746 MutexAutoLock lock(mCallbacksLock);
1747 mCallbacks = nullptr;
1748 }
1749
1750 if (NS_FAILED(reason) && (reason != NS_BINDING_RETARGETED)) {
1751 Close(reason, aIsShutdown);
1752 }
1753
1754 // flag the connection as reused here for convenience sake. certainly
1755 // it might be going away instead ;-)
1756 mIsReused = true;
1757 }
1758
ReadFromStream(nsIInputStream * input,void * closure,const char * buf,uint32_t offset,uint32_t count,uint32_t * countRead)1759 nsresult nsHttpConnection::ReadFromStream(nsIInputStream* input, void* closure,
1760 const char* buf, uint32_t offset,
1761 uint32_t count, uint32_t* countRead) {
1762 // thunk for nsIInputStream instance
1763 nsHttpConnection* conn = (nsHttpConnection*)closure;
1764 return conn->OnReadSegment(buf, count, countRead);
1765 }
1766
CheckCanWrite0RTTData()1767 bool nsHttpConnection::CheckCanWrite0RTTData() {
1768 MOZ_ASSERT(mWaitingFor0RTTResponse);
1769 nsCOMPtr<nsISupports> securityInfo;
1770 GetSecurityInfo(getter_AddRefs(securityInfo));
1771 if (!securityInfo) {
1772 return false;
1773 }
1774 nsCOMPtr<nsITransportSecurityInfo> info;
1775 info = do_QueryInterface(securityInfo);
1776 if (!info) {
1777 return false;
1778 }
1779 nsAutoCString negotiatedNPN;
1780 // If the following code fails means that the handshake is not done
1781 // yet, so continue writing 0RTT data.
1782 nsresult rv = info->GetNegotiatedNPN(negotiatedNPN);
1783 if (NS_FAILED(rv)) {
1784 return true;
1785 }
1786 nsCOMPtr<nsISSLSocketControl> ssl;
1787 ssl = do_QueryInterface(securityInfo);
1788 if (!ssl) {
1789 return false;
1790 }
1791 bool earlyDataAccepted = false;
1792 rv = ssl->GetEarlyDataAccepted(&earlyDataAccepted);
1793 // If 0RTT data is accepted we can continue writing data,
1794 // if it is reject stop writing more data.
1795 return NS_SUCCEEDED(rv) && earlyDataAccepted;
1796 }
1797
OnReadSegment(const char * buf,uint32_t count,uint32_t * countRead)1798 nsresult nsHttpConnection::OnReadSegment(const char* buf, uint32_t count,
1799 uint32_t* countRead) {
1800 LOG(("nsHttpConnection::OnReadSegment [this=%p]\n", this));
1801 if (count == 0) {
1802 // some ReadSegments implementations will erroneously call the writer
1803 // to consume 0 bytes worth of data. we must protect against this case
1804 // or else we'd end up closing the socket prematurely.
1805 NS_ERROR("bad ReadSegments implementation");
1806 return NS_ERROR_FAILURE; // stop iterating
1807 }
1808
1809 // If we are waiting for 0RTT Response, check maybe nss has finished
1810 // handshake already.
1811 // IsAlive() calls drive the handshake and that may cause nss and necko
1812 // to be out of sync.
1813 if (mWaitingFor0RTTResponse && !CheckCanWrite0RTTData()) {
1814 LOG(
1815 ("nsHttpConnection::OnReadSegment Do not write any data, wait"
1816 " for EnsureNPNComplete to be called [this=%p]",
1817 this));
1818 *countRead = 0;
1819 return NS_BASE_STREAM_WOULD_BLOCK;
1820 }
1821
1822 nsresult rv = mSocketOut->Write(buf, count, countRead);
1823 if (NS_FAILED(rv)) {
1824 mSocketOutCondition = rv;
1825 } else if (*countRead == 0) {
1826 mSocketOutCondition = NS_BASE_STREAM_CLOSED;
1827 } else {
1828 mLastWriteTime = PR_IntervalNow();
1829 mSocketOutCondition = NS_OK; // reset condition
1830 if (!mProxyConnectInProgress) mTotalBytesWritten += *countRead;
1831 }
1832
1833 return mSocketOutCondition;
1834 }
1835
OnSocketWritable()1836 nsresult nsHttpConnection::OnSocketWritable() {
1837 LOG(("nsHttpConnection::OnSocketWritable [this=%p] host=%s\n", this,
1838 mConnInfo->Origin()));
1839
1840 nsresult rv;
1841 uint32_t transactionBytes;
1842 bool again = true;
1843
1844 // Prevent STS thread from being blocked by single OnOutputStreamReady
1845 // callback.
1846 const uint32_t maxWriteAttempts = 128;
1847 uint32_t writeAttempts = 0;
1848
1849 if (mTransactionCaps & NS_HTTP_CONNECT_ONLY) {
1850 if (!mCompletedProxyConnect && !mProxyConnectStream) {
1851 // A CONNECT has been requested for this connection but will never
1852 // be performed. This should never happen.
1853 MOZ_ASSERT(false, "proxy connect will never happen");
1854 LOG(("return failure because proxy connect will never happen\n"));
1855 return NS_ERROR_FAILURE;
1856 }
1857
1858 if (mCompletedProxyConnect) {
1859 // Don't need to check this each write attempt since it is only
1860 // updated after OnSocketWritable completes.
1861 // We've already done primary tls (if needed) and sent our CONNECT.
1862 // If we're doing a CONNECT only request there's no need to write
1863 // the http transaction or do the SSL handshake here.
1864 LOG(("return ok because proxy connect successful\n"));
1865 return NS_OK;
1866 }
1867 }
1868
1869 do {
1870 ++writeAttempts;
1871 rv = mSocketOutCondition = NS_OK;
1872 transactionBytes = 0;
1873
1874 // The SSL handshake must be completed before the
1875 // transaction->readsegments() processing can proceed because we need to
1876 // know how to format the request differently for http/1, http/2, spdy,
1877 // etc.. and that is negotiated with NPN/ALPN in the SSL handshake.
1878
1879 if (mConnInfo->UsingHttpsProxy() &&
1880 !EnsureNPNComplete(rv, transactionBytes)) {
1881 MOZ_ASSERT(!transactionBytes);
1882 mSocketOutCondition = NS_BASE_STREAM_WOULD_BLOCK;
1883 } else if (mProxyConnectStream) {
1884 // If we're need an HTTP/1 CONNECT tunnel through a proxy
1885 // send it before doing the SSL handshake
1886 LOG((" writing CONNECT request stream\n"));
1887 rv = mProxyConnectStream->ReadSegments(ReadFromStream, this,
1888 nsIOService::gDefaultSegmentSize,
1889 &transactionBytes);
1890 } else if (!EnsureNPNComplete(rv, transactionBytes)) {
1891 if (NS_SUCCEEDED(rv) && !transactionBytes &&
1892 NS_SUCCEEDED(mSocketOutCondition)) {
1893 mSocketOutCondition = NS_BASE_STREAM_WOULD_BLOCK;
1894 }
1895 } else if (!mTransaction) {
1896 rv = NS_ERROR_FAILURE;
1897 LOG((" No Transaction In OnSocketWritable\n"));
1898 } else if (NS_SUCCEEDED(rv)) {
1899 // for non spdy sessions let the connection manager know
1900 if (!mReportedSpdy) {
1901 mReportedSpdy = true;
1902 MOZ_ASSERT(!mEverUsedSpdy);
1903 gHttpHandler->ConnMgr()->ReportSpdyConnection(this, false);
1904 }
1905
1906 LOG((" writing transaction request stream\n"));
1907 mProxyConnectInProgress = false;
1908 rv = mTransaction->ReadSegmentsAgain(
1909 this, nsIOService::gDefaultSegmentSize, &transactionBytes, &again);
1910 mContentBytesWritten += transactionBytes;
1911 }
1912
1913 LOG(
1914 ("nsHttpConnection::OnSocketWritable %p "
1915 "ReadSegments returned [rv=%" PRIx32 " read=%u "
1916 "sock-cond=%" PRIx32 " again=%d]\n",
1917 this, static_cast<uint32_t>(rv), transactionBytes,
1918 static_cast<uint32_t>(mSocketOutCondition), again));
1919
1920 // XXX some streams return NS_BASE_STREAM_CLOSED to indicate EOF.
1921 if (rv == NS_BASE_STREAM_CLOSED && !mTransaction->IsDone()) {
1922 rv = NS_OK;
1923 transactionBytes = 0;
1924 }
1925
1926 if (!again && mWaitingFor0RTTResponse) {
1927 // Continue waiting;
1928 rv = mSocketOut->AsyncWait(this, 0, 0, nullptr);
1929 }
1930 if (NS_FAILED(rv)) {
1931 // if the transaction didn't want to write any more data, then
1932 // wait for the transaction to call ResumeSend.
1933 if (rv == NS_BASE_STREAM_WOULD_BLOCK) {
1934 rv = NS_OK;
1935 if (mWaitingFor0RTTResponse) {
1936 // Continue waiting;
1937 rv = mSocketOut->AsyncWait(this, 0, 0, nullptr);
1938 }
1939 }
1940 again = false;
1941 } else if (NS_FAILED(mSocketOutCondition)) {
1942 if (mSocketOutCondition == NS_BASE_STREAM_WOULD_BLOCK) {
1943 if (mTLSFilter) {
1944 LOG((" blocked tunnel (handshake?)\n"));
1945 rv = mTLSFilter->NudgeTunnel(this);
1946 } else {
1947 rv = mSocketOut->AsyncWait(this, 0, 0, nullptr); // continue writing
1948 }
1949 } else {
1950 rv = mSocketOutCondition;
1951 }
1952 again = false;
1953 } else if (!transactionBytes) {
1954 rv = NS_OK;
1955
1956 if (mWaitingFor0RTTResponse) {
1957 // Wait for tls handshake to finish or waiting for connect.
1958 rv = mSocketOut->AsyncWait(this, 0, 0, nullptr);
1959 } else if (mTransaction) { // in case the ReadSegments stack called
1960 // CloseTransaction()
1961 //
1962 // at this point we've written out the entire transaction, and now we
1963 // must wait for the server's response. we manufacture a status message
1964 // here to reflect the fact that we are waiting. this message will be
1965 // trumped (overwritten) if the server responds quickly.
1966 //
1967 mTransaction->OnTransportStatus(mSocketTransport,
1968 NS_NET_STATUS_WAITING_FOR, 0);
1969
1970 rv = ResumeRecv(); // start reading
1971 }
1972 again = false;
1973 } else if (writeAttempts >= maxWriteAttempts) {
1974 LOG((" yield for other transactions\n"));
1975 rv = mSocketOut->AsyncWait(this, 0, 0, nullptr); // continue writing
1976 again = false;
1977 }
1978 // write more to the socket until error or end-of-request...
1979 } while (again && gHttpHandler->Active());
1980
1981 return rv;
1982 }
1983
OnWriteSegment(char * buf,uint32_t count,uint32_t * countWritten)1984 nsresult nsHttpConnection::OnWriteSegment(char* buf, uint32_t count,
1985 uint32_t* countWritten) {
1986 if (count == 0) {
1987 // some WriteSegments implementations will erroneously call the reader
1988 // to provide 0 bytes worth of data. we must protect against this case
1989 // or else we'd end up closing the socket prematurely.
1990 NS_ERROR("bad WriteSegments implementation");
1991 return NS_ERROR_FAILURE; // stop iterating
1992 }
1993
1994 if (ChaosMode::isActive(ChaosFeature::IOAmounts) &&
1995 ChaosMode::randomUint32LessThan(2)) {
1996 // read 1...count bytes
1997 count = ChaosMode::randomUint32LessThan(count) + 1;
1998 }
1999
2000 nsresult rv = mSocketIn->Read(buf, count, countWritten);
2001 if (NS_FAILED(rv)) {
2002 mSocketInCondition = rv;
2003 } else if (*countWritten == 0) {
2004 mSocketInCondition = NS_BASE_STREAM_CLOSED;
2005 } else {
2006 mSocketInCondition = NS_OK; // reset condition
2007 }
2008
2009 return mSocketInCondition;
2010 }
2011
OnSocketReadable()2012 nsresult nsHttpConnection::OnSocketReadable() {
2013 LOG(("nsHttpConnection::OnSocketReadable [this=%p]\n", this));
2014
2015 PRIntervalTime now = PR_IntervalNow();
2016 PRIntervalTime delta = now - mLastReadTime;
2017
2018 // Reset mResponseTimeoutEnabled to stop response timeout checks.
2019 mResponseTimeoutEnabled = false;
2020
2021 if ((mTransactionCaps & NS_HTTP_CONNECT_ONLY) && !mCompletedProxyConnect &&
2022 !mProxyConnectStream) {
2023 // A CONNECT has been requested for this connection but will never
2024 // be performed. This should never happen.
2025 MOZ_ASSERT(false, "proxy connect will never happen");
2026 LOG(("return failure because proxy connect will never happen\n"));
2027 return NS_ERROR_FAILURE;
2028 }
2029
2030 if (mKeepAliveMask && (delta >= mMaxHangTime)) {
2031 LOG(("max hang time exceeded!\n"));
2032 // give the handler a chance to create a new persistent connection to
2033 // this host if we've been busy for too long.
2034 mKeepAliveMask = false;
2035 Unused << gHttpHandler->ProcessPendingQ(mConnInfo);
2036 }
2037
2038 // Reduce the estimate of the time since last read by up to 1 RTT to
2039 // accommodate exhausted sender TCP congestion windows or minor I/O delays.
2040 mLastReadTime = now;
2041
2042 nsresult rv;
2043 uint32_t n;
2044 bool again = true;
2045
2046 do {
2047 if (!mProxyConnectInProgress && !mNPNComplete) {
2048 // Unless we are setting up a tunnel via CONNECT, prevent reading
2049 // from the socket until the results of NPN
2050 // negotiation are known (which is determined from the write path).
2051 // If the server speaks SPDY it is likely the readable data here is
2052 // a spdy settings frame and without NPN it would be misinterpreted
2053 // as HTTP/*
2054
2055 LOG(
2056 ("nsHttpConnection::OnSocketReadable %p return due to inactive "
2057 "tunnel setup but incomplete NPN state\n",
2058 this));
2059 rv = NS_OK;
2060 break;
2061 }
2062
2063 mSocketInCondition = NS_OK;
2064 rv = mTransaction->WriteSegmentsAgain(
2065 this, nsIOService::gDefaultSegmentSize, &n, &again);
2066 LOG(("nsHttpConnection::OnSocketReadable %p trans->ws rv=%" PRIx32
2067 " n=%d socketin=%" PRIx32 "\n",
2068 this, static_cast<uint32_t>(rv), n,
2069 static_cast<uint32_t>(mSocketInCondition)));
2070 if (NS_FAILED(rv)) {
2071 // if the transaction didn't want to take any more data, then
2072 // wait for the transaction to call ResumeRecv.
2073 if (rv == NS_BASE_STREAM_WOULD_BLOCK) {
2074 rv = NS_OK;
2075 }
2076 again = false;
2077 } else {
2078 mCurrentBytesRead += n;
2079 mTotalBytesRead += n;
2080 if (NS_FAILED(mSocketInCondition)) {
2081 // continue waiting for the socket if necessary...
2082 if (mSocketInCondition == NS_BASE_STREAM_WOULD_BLOCK) {
2083 rv = ResumeRecv();
2084 } else {
2085 rv = mSocketInCondition;
2086 }
2087 again = false;
2088 }
2089 }
2090 // read more from the socket until error...
2091 } while (again && gHttpHandler->Active());
2092
2093 return rv;
2094 }
2095
SetupSecondaryTLS(nsAHttpTransaction * aSpdyConnectTransaction)2096 void nsHttpConnection::SetupSecondaryTLS(
2097 nsAHttpTransaction* aSpdyConnectTransaction) {
2098 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
2099 MOZ_ASSERT(!mTLSFilter);
2100 LOG(
2101 ("nsHttpConnection %p SetupSecondaryTLS %s %d "
2102 "aSpdyConnectTransaction=%p\n",
2103 this, mConnInfo->Origin(), mConnInfo->OriginPort(),
2104 aSpdyConnectTransaction));
2105
2106 nsHttpConnectionInfo* ci = nullptr;
2107 if (mTransaction) {
2108 ci = mTransaction->ConnectionInfo();
2109 }
2110 if (!ci) {
2111 ci = mConnInfo;
2112 }
2113 MOZ_ASSERT(ci);
2114
2115 mTLSFilter = new TLSFilterTransaction(mTransaction, ci->Origin(),
2116 ci->OriginPort(), this, this);
2117
2118 if (mTransaction) {
2119 mTransaction = mTLSFilter;
2120 }
2121 mWeakTrans = do_GetWeakReference(aSpdyConnectTransaction);
2122 }
2123
SetInSpdyTunnel(bool arg)2124 void nsHttpConnection::SetInSpdyTunnel(bool arg) {
2125 MOZ_ASSERT(mTLSFilter);
2126 mInSpdyTunnel = arg;
2127
2128 // don't setup another tunnel :)
2129 mProxyConnectStream = nullptr;
2130 mCompletedProxyConnect = true;
2131 mProxyConnectInProgress = false;
2132 }
2133
2134 // static
MakeConnectString(nsAHttpTransaction * trans,nsHttpRequestHead * request,nsACString & result,bool h2ws)2135 nsresult nsHttpConnection::MakeConnectString(nsAHttpTransaction* trans,
2136 nsHttpRequestHead* request,
2137 nsACString& result, bool h2ws) {
2138 result.Truncate();
2139 if (!trans->ConnectionInfo()) {
2140 return NS_ERROR_NOT_INITIALIZED;
2141 }
2142
2143 DebugOnly<nsresult> rv{};
2144
2145 rv = nsHttpHandler::GenerateHostPort(
2146 nsDependentCString(trans->ConnectionInfo()->Origin()),
2147 trans->ConnectionInfo()->OriginPort(), result);
2148 MOZ_ASSERT(NS_SUCCEEDED(rv));
2149
2150 // CONNECT host:port HTTP/1.1
2151 request->SetMethod("CONNECT"_ns);
2152 request->SetVersion(gHttpHandler->HttpVersion());
2153 if (h2ws) {
2154 // HTTP/2 websocket CONNECT forms need the full request URI
2155 nsAutoCString requestURI;
2156 trans->RequestHead()->RequestURI(requestURI);
2157 request->SetRequestURI(requestURI);
2158
2159 request->SetHTTPS(trans->RequestHead()->IsHTTPS());
2160 } else {
2161 request->SetRequestURI(result);
2162 }
2163 rv = request->SetHeader(nsHttp::User_Agent, gHttpHandler->UserAgent());
2164 MOZ_ASSERT(NS_SUCCEEDED(rv));
2165
2166 // a CONNECT is always persistent
2167 rv = request->SetHeader(nsHttp::Proxy_Connection, "keep-alive"_ns);
2168 MOZ_ASSERT(NS_SUCCEEDED(rv));
2169 rv = request->SetHeader(nsHttp::Connection, "keep-alive"_ns);
2170 MOZ_ASSERT(NS_SUCCEEDED(rv));
2171
2172 // all HTTP/1.1 requests must include a Host header (even though it
2173 // may seem redundant in this case; see bug 82388).
2174 rv = request->SetHeader(nsHttp::Host, result);
2175 MOZ_ASSERT(NS_SUCCEEDED(rv));
2176
2177 nsAutoCString val;
2178 if (NS_SUCCEEDED(
2179 trans->RequestHead()->GetHeader(nsHttp::Proxy_Authorization, val))) {
2180 // we don't know for sure if this authorization is intended for the
2181 // SSL proxy, so we add it just in case.
2182 rv = request->SetHeader(nsHttp::Proxy_Authorization, val);
2183 MOZ_ASSERT(NS_SUCCEEDED(rv));
2184 }
2185
2186 if ((trans->Caps() & NS_HTTP_CONNECT_ONLY) &&
2187 NS_SUCCEEDED(trans->RequestHead()->GetHeader(nsHttp::Upgrade, val))) {
2188 // rfc7639 proposes using the ALPN header to indicate the protocol used
2189 // in CONNECT when not used for TLS. The protocol is stored in Upgrade.
2190 // We have to copy this header here since a new HEAD request is created
2191 // for the CONNECT.
2192 rv = request->SetHeader("ALPN"_ns, val);
2193 MOZ_ASSERT(NS_SUCCEEDED(rv));
2194 }
2195
2196 result.Truncate();
2197 request->Flatten(result, false);
2198
2199 if (LOG1_ENABLED()) {
2200 LOG(("nsHttpConnection::MakeConnectString for transaction=%p [",
2201 trans->QueryHttpTransaction()));
2202 LogHeaders(result.BeginReading());
2203 LOG(("]"));
2204 }
2205
2206 result.AppendLiteral("\r\n");
2207 return NS_OK;
2208 }
2209
SetupProxyConnect()2210 nsresult nsHttpConnection::SetupProxyConnect() {
2211 LOG(("nsHttpConnection::SetupProxyConnect [this=%p]\n", this));
2212 NS_ENSURE_TRUE(!mProxyConnectStream, NS_ERROR_ALREADY_INITIALIZED);
2213 MOZ_ASSERT(mUsingSpdyVersion == SpdyVersion::NONE,
2214 "SPDY NPN Complete while using proxy connect stream");
2215
2216 nsAutoCString buf;
2217 nsHttpRequestHead request;
2218 nsresult rv = MakeConnectString(mTransaction, &request, buf, false);
2219 if (NS_FAILED(rv)) {
2220 return rv;
2221 }
2222 return NS_NewCStringInputStream(getter_AddRefs(mProxyConnectStream),
2223 std::move(buf));
2224 }
2225
StartShortLivedTCPKeepalives()2226 nsresult nsHttpConnection::StartShortLivedTCPKeepalives() {
2227 if (mUsingSpdyVersion != SpdyVersion::NONE) {
2228 return NS_OK;
2229 }
2230 MOZ_ASSERT(mSocketTransport);
2231 if (!mSocketTransport) {
2232 return NS_ERROR_NOT_INITIALIZED;
2233 }
2234
2235 nsresult rv = NS_OK;
2236 int32_t idleTimeS = -1;
2237 int32_t retryIntervalS = -1;
2238 if (gHttpHandler->TCPKeepaliveEnabledForShortLivedConns()) {
2239 // Set the idle time.
2240 idleTimeS = gHttpHandler->GetTCPKeepaliveShortLivedIdleTime();
2241 LOG(
2242 ("nsHttpConnection::StartShortLivedTCPKeepalives[%p] "
2243 "idle time[%ds].",
2244 this, idleTimeS));
2245
2246 retryIntervalS = std::max<int32_t>((int32_t)PR_IntervalToSeconds(mRtt), 1);
2247 rv = mSocketTransport->SetKeepaliveVals(idleTimeS, retryIntervalS);
2248 if (NS_FAILED(rv)) {
2249 return rv;
2250 }
2251 rv = mSocketTransport->SetKeepaliveEnabled(true);
2252 mTCPKeepaliveConfig = kTCPKeepaliveShortLivedConfig;
2253 } else {
2254 rv = mSocketTransport->SetKeepaliveEnabled(false);
2255 mTCPKeepaliveConfig = kTCPKeepaliveDisabled;
2256 }
2257 if (NS_FAILED(rv)) {
2258 return rv;
2259 }
2260
2261 // Start a timer to move to long-lived keepalive config.
2262 if (!mTCPKeepaliveTransitionTimer) {
2263 mTCPKeepaliveTransitionTimer = NS_NewTimer();
2264 }
2265
2266 if (mTCPKeepaliveTransitionTimer) {
2267 int32_t time = gHttpHandler->GetTCPKeepaliveShortLivedTime();
2268
2269 // Adjust |time| to ensure a full set of keepalive probes can be sent
2270 // at the end of the short-lived phase.
2271 if (gHttpHandler->TCPKeepaliveEnabledForShortLivedConns()) {
2272 if (NS_WARN_IF(!gSocketTransportService)) {
2273 return NS_ERROR_NOT_INITIALIZED;
2274 }
2275 int32_t probeCount = -1;
2276 rv = gSocketTransportService->GetKeepaliveProbeCount(&probeCount);
2277 if (NS_WARN_IF(NS_FAILED(rv))) {
2278 return rv;
2279 }
2280 if (NS_WARN_IF(probeCount <= 0)) {
2281 return NS_ERROR_UNEXPECTED;
2282 }
2283 // Add time for final keepalive probes, and 2 seconds for a buffer.
2284 time += ((probeCount)*retryIntervalS) - (time % idleTimeS) + 2;
2285 }
2286 mTCPKeepaliveTransitionTimer->InitWithNamedFuncCallback(
2287 nsHttpConnection::UpdateTCPKeepalive, this, (uint32_t)time * 1000,
2288 nsITimer::TYPE_ONE_SHOT,
2289 "net::nsHttpConnection::StartShortLivedTCPKeepalives");
2290 } else {
2291 NS_WARNING(
2292 "nsHttpConnection::StartShortLivedTCPKeepalives failed to "
2293 "create timer.");
2294 }
2295
2296 return NS_OK;
2297 }
2298
StartLongLivedTCPKeepalives()2299 nsresult nsHttpConnection::StartLongLivedTCPKeepalives() {
2300 MOZ_ASSERT(mUsingSpdyVersion == SpdyVersion::NONE,
2301 "Don't use TCP Keepalive with SPDY!");
2302 if (NS_WARN_IF(mUsingSpdyVersion != SpdyVersion::NONE)) {
2303 return NS_OK;
2304 }
2305 MOZ_ASSERT(mSocketTransport);
2306 if (!mSocketTransport) {
2307 return NS_ERROR_NOT_INITIALIZED;
2308 }
2309
2310 nsresult rv = NS_OK;
2311 if (gHttpHandler->TCPKeepaliveEnabledForLongLivedConns()) {
2312 // Increase the idle time.
2313 int32_t idleTimeS = gHttpHandler->GetTCPKeepaliveLongLivedIdleTime();
2314 LOG(("nsHttpConnection::StartLongLivedTCPKeepalives[%p] idle time[%ds]",
2315 this, idleTimeS));
2316
2317 int32_t retryIntervalS =
2318 std::max<int32_t>((int32_t)PR_IntervalToSeconds(mRtt), 1);
2319 rv = mSocketTransport->SetKeepaliveVals(idleTimeS, retryIntervalS);
2320 if (NS_FAILED(rv)) {
2321 return rv;
2322 }
2323
2324 // Ensure keepalive is enabled, if current status is disabled.
2325 if (mTCPKeepaliveConfig == kTCPKeepaliveDisabled) {
2326 rv = mSocketTransport->SetKeepaliveEnabled(true);
2327 if (NS_FAILED(rv)) {
2328 return rv;
2329 }
2330 }
2331 mTCPKeepaliveConfig = kTCPKeepaliveLongLivedConfig;
2332 } else {
2333 rv = mSocketTransport->SetKeepaliveEnabled(false);
2334 mTCPKeepaliveConfig = kTCPKeepaliveDisabled;
2335 }
2336
2337 if (NS_FAILED(rv)) {
2338 return rv;
2339 }
2340 return NS_OK;
2341 }
2342
DisableTCPKeepalives()2343 nsresult nsHttpConnection::DisableTCPKeepalives() {
2344 MOZ_ASSERT(mSocketTransport);
2345 if (!mSocketTransport) {
2346 return NS_ERROR_NOT_INITIALIZED;
2347 }
2348
2349 LOG(("nsHttpConnection::DisableTCPKeepalives [%p]", this));
2350 if (mTCPKeepaliveConfig != kTCPKeepaliveDisabled) {
2351 nsresult rv = mSocketTransport->SetKeepaliveEnabled(false);
2352 if (NS_FAILED(rv)) {
2353 return rv;
2354 }
2355 mTCPKeepaliveConfig = kTCPKeepaliveDisabled;
2356 }
2357 if (mTCPKeepaliveTransitionTimer) {
2358 mTCPKeepaliveTransitionTimer->Cancel();
2359 mTCPKeepaliveTransitionTimer = nullptr;
2360 }
2361 return NS_OK;
2362 }
2363
2364 //-----------------------------------------------------------------------------
2365 // nsHttpConnection::nsISupports
2366 //-----------------------------------------------------------------------------
2367
2368 NS_IMPL_ADDREF(nsHttpConnection)
NS_IMPL_RELEASE(nsHttpConnection)2369 NS_IMPL_RELEASE(nsHttpConnection)
2370
2371 NS_INTERFACE_MAP_BEGIN(nsHttpConnection)
2372 NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
2373 NS_INTERFACE_MAP_ENTRY(nsIInputStreamCallback)
2374 NS_INTERFACE_MAP_ENTRY(nsIOutputStreamCallback)
2375 NS_INTERFACE_MAP_ENTRY(nsITransportEventSink)
2376 NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
2377 NS_INTERFACE_MAP_ENTRY(HttpConnectionBase)
2378 NS_INTERFACE_MAP_ENTRY_CONCRETE(nsHttpConnection)
2379 NS_INTERFACE_MAP_END
2380
2381 //-----------------------------------------------------------------------------
2382 // nsHttpConnection::nsIInputStreamCallback
2383 //-----------------------------------------------------------------------------
2384
2385 // called on the socket transport thread
2386 NS_IMETHODIMP
2387 nsHttpConnection::OnInputStreamReady(nsIAsyncInputStream* in) {
2388 MOZ_ASSERT(in == mSocketIn, "unexpected stream");
2389 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
2390
2391 if (mIdleMonitoring) {
2392 MOZ_ASSERT(!mTransaction, "Idle Input Event While Active");
2393
2394 // The only read event that is protocol compliant for an idle connection
2395 // is an EOF, which we check for with CanReuse(). If the data is
2396 // something else then just ignore it and suspend checking for EOF -
2397 // our normal timers or protocol stack are the place to deal with
2398 // any exception logic.
2399
2400 if (!CanReuse()) {
2401 LOG(("Server initiated close of idle conn %p\n", this));
2402 Unused << gHttpHandler->ConnMgr()->CloseIdleConnection(this);
2403 return NS_OK;
2404 }
2405
2406 LOG(("Input data on idle conn %p, but not closing yet\n", this));
2407 return NS_OK;
2408 }
2409
2410 // if the transaction was dropped...
2411 if (!mTransaction) {
2412 LOG((" no transaction; ignoring event\n"));
2413 return NS_OK;
2414 }
2415
2416 nsresult rv = OnSocketReadable();
2417 if (NS_FAILED(rv)) CloseTransaction(mTransaction, rv);
2418
2419 return NS_OK;
2420 }
2421
2422 //-----------------------------------------------------------------------------
2423 // nsHttpConnection::nsIOutputStreamCallback
2424 //-----------------------------------------------------------------------------
2425
2426 NS_IMETHODIMP
OnOutputStreamReady(nsIAsyncOutputStream * out)2427 nsHttpConnection::OnOutputStreamReady(nsIAsyncOutputStream* out) {
2428 MOZ_ASSERT(OnSocketThread(), "not on socket thread");
2429 MOZ_ASSERT(out == mSocketOut, "unexpected socket");
2430 // if the transaction was dropped...
2431 if (!mTransaction) {
2432 LOG((" no transaction; ignoring event\n"));
2433 return NS_OK;
2434 }
2435
2436 nsresult rv = OnSocketWritable();
2437 if (NS_FAILED(rv)) CloseTransaction(mTransaction, rv);
2438
2439 return NS_OK;
2440 }
2441
2442 //-----------------------------------------------------------------------------
2443 // nsHttpConnection::nsITransportEventSink
2444 //-----------------------------------------------------------------------------
2445
2446 NS_IMETHODIMP
OnTransportStatus(nsITransport * trans,nsresult status,int64_t progress,int64_t progressMax)2447 nsHttpConnection::OnTransportStatus(nsITransport* trans, nsresult status,
2448 int64_t progress, int64_t progressMax) {
2449 if (mTransaction) mTransaction->OnTransportStatus(trans, status, progress);
2450 return NS_OK;
2451 }
2452
2453 //-----------------------------------------------------------------------------
2454 // nsHttpConnection::nsIInterfaceRequestor
2455 //-----------------------------------------------------------------------------
2456
2457 // not called on the socket transport thread
2458 NS_IMETHODIMP
GetInterface(const nsIID & iid,void ** result)2459 nsHttpConnection::GetInterface(const nsIID& iid, void** result) {
2460 // NOTE: This function is only called on the UI thread via sync proxy from
2461 // the socket transport thread. If that weren't the case, then we'd
2462 // have to worry about the possibility of mTransaction going away
2463 // part-way through this function call. See CloseTransaction.
2464
2465 // NOTE - there is a bug here, the call to getinterface is proxied off the
2466 // nss thread, not the ui thread as the above comment says. So there is
2467 // indeed a chance of mTransaction going away. bug 615342
2468
2469 MOZ_ASSERT(!OnSocketThread(), "on socket thread");
2470
2471 nsCOMPtr<nsIInterfaceRequestor> callbacks;
2472 {
2473 MutexAutoLock lock(mCallbacksLock);
2474 callbacks = mCallbacks;
2475 }
2476 if (callbacks) return callbacks->GetInterface(iid, result);
2477 return NS_ERROR_NO_INTERFACE;
2478 }
2479
CheckForTraffic(bool check)2480 void nsHttpConnection::CheckForTraffic(bool check) {
2481 if (check) {
2482 LOG((" CheckForTraffic conn %p\n", this));
2483 if (mSpdySession) {
2484 if (PR_IntervalToMilliseconds(IdleTime()) >= 500) {
2485 // Send a ping to verify it is still alive if it has been idle
2486 // more than half a second, the network changed events are
2487 // rate-limited to one per 1000 ms.
2488 LOG((" SendPing\n"));
2489 mSpdySession->SendPing();
2490 } else {
2491 LOG((" SendPing skipped due to network activity\n"));
2492 }
2493 } else {
2494 // If not SPDY, Store snapshot amount of data right now
2495 mTrafficCount = mTotalBytesWritten + mTotalBytesRead;
2496 mTrafficStamp = true;
2497 }
2498 } else {
2499 // mark it as not checked
2500 mTrafficStamp = false;
2501 }
2502 }
2503
SetEvent(nsresult aStatus)2504 void nsHttpConnection::SetEvent(nsresult aStatus) {
2505 switch (aStatus) {
2506 case NS_NET_STATUS_RESOLVING_HOST:
2507 mBootstrappedTimings.domainLookupStart = TimeStamp::Now();
2508 break;
2509 case NS_NET_STATUS_RESOLVED_HOST:
2510 mBootstrappedTimings.domainLookupEnd = TimeStamp::Now();
2511 break;
2512 case NS_NET_STATUS_CONNECTING_TO:
2513 mBootstrappedTimings.connectStart = TimeStamp::Now();
2514 break;
2515 case NS_NET_STATUS_CONNECTED_TO: {
2516 TimeStamp tnow = TimeStamp::Now();
2517 mBootstrappedTimings.tcpConnectEnd = tnow;
2518 mBootstrappedTimings.connectEnd = tnow;
2519 mBootstrappedTimings.secureConnectionStart = tnow;
2520 break;
2521 }
2522 case NS_NET_STATUS_TLS_HANDSHAKE_STARTING:
2523 mBootstrappedTimings.secureConnectionStart = TimeStamp::Now();
2524 break;
2525 case NS_NET_STATUS_TLS_HANDSHAKE_ENDED:
2526 mBootstrappedTimings.connectEnd = TimeStamp::Now();
2527 break;
2528 default:
2529 break;
2530 }
2531 }
2532
NoClientCertAuth() const2533 bool nsHttpConnection::NoClientCertAuth() const {
2534 if (!mSocketTransport) {
2535 return false;
2536 }
2537
2538 nsCOMPtr<nsISupports> secInfo;
2539 mSocketTransport->GetSecurityInfo(getter_AddRefs(secInfo));
2540 if (!secInfo) {
2541 return false;
2542 }
2543
2544 nsCOMPtr<nsISSLSocketControl> ssc(do_QueryInterface(secInfo));
2545 if (!ssc) {
2546 return false;
2547 }
2548
2549 return !ssc->GetClientCertSent();
2550 }
2551
CanAcceptWebsocket()2552 bool nsHttpConnection::CanAcceptWebsocket() {
2553 if (!UsingSpdy()) {
2554 return true;
2555 }
2556
2557 return mSpdySession->CanAcceptWebsocket();
2558 }
2559
IsProxyConnectInProgress()2560 bool nsHttpConnection::IsProxyConnectInProgress() {
2561 return mProxyConnectInProgress;
2562 }
2563
LastTransactionExpectedNoContent()2564 bool nsHttpConnection::LastTransactionExpectedNoContent() {
2565 return mLastTransactionExpectedNoContent;
2566 }
2567
SetLastTransactionExpectedNoContent(bool val)2568 void nsHttpConnection::SetLastTransactionExpectedNoContent(bool val) {
2569 mLastTransactionExpectedNoContent = val;
2570 }
2571
IsPersistent()2572 bool nsHttpConnection::IsPersistent() { return IsKeepAlive() && !mDontReuse; }
2573
Transaction()2574 nsAHttpTransaction* nsHttpConnection::Transaction() { return mTransaction; }
2575
GetSelfAddr(NetAddr * addr)2576 nsresult nsHttpConnection::GetSelfAddr(NetAddr* addr) {
2577 if (!mSocketTransport) {
2578 return NS_ERROR_FAILURE;
2579 }
2580 return mSocketTransport->GetSelfAddr(addr);
2581 }
2582
GetPeerAddr(NetAddr * addr)2583 nsresult nsHttpConnection::GetPeerAddr(NetAddr* addr) {
2584 if (!mSocketTransport) {
2585 return NS_ERROR_FAILURE;
2586 }
2587 return mSocketTransport->GetPeerAddr(addr);
2588 }
2589
ResolvedByTRR()2590 bool nsHttpConnection::ResolvedByTRR() {
2591 bool val = false;
2592 if (mSocketTransport) {
2593 mSocketTransport->ResolvedByTRR(&val);
2594 }
2595 return val;
2596 }
2597
GetEchConfigUsed()2598 bool nsHttpConnection::GetEchConfigUsed() {
2599 bool val = false;
2600 if (mSocketTransport) {
2601 mSocketTransport->GetEchConfigUsed(&val);
2602 }
2603 return val;
2604 }
2605
2606 } // namespace net
2607 } // namespace mozilla
2608