1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/netwerk/protocol/http/nsHttpConnection.cpp Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,1879 @@ 1.4 +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ 1.5 +/* vim:set ts=4 sw=4 sts=4 et cin: */ 1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.9 + 1.10 +// HttpLog.h should generally be included first 1.11 +#include "HttpLog.h" 1.12 + 1.13 +// Log on level :5, instead of default :4. 1.14 +#undef LOG 1.15 +#define LOG(args) LOG5(args) 1.16 +#undef LOG_ENABLED 1.17 +#define LOG_ENABLED() LOG5_ENABLED() 1.18 + 1.19 +#include "nsHttpConnection.h" 1.20 +#include "nsHttpRequestHead.h" 1.21 +#include "nsHttpResponseHead.h" 1.22 +#include "nsHttpHandler.h" 1.23 +#include "nsIOService.h" 1.24 +#include "nsISocketTransport.h" 1.25 +#include "nsSocketTransportService2.h" 1.26 +#include "nsISSLSocketControl.h" 1.27 +#include "sslt.h" 1.28 +#include "nsStringStream.h" 1.29 +#include "nsProxyRelease.h" 1.30 +#include "nsPreloadedStream.h" 1.31 +#include "ASpdySession.h" 1.32 +#include "mozilla/Telemetry.h" 1.33 +#include "nsISupportsPriority.h" 1.34 +#include "nsHttpPipeline.h" 1.35 +#include <algorithm> 1.36 +#include "mozilla/ChaosMode.h" 1.37 + 1.38 +#ifdef DEBUG 1.39 +// defined by the socket transport service while active 1.40 +extern PRThread *gSocketThread; 1.41 +#endif 1.42 + 1.43 +namespace mozilla { 1.44 +namespace net { 1.45 + 1.46 +//----------------------------------------------------------------------------- 1.47 +// nsHttpConnection <public> 1.48 +//----------------------------------------------------------------------------- 1.49 + 1.50 +nsHttpConnection::nsHttpConnection() 1.51 + : mTransaction(nullptr) 1.52 + , mHttpHandler(gHttpHandler) 1.53 + , mCallbacksLock("nsHttpConnection::mCallbacksLock") 1.54 + , mConsiderReusedAfterInterval(0) 1.55 + , mConsiderReusedAfterEpoch(0) 1.56 + , mCurrentBytesRead(0) 1.57 + , mMaxBytesRead(0) 1.58 + , mTotalBytesRead(0) 1.59 + , mTotalBytesWritten(0) 1.60 + , mKeepAlive(true) // assume to keep-alive by default 1.61 + , mKeepAliveMask(true) 1.62 + , mDontReuse(false) 1.63 + , mSupportsPipelining(false) // assume low-grade server 1.64 + , mIsReused(false) 1.65 + , mCompletedProxyConnect(false) 1.66 + , mLastTransactionExpectedNoContent(false) 1.67 + , mIdleMonitoring(false) 1.68 + , mProxyConnectInProgress(false) 1.69 + , mExperienced(false) 1.70 + , mHttp1xTransactionCount(0) 1.71 + , mRemainingConnectionUses(0xffffffff) 1.72 + , mClassification(nsAHttpTransaction::CLASS_GENERAL) 1.73 + , mNPNComplete(false) 1.74 + , mSetupSSLCalled(false) 1.75 + , mUsingSpdyVersion(0) 1.76 + , mPriority(nsISupportsPriority::PRIORITY_NORMAL) 1.77 + , mReportedSpdy(false) 1.78 + , mEverUsedSpdy(false) 1.79 + , mLastHttpResponseVersion(NS_HTTP_VERSION_1_1) 1.80 + , mTransactionCaps(0) 1.81 + , mResponseTimeoutEnabled(false) 1.82 + , mTCPKeepaliveConfig(kTCPKeepaliveDisabled) 1.83 +{ 1.84 + LOG(("Creating nsHttpConnection @%x\n", this)); 1.85 + 1.86 + // the default timeout is for when this connection has not yet processed a 1.87 + // transaction 1.88 + static const PRIntervalTime k5Sec = PR_SecondsToInterval(5); 1.89 + mIdleTimeout = 1.90 + (k5Sec < gHttpHandler->IdleTimeout()) ? k5Sec : gHttpHandler->IdleTimeout(); 1.91 +} 1.92 + 1.93 +nsHttpConnection::~nsHttpConnection() 1.94 +{ 1.95 + LOG(("Destroying nsHttpConnection @%x\n", this)); 1.96 + 1.97 + if (!mEverUsedSpdy) { 1.98 + LOG(("nsHttpConnection %p performed %d HTTP/1.x transactions\n", 1.99 + this, mHttp1xTransactionCount)); 1.100 + Telemetry::Accumulate(Telemetry::HTTP_REQUEST_PER_CONN, 1.101 + mHttp1xTransactionCount); 1.102 + } 1.103 + 1.104 + if (mTotalBytesRead) { 1.105 + uint32_t totalKBRead = static_cast<uint32_t>(mTotalBytesRead >> 10); 1.106 + LOG(("nsHttpConnection %p read %dkb on connection spdy=%d\n", 1.107 + this, totalKBRead, mEverUsedSpdy)); 1.108 + Telemetry::Accumulate(mEverUsedSpdy ? 1.109 + Telemetry::SPDY_KBREAD_PER_CONN : 1.110 + Telemetry::HTTP_KBREAD_PER_CONN, 1.111 + totalKBRead); 1.112 + } 1.113 +} 1.114 + 1.115 +nsresult 1.116 +nsHttpConnection::Init(nsHttpConnectionInfo *info, 1.117 + uint16_t maxHangTime, 1.118 + nsISocketTransport *transport, 1.119 + nsIAsyncInputStream *instream, 1.120 + nsIAsyncOutputStream *outstream, 1.121 + nsIInterfaceRequestor *callbacks, 1.122 + PRIntervalTime rtt) 1.123 +{ 1.124 + MOZ_ASSERT(transport && instream && outstream, 1.125 + "invalid socket information"); 1.126 + LOG(("nsHttpConnection::Init [this=%p " 1.127 + "transport=%p instream=%p outstream=%p rtt=%d]\n", 1.128 + this, transport, instream, outstream, 1.129 + PR_IntervalToMilliseconds(rtt))); 1.130 + 1.131 + NS_ENSURE_ARG_POINTER(info); 1.132 + NS_ENSURE_TRUE(!mConnInfo, NS_ERROR_ALREADY_INITIALIZED); 1.133 + 1.134 + mConnInfo = info; 1.135 + mLastWriteTime = mLastReadTime = PR_IntervalNow(); 1.136 + mSupportsPipelining = 1.137 + gHttpHandler->ConnMgr()->SupportsPipelining(mConnInfo); 1.138 + mRtt = rtt; 1.139 + mMaxHangTime = PR_SecondsToInterval(maxHangTime); 1.140 + 1.141 + mSocketTransport = transport; 1.142 + mSocketIn = instream; 1.143 + mSocketOut = outstream; 1.144 + nsresult rv = mSocketTransport->SetEventSink(this, nullptr); 1.145 + NS_ENSURE_SUCCESS(rv, rv); 1.146 + 1.147 + // See explanation for non-strictness of this operation in SetSecurityCallbacks. 1.148 + mCallbacks = new nsMainThreadPtrHolder<nsIInterfaceRequestor>(callbacks, false); 1.149 + rv = mSocketTransport->SetSecurityCallbacks(this); 1.150 + NS_ENSURE_SUCCESS(rv, rv); 1.151 + 1.152 + return NS_OK; 1.153 +} 1.154 + 1.155 +void 1.156 +nsHttpConnection::StartSpdy(uint8_t spdyVersion) 1.157 +{ 1.158 + LOG(("nsHttpConnection::StartSpdy [this=%p]\n", this)); 1.159 + 1.160 + MOZ_ASSERT(!mSpdySession); 1.161 + 1.162 + mUsingSpdyVersion = spdyVersion; 1.163 + mEverUsedSpdy = true; 1.164 + 1.165 + // Setting the connection as reused allows some transactions that fail 1.166 + // with NS_ERROR_NET_RESET to be restarted and SPDY uses that code 1.167 + // to handle clean rejections (such as those that arrived after 1.168 + // a server goaway was generated). 1.169 + mIsReused = true; 1.170 + 1.171 + // If mTransaction is a pipeline object it might represent 1.172 + // several requests. If so, we need to unpack that and 1.173 + // pack them all into a new spdy session. 1.174 + 1.175 + nsTArray<nsRefPtr<nsAHttpTransaction> > list; 1.176 + nsresult rv = mTransaction->TakeSubTransactions(list); 1.177 + 1.178 + if (rv == NS_ERROR_ALREADY_OPENED) { 1.179 + // Has the interface for TakeSubTransactions() changed? 1.180 + LOG(("TakeSubTranscations somehow called after " 1.181 + "nsAHttpTransaction began processing\n")); 1.182 + MOZ_ASSERT(false, 1.183 + "TakeSubTranscations somehow called after " 1.184 + "nsAHttpTransaction began processing"); 1.185 + mTransaction->Close(NS_ERROR_ABORT); 1.186 + return; 1.187 + } 1.188 + 1.189 + if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) { 1.190 + // Has the interface for TakeSubTransactions() changed? 1.191 + LOG(("unexpected rv from nnsAHttpTransaction::TakeSubTransactions()")); 1.192 + MOZ_ASSERT(false, 1.193 + "unexpected result from " 1.194 + "nsAHttpTransaction::TakeSubTransactions()"); 1.195 + mTransaction->Close(NS_ERROR_ABORT); 1.196 + return; 1.197 + } 1.198 + 1.199 + if (NS_FAILED(rv)) { // includes NS_ERROR_NOT_IMPLEMENTED 1.200 + MOZ_ASSERT(list.IsEmpty(), "sub transaction list not empty"); 1.201 + 1.202 + // This is ok - treat mTransaction as a single real request. 1.203 + // Wrap the old http transaction into the new spdy session 1.204 + // as the first stream. 1.205 + mSpdySession = ASpdySession::NewSpdySession(spdyVersion, 1.206 + mTransaction, mSocketTransport, 1.207 + mPriority); 1.208 + LOG(("nsHttpConnection::StartSpdy moves single transaction %p " 1.209 + "into SpdySession %p\n", mTransaction.get(), mSpdySession.get())); 1.210 + } 1.211 + else { 1.212 + int32_t count = list.Length(); 1.213 + 1.214 + LOG(("nsHttpConnection::StartSpdy moving transaction list len=%d " 1.215 + "into SpdySession %p\n", count, mSpdySession.get())); 1.216 + 1.217 + if (!count) { 1.218 + mTransaction->Close(NS_ERROR_ABORT); 1.219 + return; 1.220 + } 1.221 + 1.222 + for (int32_t index = 0; index < count; ++index) { 1.223 + if (!mSpdySession) { 1.224 + mSpdySession = ASpdySession::NewSpdySession(spdyVersion, 1.225 + list[index], mSocketTransport, 1.226 + mPriority); 1.227 + } 1.228 + else { 1.229 + // AddStream() cannot fail 1.230 + if (!mSpdySession->AddStream(list[index], mPriority)) { 1.231 + MOZ_ASSERT(false, "SpdySession::AddStream failed"); 1.232 + LOG(("SpdySession::AddStream failed\n")); 1.233 + mTransaction->Close(NS_ERROR_ABORT); 1.234 + return; 1.235 + } 1.236 + } 1.237 + } 1.238 + } 1.239 + 1.240 + // Disable TCP Keepalives - use SPDY ping instead. 1.241 + rv = DisableTCPKeepalives(); 1.242 + if (NS_WARN_IF(NS_FAILED(rv))) { 1.243 + LOG(("nsHttpConnection::StartSpdy [%p] DisableTCPKeepalives failed " 1.244 + "rv[0x%x]", this, rv)); 1.245 + } 1.246 + 1.247 + mSupportsPipelining = false; // dont use http/1 pipelines with spdy 1.248 + mTransaction = mSpdySession; 1.249 + mIdleTimeout = gHttpHandler->SpdyTimeout(); 1.250 +} 1.251 + 1.252 +bool 1.253 +nsHttpConnection::EnsureNPNComplete() 1.254 +{ 1.255 + // If for some reason the components to check on NPN aren't available, 1.256 + // this function will just return true to continue on and disable SPDY 1.257 + 1.258 + MOZ_ASSERT(mSocketTransport); 1.259 + if (!mSocketTransport) { 1.260 + // this cannot happen 1.261 + mNPNComplete = true; 1.262 + return true; 1.263 + } 1.264 + 1.265 + if (mNPNComplete) 1.266 + return true; 1.267 + 1.268 + nsresult rv; 1.269 + 1.270 + nsCOMPtr<nsISupports> securityInfo; 1.271 + nsCOMPtr<nsISSLSocketControl> ssl; 1.272 + nsAutoCString negotiatedNPN; 1.273 + 1.274 + rv = mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo)); 1.275 + if (NS_FAILED(rv)) 1.276 + goto npnComplete; 1.277 + 1.278 + ssl = do_QueryInterface(securityInfo, &rv); 1.279 + if (NS_FAILED(rv)) 1.280 + goto npnComplete; 1.281 + 1.282 + rv = ssl->GetNegotiatedNPN(negotiatedNPN); 1.283 + if (rv == NS_ERROR_NOT_CONNECTED) { 1.284 + 1.285 + // By writing 0 bytes to the socket the SSL handshake machine is 1.286 + // pushed forward. 1.287 + uint32_t count = 0; 1.288 + rv = mSocketOut->Write("", 0, &count); 1.289 + 1.290 + if (NS_FAILED(rv) && rv != NS_BASE_STREAM_WOULD_BLOCK) 1.291 + goto npnComplete; 1.292 + return false; 1.293 + } 1.294 + 1.295 + if (NS_FAILED(rv)) 1.296 + goto npnComplete; 1.297 + 1.298 + LOG(("nsHttpConnection::EnsureNPNComplete %p [%s] negotiated to '%s'\n", 1.299 + this, mConnInfo->Host(), negotiatedNPN.get())); 1.300 + 1.301 + uint8_t spdyVersion; 1.302 + rv = gHttpHandler->SpdyInfo()->GetNPNVersionIndex(negotiatedNPN, 1.303 + &spdyVersion); 1.304 + if (NS_SUCCEEDED(rv)) 1.305 + StartSpdy(spdyVersion); 1.306 + 1.307 + Telemetry::Accumulate(Telemetry::SPDY_NPN_CONNECT, UsingSpdy()); 1.308 + 1.309 +npnComplete: 1.310 + LOG(("nsHttpConnection::EnsureNPNComplete setting complete to true")); 1.311 + mNPNComplete = true; 1.312 + return true; 1.313 +} 1.314 + 1.315 +// called on the socket thread 1.316 +nsresult 1.317 +nsHttpConnection::Activate(nsAHttpTransaction *trans, uint32_t caps, int32_t pri) 1.318 +{ 1.319 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.320 + LOG(("nsHttpConnection::Activate [this=%p trans=%x caps=%x]\n", 1.321 + this, trans, caps)); 1.322 + 1.323 + if (!trans->IsNullTransaction()) 1.324 + mExperienced = true; 1.325 + 1.326 + mTransactionCaps = caps; 1.327 + mPriority = pri; 1.328 + if (mTransaction && mUsingSpdyVersion) 1.329 + return AddTransaction(trans, pri); 1.330 + 1.331 + NS_ENSURE_ARG_POINTER(trans); 1.332 + NS_ENSURE_TRUE(!mTransaction, NS_ERROR_IN_PROGRESS); 1.333 + 1.334 + // reset the read timers to wash away any idle time 1.335 + mLastWriteTime = mLastReadTime = PR_IntervalNow(); 1.336 + 1.337 + // Update security callbacks 1.338 + nsCOMPtr<nsIInterfaceRequestor> callbacks; 1.339 + trans->GetSecurityCallbacks(getter_AddRefs(callbacks)); 1.340 + SetSecurityCallbacks(callbacks); 1.341 + 1.342 + SetupSSL(caps); 1.343 + 1.344 + // take ownership of the transaction 1.345 + mTransaction = trans; 1.346 + 1.347 + MOZ_ASSERT(!mIdleMonitoring, "Activating a connection with an Idle Monitor"); 1.348 + mIdleMonitoring = false; 1.349 + 1.350 + // set mKeepAlive according to what will be requested 1.351 + mKeepAliveMask = mKeepAlive = (caps & NS_HTTP_ALLOW_KEEPALIVE); 1.352 + 1.353 + // need to handle HTTP CONNECT tunnels if this is the first time if 1.354 + // we are tunneling through a proxy 1.355 + nsresult rv = NS_OK; 1.356 + if (mConnInfo->UsingConnect() && !mCompletedProxyConnect) { 1.357 + rv = SetupProxyConnect(); 1.358 + if (NS_FAILED(rv)) 1.359 + goto failed_activation; 1.360 + mProxyConnectInProgress = true; 1.361 + } 1.362 + 1.363 + // Clear the per activation counter 1.364 + mCurrentBytesRead = 0; 1.365 + 1.366 + // The overflow state is not needed between activations 1.367 + mInputOverflow = nullptr; 1.368 + 1.369 + mResponseTimeoutEnabled = gHttpHandler->ResponseTimeoutEnabled() && 1.370 + mTransaction->ResponseTimeout() > 0 && 1.371 + mTransaction->ResponseTimeoutEnabled(); 1.372 + 1.373 + rv = StartShortLivedTCPKeepalives(); 1.374 + if (NS_WARN_IF(NS_FAILED(rv))) { 1.375 + LOG(("nsHttpConnection::Activate [%p] " 1.376 + "StartShortLivedTCPKeepalives failed rv[0x%x]", 1.377 + this, rv)); 1.378 + } 1.379 + 1.380 + rv = OnOutputStreamReady(mSocketOut); 1.381 + 1.382 +failed_activation: 1.383 + if (NS_FAILED(rv)) { 1.384 + mTransaction = nullptr; 1.385 + } 1.386 + 1.387 + return rv; 1.388 +} 1.389 + 1.390 +void 1.391 +nsHttpConnection::SetupSSL(uint32_t caps) 1.392 +{ 1.393 + LOG(("nsHttpConnection::SetupSSL %p caps=0x%X\n", this, caps)); 1.394 + 1.395 + if (mSetupSSLCalled) // do only once 1.396 + return; 1.397 + mSetupSSLCalled = true; 1.398 + 1.399 + if (mNPNComplete) 1.400 + return; 1.401 + 1.402 + // we flip this back to false if SetNPNList succeeds at the end 1.403 + // of this function 1.404 + mNPNComplete = true; 1.405 + 1.406 + if (!mConnInfo->UsingSSL()) 1.407 + return; 1.408 + 1.409 + LOG(("nsHttpConnection::SetupSSL Setting up " 1.410 + "Next Protocol Negotiation")); 1.411 + nsCOMPtr<nsISupports> securityInfo; 1.412 + nsresult rv = 1.413 + mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo)); 1.414 + if (NS_FAILED(rv)) 1.415 + return; 1.416 + 1.417 + nsCOMPtr<nsISSLSocketControl> ssl = do_QueryInterface(securityInfo, &rv); 1.418 + if (NS_FAILED(rv)) 1.419 + return; 1.420 + 1.421 + if (caps & NS_HTTP_ALLOW_RSA_FALSESTART) { 1.422 + LOG(("nsHttpConnection::SetupSSL %p " 1.423 + ">= RSA Key Exchange Expected\n", this)); 1.424 + ssl->SetKEAExpected(ssl_kea_rsa); 1.425 + } 1.426 + 1.427 + nsTArray<nsCString> protocolArray; 1.428 + 1.429 + // The first protocol is used as the fallback if none of the 1.430 + // protocols supported overlap with the server's list. 1.431 + // In the case of overlap, matching priority is driven by 1.432 + // the order of the server's advertisement. 1.433 + protocolArray.AppendElement(NS_LITERAL_CSTRING("http/1.1")); 1.434 + 1.435 + if (gHttpHandler->IsSpdyEnabled() && 1.436 + !(caps & NS_HTTP_DISALLOW_SPDY)) { 1.437 + LOG(("nsHttpConnection::SetupSSL Allow SPDY NPN selection")); 1.438 + for (uint32_t index = 0; index < SpdyInformation::kCount; ++index) { 1.439 + if (gHttpHandler->SpdyInfo()->ProtocolEnabled(index)) 1.440 + protocolArray.AppendElement( 1.441 + gHttpHandler->SpdyInfo()->VersionString[index]); 1.442 + } 1.443 + } 1.444 + 1.445 + if (NS_SUCCEEDED(ssl->SetNPNList(protocolArray))) { 1.446 + LOG(("nsHttpConnection::Init Setting up SPDY Negotiation OK")); 1.447 + mNPNComplete = false; 1.448 + } 1.449 +} 1.450 + 1.451 +nsresult 1.452 +nsHttpConnection::AddTransaction(nsAHttpTransaction *httpTransaction, 1.453 + int32_t priority) 1.454 +{ 1.455 + LOG(("nsHttpConnection::AddTransaction for SPDY")); 1.456 + 1.457 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.458 + MOZ_ASSERT(mSpdySession && mUsingSpdyVersion, 1.459 + "AddTransaction to live http connection without spdy"); 1.460 + MOZ_ASSERT(mTransaction, 1.461 + "AddTransaction to idle http connection"); 1.462 + 1.463 + if (!mSpdySession->AddStream(httpTransaction, priority)) { 1.464 + MOZ_ASSERT(false, "AddStream should never fail due to" 1.465 + "RoomForMore() admission check"); 1.466 + return NS_ERROR_FAILURE; 1.467 + } 1.468 + 1.469 + ResumeSend(); 1.470 + 1.471 + return NS_OK; 1.472 +} 1.473 + 1.474 +void 1.475 +nsHttpConnection::Close(nsresult reason) 1.476 +{ 1.477 + LOG(("nsHttpConnection::Close [this=%p reason=%x]\n", this, reason)); 1.478 + 1.479 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.480 + 1.481 + // Ensure TCP keepalive timer is stopped. 1.482 + if (mTCPKeepaliveTransitionTimer) { 1.483 + mTCPKeepaliveTransitionTimer->Cancel(); 1.484 + mTCPKeepaliveTransitionTimer = nullptr; 1.485 + } 1.486 + 1.487 + if (NS_FAILED(reason)) { 1.488 + if (mIdleMonitoring) 1.489 + EndIdleMonitoring(); 1.490 + 1.491 + if (mSocketTransport) { 1.492 + mSocketTransport->SetEventSink(nullptr, nullptr); 1.493 + 1.494 + // If there are bytes sitting in the input queue then read them 1.495 + // into a junk buffer to avoid generating a tcp rst by closing a 1.496 + // socket with data pending. TLS is a classic case of this where 1.497 + // a Alert record might be superfulous to a clean HTTP/SPDY shutdown. 1.498 + // Never block to do this and limit it to a small amount of data. 1.499 + if (mSocketIn) { 1.500 + char buffer[4000]; 1.501 + uint32_t count, total = 0; 1.502 + nsresult rv; 1.503 + do { 1.504 + rv = mSocketIn->Read(buffer, 4000, &count); 1.505 + if (NS_SUCCEEDED(rv)) 1.506 + total += count; 1.507 + } 1.508 + while (NS_SUCCEEDED(rv) && count > 0 && total < 64000); 1.509 + LOG(("nsHttpConnection::Close drained %d bytes\n", total)); 1.510 + } 1.511 + 1.512 + mSocketTransport->SetSecurityCallbacks(nullptr); 1.513 + mSocketTransport->Close(reason); 1.514 + if (mSocketOut) 1.515 + mSocketOut->AsyncWait(nullptr, 0, 0, nullptr); 1.516 + } 1.517 + mKeepAlive = false; 1.518 + } 1.519 +} 1.520 + 1.521 +// called on the socket thread 1.522 +nsresult 1.523 +nsHttpConnection::ProxyStartSSL() 1.524 +{ 1.525 + LOG(("nsHttpConnection::ProxyStartSSL [this=%p]\n", this)); 1.526 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.527 + 1.528 + nsCOMPtr<nsISupports> securityInfo; 1.529 + nsresult rv = mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo)); 1.530 + if (NS_FAILED(rv)) return rv; 1.531 + 1.532 + nsCOMPtr<nsISSLSocketControl> ssl = do_QueryInterface(securityInfo, &rv); 1.533 + if (NS_FAILED(rv)) return rv; 1.534 + 1.535 + return ssl->ProxyStartSSL(); 1.536 +} 1.537 + 1.538 +void 1.539 +nsHttpConnection::DontReuse() 1.540 +{ 1.541 + mKeepAliveMask = false; 1.542 + mKeepAlive = false; 1.543 + mDontReuse = true; 1.544 + mIdleTimeout = 0; 1.545 + if (mSpdySession) 1.546 + mSpdySession->DontReuse(); 1.547 +} 1.548 + 1.549 +// Checked by the Connection Manager before scheduling a pipelined transaction 1.550 +bool 1.551 +nsHttpConnection::SupportsPipelining() 1.552 +{ 1.553 + if (mTransaction && 1.554 + mTransaction->PipelineDepth() >= mRemainingConnectionUses) { 1.555 + LOG(("nsHttpConnection::SupportsPipelining this=%p deny pipeline " 1.556 + "because current depth %d exceeds max remaining uses %d\n", 1.557 + this, mTransaction->PipelineDepth(), mRemainingConnectionUses)); 1.558 + return false; 1.559 + } 1.560 + return mSupportsPipelining && IsKeepAlive() && !mDontReuse; 1.561 +} 1.562 + 1.563 +bool 1.564 +nsHttpConnection::CanReuse() 1.565 +{ 1.566 + if (mDontReuse) 1.567 + return false; 1.568 + 1.569 + if ((mTransaction ? mTransaction->PipelineDepth() : 0) >= 1.570 + mRemainingConnectionUses) { 1.571 + return false; 1.572 + } 1.573 + 1.574 + bool canReuse; 1.575 + 1.576 + if (mSpdySession) 1.577 + canReuse = mSpdySession->CanReuse(); 1.578 + else 1.579 + canReuse = IsKeepAlive(); 1.580 + 1.581 + canReuse = canReuse && (IdleTime() < mIdleTimeout) && IsAlive(); 1.582 + 1.583 + // An idle persistent connection should not have data waiting to be read 1.584 + // before a request is sent. Data here is likely a 408 timeout response 1.585 + // which we would deal with later on through the restart logic, but that 1.586 + // path is more expensive than just closing the socket now. 1.587 + 1.588 + uint64_t dataSize; 1.589 + if (canReuse && mSocketIn && !mUsingSpdyVersion && mHttp1xTransactionCount && 1.590 + NS_SUCCEEDED(mSocketIn->Available(&dataSize)) && dataSize) { 1.591 + LOG(("nsHttpConnection::CanReuse %p %s" 1.592 + "Socket not reusable because read data pending (%llu) on it.\n", 1.593 + this, mConnInfo->Host(), dataSize)); 1.594 + canReuse = false; 1.595 + } 1.596 + return canReuse; 1.597 +} 1.598 + 1.599 +bool 1.600 +nsHttpConnection::CanDirectlyActivate() 1.601 +{ 1.602 + // return true if a new transaction can be addded to ths connection at any 1.603 + // time through Activate(). In practice this means this is a healthy SPDY 1.604 + // connection with room for more concurrent streams. 1.605 + 1.606 + return UsingSpdy() && CanReuse() && 1.607 + mSpdySession && mSpdySession->RoomForMoreStreams(); 1.608 +} 1.609 + 1.610 +PRIntervalTime 1.611 +nsHttpConnection::IdleTime() 1.612 +{ 1.613 + return mSpdySession ? 1.614 + mSpdySession->IdleTime() : (PR_IntervalNow() - mLastReadTime); 1.615 +} 1.616 + 1.617 +// returns the number of seconds left before the allowable idle period 1.618 +// expires, or 0 if the period has already expied. 1.619 +uint32_t 1.620 +nsHttpConnection::TimeToLive() 1.621 +{ 1.622 + if (IdleTime() >= mIdleTimeout) 1.623 + return 0; 1.624 + uint32_t timeToLive = PR_IntervalToSeconds(mIdleTimeout - IdleTime()); 1.625 + 1.626 + // a positive amount of time can be rounded to 0. Because 0 is used 1.627 + // as the expiration signal, round all values from 0 to 1 up to 1. 1.628 + if (!timeToLive) 1.629 + timeToLive = 1; 1.630 + return timeToLive; 1.631 +} 1.632 + 1.633 +bool 1.634 +nsHttpConnection::IsAlive() 1.635 +{ 1.636 + if (!mSocketTransport) 1.637 + return false; 1.638 + 1.639 + // SocketTransport::IsAlive can run the SSL state machine, so make sure 1.640 + // the NPN options are set before that happens. 1.641 + SetupSSL(mTransactionCaps); 1.642 + 1.643 + bool alive; 1.644 + nsresult rv = mSocketTransport->IsAlive(&alive); 1.645 + if (NS_FAILED(rv)) 1.646 + alive = false; 1.647 + 1.648 +//#define TEST_RESTART_LOGIC 1.649 +#ifdef TEST_RESTART_LOGIC 1.650 + if (!alive) { 1.651 + LOG(("pretending socket is still alive to test restart logic\n")); 1.652 + alive = true; 1.653 + } 1.654 +#endif 1.655 + 1.656 + return alive; 1.657 +} 1.658 + 1.659 +bool 1.660 +nsHttpConnection::SupportsPipelining(nsHttpResponseHead *responseHead) 1.661 +{ 1.662 + // SPDY supports infinite parallelism, so no need to pipeline. 1.663 + if (mUsingSpdyVersion) 1.664 + return false; 1.665 + 1.666 + // assuming connection is HTTP/1.1 with keep-alive enabled 1.667 + if (mConnInfo->UsingHttpProxy() && !mConnInfo->UsingConnect()) { 1.668 + // XXX check for bad proxy servers... 1.669 + return true; 1.670 + } 1.671 + 1.672 + // check for bad origin servers 1.673 + const char *val = responseHead->PeekHeader(nsHttp::Server); 1.674 + 1.675 + // If there is no server header we will assume it should not be banned 1.676 + // as facebook and some other prominent sites do this 1.677 + if (!val) 1.678 + return true; 1.679 + 1.680 + // The blacklist is indexed by the first character. All of these servers are 1.681 + // known to return their identifier as the first thing in the server string, 1.682 + // so we can do a leading match. 1.683 + 1.684 + static const char *bad_servers[26][6] = { 1.685 + { nullptr }, { nullptr }, { nullptr }, { nullptr }, // a - d 1.686 + { "EFAServer/", nullptr }, // e 1.687 + { nullptr }, { nullptr }, { nullptr }, { nullptr }, // f - i 1.688 + { nullptr }, { nullptr }, { nullptr }, // j - l 1.689 + { "Microsoft-IIS/4.", "Microsoft-IIS/5.", nullptr }, // m 1.690 + { "Netscape-Enterprise/3.", "Netscape-Enterprise/4.", 1.691 + "Netscape-Enterprise/5.", "Netscape-Enterprise/6.", nullptr }, // n 1.692 + { nullptr }, { nullptr }, { nullptr }, { nullptr }, // o - r 1.693 + { nullptr }, { nullptr }, { nullptr }, { nullptr }, // s - v 1.694 + { "WebLogic 3.", "WebLogic 4.","WebLogic 5.", "WebLogic 6.", 1.695 + "Winstone Servlet Engine v0.", nullptr }, // w 1.696 + { nullptr }, { nullptr }, { nullptr } // x - z 1.697 + }; 1.698 + 1.699 + int index = val[0] - 'A'; // the whole table begins with capital letters 1.700 + if ((index >= 0) && (index <= 25)) 1.701 + { 1.702 + for (int i = 0; bad_servers[index][i] != nullptr; i++) { 1.703 + if (!PL_strncmp (val, bad_servers[index][i], strlen (bad_servers[index][i]))) { 1.704 + LOG(("looks like this server does not support pipelining")); 1.705 + gHttpHandler->ConnMgr()->PipelineFeedbackInfo( 1.706 + mConnInfo, nsHttpConnectionMgr::RedBannedServer, this , 0); 1.707 + return false; 1.708 + } 1.709 + } 1.710 + } 1.711 + 1.712 + // ok, let's allow pipelining to this server 1.713 + return true; 1.714 +} 1.715 + 1.716 +//---------------------------------------------------------------------------- 1.717 +// nsHttpConnection::nsAHttpConnection compatible methods 1.718 +//---------------------------------------------------------------------------- 1.719 + 1.720 +nsresult 1.721 +nsHttpConnection::OnHeadersAvailable(nsAHttpTransaction *trans, 1.722 + nsHttpRequestHead *requestHead, 1.723 + nsHttpResponseHead *responseHead, 1.724 + bool *reset) 1.725 +{ 1.726 + LOG(("nsHttpConnection::OnHeadersAvailable [this=%p trans=%p response-head=%p]\n", 1.727 + this, trans, responseHead)); 1.728 + 1.729 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.730 + NS_ENSURE_ARG_POINTER(trans); 1.731 + MOZ_ASSERT(responseHead, "No response head?"); 1.732 + 1.733 + // we won't change our keep-alive policy unless the server has explicitly 1.734 + // told us to do so. 1.735 + 1.736 + // inspect the connection headers for keep-alive info provided the 1.737 + // transaction completed successfully. In the case of a non-sensical close 1.738 + // and keep-alive favor the close out of conservatism. 1.739 + 1.740 + bool explicitKeepAlive = false; 1.741 + bool explicitClose = responseHead->HasHeaderValue(nsHttp::Connection, "close") || 1.742 + responseHead->HasHeaderValue(nsHttp::Proxy_Connection, "close"); 1.743 + if (!explicitClose) 1.744 + explicitKeepAlive = responseHead->HasHeaderValue(nsHttp::Connection, "keep-alive") || 1.745 + responseHead->HasHeaderValue(nsHttp::Proxy_Connection, "keep-alive"); 1.746 + 1.747 + // deal with 408 Server Timeouts 1.748 + uint16_t responseStatus = responseHead->Status(); 1.749 + static const PRIntervalTime k1000ms = PR_MillisecondsToInterval(1000); 1.750 + if (responseStatus == 408) { 1.751 + // If this error could be due to a persistent connection reuse then 1.752 + // we pass an error code of NS_ERROR_NET_RESET to 1.753 + // trigger the transaction 'restart' mechanism. We tell it to reset its 1.754 + // response headers so that it will be ready to receive the new response. 1.755 + if (mIsReused && ((PR_IntervalNow() - mLastWriteTime) < k1000ms)) { 1.756 + Close(NS_ERROR_NET_RESET); 1.757 + *reset = true; 1.758 + return NS_OK; 1.759 + } 1.760 + 1.761 + // timeouts that are not caused by persistent connection reuse should 1.762 + // not be retried for browser compatibility reasons. bug 907800. The 1.763 + // server driven close is implicit in the 408. 1.764 + explicitClose = true; 1.765 + explicitKeepAlive = false; 1.766 + } 1.767 + 1.768 + // reset to default (the server may have changed since we last checked) 1.769 + mSupportsPipelining = false; 1.770 + 1.771 + if ((responseHead->Version() < NS_HTTP_VERSION_1_1) || 1.772 + (requestHead->Version() < NS_HTTP_VERSION_1_1)) { 1.773 + // HTTP/1.0 connections are by default NOT persistent 1.774 + if (explicitKeepAlive) 1.775 + mKeepAlive = true; 1.776 + else 1.777 + mKeepAlive = false; 1.778 + 1.779 + // We need at least version 1.1 to use pipelines 1.780 + gHttpHandler->ConnMgr()->PipelineFeedbackInfo( 1.781 + mConnInfo, nsHttpConnectionMgr::RedVersionTooLow, this, 0); 1.782 + } 1.783 + else { 1.784 + // HTTP/1.1 connections are by default persistent 1.785 + if (explicitClose) { 1.786 + mKeepAlive = false; 1.787 + 1.788 + // persistent connections are required for pipelining to work - if 1.789 + // this close was not pre-announced then generate the negative 1.790 + // BadExplicitClose feedback 1.791 + if (mRemainingConnectionUses > 1) 1.792 + gHttpHandler->ConnMgr()->PipelineFeedbackInfo( 1.793 + mConnInfo, nsHttpConnectionMgr::BadExplicitClose, this, 0); 1.794 + } 1.795 + else { 1.796 + mKeepAlive = true; 1.797 + 1.798 + // Do not support pipelining when we are establishing 1.799 + // an SSL tunnel though an HTTP proxy. Pipelining support 1.800 + // determination must be based on comunication with the 1.801 + // target server in this case. See bug 422016 for futher 1.802 + // details. 1.803 + if (!mProxyConnectStream) 1.804 + mSupportsPipelining = SupportsPipelining(responseHead); 1.805 + } 1.806 + } 1.807 + mKeepAliveMask = mKeepAlive; 1.808 + 1.809 + // Update the pipelining status in the connection info object 1.810 + // and also read it back. It is possible the ci status is 1.811 + // locked to false if pipelining has been banned on this ci due to 1.812 + // some kind of observed flaky behavior 1.813 + if (mSupportsPipelining) { 1.814 + // report the pipelining-compatible header to the connection manager 1.815 + // as positive feedback. This will undo 1 penalty point the host 1.816 + // may have accumulated in the past. 1.817 + 1.818 + gHttpHandler->ConnMgr()->PipelineFeedbackInfo( 1.819 + mConnInfo, nsHttpConnectionMgr::NeutralExpectedOK, this, 0); 1.820 + 1.821 + mSupportsPipelining = 1.822 + gHttpHandler->ConnMgr()->SupportsPipelining(mConnInfo); 1.823 + } 1.824 + 1.825 + // If this connection is reserved for revalidations and we are 1.826 + // receiving a document that failed revalidation then switch the 1.827 + // classification to general to avoid pipelining more revalidations behind 1.828 + // it. 1.829 + if (mClassification == nsAHttpTransaction::CLASS_REVALIDATION && 1.830 + responseStatus != 304) { 1.831 + mClassification = nsAHttpTransaction::CLASS_GENERAL; 1.832 + } 1.833 + 1.834 + // if this connection is persistent, then the server may send a "Keep-Alive" 1.835 + // header specifying the maximum number of times the connection can be 1.836 + // reused as well as the maximum amount of time the connection can be idle 1.837 + // before the server will close it. we ignore the max reuse count, because 1.838 + // a "keep-alive" connection is by definition capable of being reused, and 1.839 + // we only care about being able to reuse it once. if a timeout is not 1.840 + // specified then we use our advertized timeout value. 1.841 + bool foundKeepAliveMax = false; 1.842 + if (mKeepAlive) { 1.843 + const char *val = responseHead->PeekHeader(nsHttp::Keep_Alive); 1.844 + 1.845 + if (!mUsingSpdyVersion) { 1.846 + const char *cp = PL_strcasestr(val, "timeout="); 1.847 + if (cp) 1.848 + mIdleTimeout = PR_SecondsToInterval((uint32_t) atoi(cp + 8)); 1.849 + else 1.850 + mIdleTimeout = gHttpHandler->IdleTimeout(); 1.851 + 1.852 + cp = PL_strcasestr(val, "max="); 1.853 + if (cp) { 1.854 + int val = atoi(cp + 4); 1.855 + if (val > 0) { 1.856 + foundKeepAliveMax = true; 1.857 + mRemainingConnectionUses = static_cast<uint32_t>(val); 1.858 + } 1.859 + } 1.860 + } 1.861 + else { 1.862 + mIdleTimeout = gHttpHandler->SpdyTimeout(); 1.863 + } 1.864 + 1.865 + LOG(("Connection can be reused [this=%p idle-timeout=%usec]\n", 1.866 + this, PR_IntervalToSeconds(mIdleTimeout))); 1.867 + } 1.868 + 1.869 + if (!foundKeepAliveMax && mRemainingConnectionUses && !mUsingSpdyVersion) 1.870 + --mRemainingConnectionUses; 1.871 + 1.872 + // If we're doing a proxy connect, we need to check whether or not 1.873 + // it was successful. If so, we have to reset the transaction and step-up 1.874 + // the socket connection if using SSL. Finally, we have to wake up the 1.875 + // socket write request. 1.876 + if (mProxyConnectStream) { 1.877 + MOZ_ASSERT(!mUsingSpdyVersion, 1.878 + "SPDY NPN Complete while using proxy connect stream"); 1.879 + mProxyConnectStream = 0; 1.880 + if (responseStatus == 200) { 1.881 + LOG(("proxy CONNECT succeeded! ssl=%s\n", 1.882 + mConnInfo->UsingSSL() ? "true" :"false")); 1.883 + *reset = true; 1.884 + nsresult rv; 1.885 + if (mConnInfo->UsingSSL()) { 1.886 + rv = ProxyStartSSL(); 1.887 + if (NS_FAILED(rv)) // XXX need to handle this for real 1.888 + LOG(("ProxyStartSSL failed [rv=%x]\n", rv)); 1.889 + } 1.890 + mCompletedProxyConnect = true; 1.891 + mProxyConnectInProgress = false; 1.892 + rv = mSocketOut->AsyncWait(this, 0, 0, nullptr); 1.893 + // XXX what if this fails -- need to handle this error 1.894 + MOZ_ASSERT(NS_SUCCEEDED(rv), "mSocketOut->AsyncWait failed"); 1.895 + } 1.896 + else { 1.897 + LOG(("proxy CONNECT failed! ssl=%s\n", 1.898 + mConnInfo->UsingSSL() ? "true" :"false")); 1.899 + mTransaction->SetProxyConnectFailed(); 1.900 + } 1.901 + } 1.902 + 1.903 + const char *upgradeReq = requestHead->PeekHeader(nsHttp::Upgrade); 1.904 + // Don't use persistent connection for Upgrade unless there's an auth failure: 1.905 + // some proxies expect to see auth response on persistent connection. 1.906 + if (upgradeReq && responseStatus != 401 && responseStatus != 407) { 1.907 + LOG(("HTTP Upgrade in play - disable keepalive\n")); 1.908 + DontReuse(); 1.909 + } 1.910 + 1.911 + if (responseStatus == 101) { 1.912 + const char *upgradeResp = responseHead->PeekHeader(nsHttp::Upgrade); 1.913 + if (!upgradeReq || !upgradeResp || 1.914 + !nsHttp::FindToken(upgradeResp, upgradeReq, 1.915 + HTTP_HEADER_VALUE_SEPS)) { 1.916 + LOG(("HTTP 101 Upgrade header mismatch req = %s, resp = %s\n", 1.917 + upgradeReq, upgradeResp)); 1.918 + Close(NS_ERROR_ABORT); 1.919 + } 1.920 + else { 1.921 + LOG(("HTTP Upgrade Response to %s\n", upgradeResp)); 1.922 + } 1.923 + } 1.924 + 1.925 + mLastHttpResponseVersion = responseHead->Version(); 1.926 + 1.927 + return NS_OK; 1.928 +} 1.929 + 1.930 +bool 1.931 +nsHttpConnection::IsReused() 1.932 +{ 1.933 + if (mIsReused) 1.934 + return true; 1.935 + if (!mConsiderReusedAfterInterval) 1.936 + return false; 1.937 + 1.938 + // ReusedAfter allows a socket to be consider reused only after a certain 1.939 + // interval of time has passed 1.940 + return (PR_IntervalNow() - mConsiderReusedAfterEpoch) >= 1.941 + mConsiderReusedAfterInterval; 1.942 +} 1.943 + 1.944 +void 1.945 +nsHttpConnection::SetIsReusedAfter(uint32_t afterMilliseconds) 1.946 +{ 1.947 + mConsiderReusedAfterEpoch = PR_IntervalNow(); 1.948 + mConsiderReusedAfterInterval = PR_MillisecondsToInterval(afterMilliseconds); 1.949 +} 1.950 + 1.951 +nsresult 1.952 +nsHttpConnection::TakeTransport(nsISocketTransport **aTransport, 1.953 + nsIAsyncInputStream **aInputStream, 1.954 + nsIAsyncOutputStream **aOutputStream) 1.955 +{ 1.956 + if (mUsingSpdyVersion) 1.957 + return NS_ERROR_FAILURE; 1.958 + if (mTransaction && !mTransaction->IsDone()) 1.959 + return NS_ERROR_IN_PROGRESS; 1.960 + if (!(mSocketTransport && mSocketIn && mSocketOut)) 1.961 + return NS_ERROR_NOT_INITIALIZED; 1.962 + 1.963 + if (mInputOverflow) 1.964 + mSocketIn = mInputOverflow.forget(); 1.965 + 1.966 + // Change TCP Keepalive frequency to long-lived if currently short-lived. 1.967 + if (mTCPKeepaliveConfig == kTCPKeepaliveShortLivedConfig) { 1.968 + if (mTCPKeepaliveTransitionTimer) { 1.969 + mTCPKeepaliveTransitionTimer->Cancel(); 1.970 + mTCPKeepaliveTransitionTimer = nullptr; 1.971 + } 1.972 + nsresult rv = StartLongLivedTCPKeepalives(); 1.973 + LOG(("nsHttpConnection::TakeTransport [%p] calling " 1.974 + "StartLongLivedTCPKeepalives", this)); 1.975 + if (NS_WARN_IF(NS_FAILED(rv))) { 1.976 + LOG(("nsHttpConnection::TakeTransport [%p] " 1.977 + "StartLongLivedTCPKeepalives failed rv[0x%x]", this, rv)); 1.978 + } 1.979 + } 1.980 + 1.981 + NS_IF_ADDREF(*aTransport = mSocketTransport); 1.982 + NS_IF_ADDREF(*aInputStream = mSocketIn); 1.983 + NS_IF_ADDREF(*aOutputStream = mSocketOut); 1.984 + 1.985 + mSocketTransport->SetSecurityCallbacks(nullptr); 1.986 + mSocketTransport->SetEventSink(nullptr, nullptr); 1.987 + mSocketTransport = nullptr; 1.988 + mSocketIn = nullptr; 1.989 + mSocketOut = nullptr; 1.990 + 1.991 + return NS_OK; 1.992 +} 1.993 + 1.994 +uint32_t 1.995 +nsHttpConnection::ReadTimeoutTick(PRIntervalTime now) 1.996 +{ 1.997 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.998 + 1.999 + // make sure timer didn't tick before Activate() 1.1000 + if (!mTransaction) 1.1001 + return UINT32_MAX; 1.1002 + 1.1003 + // Spdy implements some timeout handling using the SPDY ping frame. 1.1004 + if (mSpdySession) { 1.1005 + return mSpdySession->ReadTimeoutTick(now); 1.1006 + } 1.1007 + 1.1008 + uint32_t nextTickAfter = UINT32_MAX; 1.1009 + // Timeout if the response is taking too long to arrive. 1.1010 + if (mResponseTimeoutEnabled) { 1.1011 + NS_WARN_IF_FALSE(gHttpHandler->ResponseTimeoutEnabled(), 1.1012 + "Timing out a response, but response timeout is disabled!"); 1.1013 + 1.1014 + PRIntervalTime initialResponseDelta = now - mLastWriteTime; 1.1015 + 1.1016 + if (initialResponseDelta > mTransaction->ResponseTimeout()) { 1.1017 + LOG(("canceling transaction: no response for %ums: timeout is %dms\n", 1.1018 + PR_IntervalToMilliseconds(initialResponseDelta), 1.1019 + PR_IntervalToMilliseconds(mTransaction->ResponseTimeout()))); 1.1020 + 1.1021 + mResponseTimeoutEnabled = false; 1.1022 + 1.1023 + // This will also close the connection 1.1024 + CloseTransaction(mTransaction, NS_ERROR_NET_TIMEOUT); 1.1025 + return UINT32_MAX; 1.1026 + } 1.1027 + nextTickAfter = PR_IntervalToSeconds(mTransaction->ResponseTimeout()) - 1.1028 + PR_IntervalToSeconds(initialResponseDelta); 1.1029 + nextTickAfter = std::max(nextTickAfter, 1U); 1.1030 + } 1.1031 + 1.1032 + if (!gHttpHandler->GetPipelineRescheduleOnTimeout()) 1.1033 + return nextTickAfter; 1.1034 + 1.1035 + PRIntervalTime delta = now - mLastReadTime; 1.1036 + 1.1037 + // we replicate some of the checks both here and in OnSocketReadable() as 1.1038 + // they will be discovered under different conditions. The ones here 1.1039 + // will generally be discovered if we are totally hung and OSR does 1.1040 + // not get called at all, however OSR discovers them with lower latency 1.1041 + // if the issue is just very slow (but not stalled) reading. 1.1042 + // 1.1043 + // Right now we only take action if pipelining is involved, but this would 1.1044 + // be the place to add general read timeout handling if it is desired. 1.1045 + 1.1046 + uint32_t pipelineDepth = mTransaction->PipelineDepth(); 1.1047 + if (pipelineDepth > 1) { 1.1048 + // if we have pipelines outstanding (not just an idle connection) 1.1049 + // then get a fairly quick tick 1.1050 + nextTickAfter = 1; 1.1051 + } 1.1052 + 1.1053 + if (delta >= gHttpHandler->GetPipelineRescheduleTimeout() && 1.1054 + pipelineDepth > 1) { 1.1055 + 1.1056 + // this just reschedules blocked transactions. no transaction 1.1057 + // is aborted completely. 1.1058 + LOG(("cancelling pipeline due to a %ums stall - depth %d\n", 1.1059 + PR_IntervalToMilliseconds(delta), pipelineDepth)); 1.1060 + 1.1061 + nsHttpPipeline *pipeline = mTransaction->QueryPipeline(); 1.1062 + MOZ_ASSERT(pipeline, "pipelinedepth > 1 without pipeline"); 1.1063 + // code this defensively for the moment and check for null in opt build 1.1064 + // This will reschedule blocked members of the pipeline, but the 1.1065 + // blocking transaction (i.e. response 0) will not be changed. 1.1066 + if (pipeline) { 1.1067 + pipeline->CancelPipeline(NS_ERROR_NET_TIMEOUT); 1.1068 + LOG(("Rescheduling the head of line blocked members of a pipeline " 1.1069 + "because reschedule-timeout idle interval exceeded")); 1.1070 + } 1.1071 + } 1.1072 + 1.1073 + if (delta < gHttpHandler->GetPipelineTimeout()) 1.1074 + return nextTickAfter; 1.1075 + 1.1076 + if (pipelineDepth <= 1 && !mTransaction->PipelinePosition()) 1.1077 + return nextTickAfter; 1.1078 + 1.1079 + // nothing has transpired on this pipelined socket for many 1.1080 + // seconds. Call that a total stall and close the transaction. 1.1081 + // There is a chance the transaction will be restarted again 1.1082 + // depending on its state.. that will come back araound 1.1083 + // without pipelining on, so this won't loop. 1.1084 + 1.1085 + LOG(("canceling transaction stalled for %ums on a pipeline " 1.1086 + "of depth %d and scheduled originally at pos %d\n", 1.1087 + PR_IntervalToMilliseconds(delta), 1.1088 + pipelineDepth, mTransaction->PipelinePosition())); 1.1089 + 1.1090 + // This will also close the connection 1.1091 + CloseTransaction(mTransaction, NS_ERROR_NET_TIMEOUT); 1.1092 + return UINT32_MAX; 1.1093 +} 1.1094 + 1.1095 +void 1.1096 +nsHttpConnection::UpdateTCPKeepalive(nsITimer *aTimer, void *aClosure) 1.1097 +{ 1.1098 + MOZ_ASSERT(aTimer); 1.1099 + MOZ_ASSERT(aClosure); 1.1100 + 1.1101 + nsHttpConnection *self = static_cast<nsHttpConnection*>(aClosure); 1.1102 + 1.1103 + if (NS_WARN_IF(self->mUsingSpdyVersion)) { 1.1104 + return; 1.1105 + } 1.1106 + 1.1107 + // Do not reduce keepalive probe frequency for idle connections. 1.1108 + if (self->mIdleMonitoring) { 1.1109 + return; 1.1110 + } 1.1111 + 1.1112 + nsresult rv = self->StartLongLivedTCPKeepalives(); 1.1113 + if (NS_WARN_IF(NS_FAILED(rv))) { 1.1114 + LOG(("nsHttpConnection::UpdateTCPKeepalive [%p] " 1.1115 + "StartLongLivedTCPKeepalives failed rv[0x%x]", 1.1116 + self, rv)); 1.1117 + } 1.1118 +} 1.1119 + 1.1120 +void 1.1121 +nsHttpConnection::GetSecurityInfo(nsISupports **secinfo) 1.1122 +{ 1.1123 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.1124 + 1.1125 + if (mSocketTransport) { 1.1126 + if (NS_FAILED(mSocketTransport->GetSecurityInfo(secinfo))) 1.1127 + *secinfo = nullptr; 1.1128 + } 1.1129 +} 1.1130 + 1.1131 +void 1.1132 +nsHttpConnection::SetSecurityCallbacks(nsIInterfaceRequestor* aCallbacks) 1.1133 +{ 1.1134 + MutexAutoLock lock(mCallbacksLock); 1.1135 + // This is called both on and off the main thread. For JS-implemented 1.1136 + // callbacks, we requires that the call happen on the main thread, but 1.1137 + // for C++-implemented callbacks we don't care. Use a pointer holder with 1.1138 + // strict checking disabled. 1.1139 + mCallbacks = new nsMainThreadPtrHolder<nsIInterfaceRequestor>(aCallbacks, false); 1.1140 +} 1.1141 + 1.1142 +nsresult 1.1143 +nsHttpConnection::PushBack(const char *data, uint32_t length) 1.1144 +{ 1.1145 + LOG(("nsHttpConnection::PushBack [this=%p, length=%d]\n", this, length)); 1.1146 + 1.1147 + if (mInputOverflow) { 1.1148 + NS_ERROR("nsHttpConnection::PushBack only one buffer supported"); 1.1149 + return NS_ERROR_UNEXPECTED; 1.1150 + } 1.1151 + 1.1152 + mInputOverflow = new nsPreloadedStream(mSocketIn, data, length); 1.1153 + return NS_OK; 1.1154 +} 1.1155 + 1.1156 +nsresult 1.1157 +nsHttpConnection::ResumeSend() 1.1158 +{ 1.1159 + LOG(("nsHttpConnection::ResumeSend [this=%p]\n", this)); 1.1160 + 1.1161 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.1162 + 1.1163 + if (mSocketOut) 1.1164 + return mSocketOut->AsyncWait(this, 0, 0, nullptr); 1.1165 + 1.1166 + NS_NOTREACHED("no socket output stream"); 1.1167 + return NS_ERROR_UNEXPECTED; 1.1168 +} 1.1169 + 1.1170 +nsresult 1.1171 +nsHttpConnection::ResumeRecv() 1.1172 +{ 1.1173 + LOG(("nsHttpConnection::ResumeRecv [this=%p]\n", this)); 1.1174 + 1.1175 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.1176 + 1.1177 + // the mLastReadTime timestamp is used for finding slowish readers 1.1178 + // and can be pretty sensitive. For that reason we actually reset it 1.1179 + // when we ask to read (resume recv()) so that when we get called back 1.1180 + // with actual read data in OnSocketReadable() we are only measuring 1.1181 + // the latency between those two acts and not all the processing that 1.1182 + // may get done before the ResumeRecv() call 1.1183 + mLastReadTime = PR_IntervalNow(); 1.1184 + 1.1185 + if (mSocketIn) 1.1186 + return mSocketIn->AsyncWait(this, 0, 0, nullptr); 1.1187 + 1.1188 + NS_NOTREACHED("no socket input stream"); 1.1189 + return NS_ERROR_UNEXPECTED; 1.1190 +} 1.1191 + 1.1192 + 1.1193 +class nsHttpConnectionForceRecv : public nsRunnable 1.1194 +{ 1.1195 +public: 1.1196 + nsHttpConnectionForceRecv(nsHttpConnection *aConn) 1.1197 + : mConn(aConn) {} 1.1198 + 1.1199 + NS_IMETHOD Run() 1.1200 + { 1.1201 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.1202 + 1.1203 + if (!mConn->mSocketIn) 1.1204 + return NS_OK; 1.1205 + return mConn->OnInputStreamReady(mConn->mSocketIn); 1.1206 + } 1.1207 +private: 1.1208 + nsRefPtr<nsHttpConnection> mConn; 1.1209 +}; 1.1210 + 1.1211 +// trigger an asynchronous read 1.1212 +nsresult 1.1213 +nsHttpConnection::ForceRecv() 1.1214 +{ 1.1215 + LOG(("nsHttpConnection::ForceRecv [this=%p]\n", this)); 1.1216 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.1217 + 1.1218 + return NS_DispatchToCurrentThread(new nsHttpConnectionForceRecv(this)); 1.1219 +} 1.1220 + 1.1221 +void 1.1222 +nsHttpConnection::BeginIdleMonitoring() 1.1223 +{ 1.1224 + LOG(("nsHttpConnection::BeginIdleMonitoring [this=%p]\n", this)); 1.1225 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.1226 + MOZ_ASSERT(!mTransaction, "BeginIdleMonitoring() while active"); 1.1227 + MOZ_ASSERT(!mUsingSpdyVersion, "Idle monitoring of spdy not allowed"); 1.1228 + 1.1229 + LOG(("Entering Idle Monitoring Mode [this=%p]", this)); 1.1230 + mIdleMonitoring = true; 1.1231 + if (mSocketIn) 1.1232 + mSocketIn->AsyncWait(this, 0, 0, nullptr); 1.1233 +} 1.1234 + 1.1235 +void 1.1236 +nsHttpConnection::EndIdleMonitoring() 1.1237 +{ 1.1238 + LOG(("nsHttpConnection::EndIdleMonitoring [this=%p]\n", this)); 1.1239 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.1240 + MOZ_ASSERT(!mTransaction, "EndIdleMonitoring() while active"); 1.1241 + 1.1242 + if (mIdleMonitoring) { 1.1243 + LOG(("Leaving Idle Monitoring Mode [this=%p]", this)); 1.1244 + mIdleMonitoring = false; 1.1245 + if (mSocketIn) 1.1246 + mSocketIn->AsyncWait(nullptr, 0, 0, nullptr); 1.1247 + } 1.1248 +} 1.1249 + 1.1250 +//----------------------------------------------------------------------------- 1.1251 +// nsHttpConnection <private> 1.1252 +//----------------------------------------------------------------------------- 1.1253 + 1.1254 +void 1.1255 +nsHttpConnection::CloseTransaction(nsAHttpTransaction *trans, nsresult reason) 1.1256 +{ 1.1257 + LOG(("nsHttpConnection::CloseTransaction[this=%p trans=%x reason=%x]\n", 1.1258 + this, trans, reason)); 1.1259 + 1.1260 + MOZ_ASSERT(trans == mTransaction, "wrong transaction"); 1.1261 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.1262 + 1.1263 + if (mCurrentBytesRead > mMaxBytesRead) 1.1264 + mMaxBytesRead = mCurrentBytesRead; 1.1265 + 1.1266 + // mask this error code because its not a real error. 1.1267 + if (reason == NS_BASE_STREAM_CLOSED) 1.1268 + reason = NS_OK; 1.1269 + 1.1270 + if (mUsingSpdyVersion) { 1.1271 + DontReuse(); 1.1272 + // if !mSpdySession then mUsingSpdyVersion must be false for canreuse() 1.1273 + mUsingSpdyVersion = 0; 1.1274 + mSpdySession = nullptr; 1.1275 + } 1.1276 + 1.1277 + if (mTransaction) { 1.1278 + mHttp1xTransactionCount += mTransaction->Http1xTransactionCount(); 1.1279 + 1.1280 + mTransaction->Close(reason); 1.1281 + mTransaction = nullptr; 1.1282 + } 1.1283 + 1.1284 + { 1.1285 + MutexAutoLock lock(mCallbacksLock); 1.1286 + mCallbacks = nullptr; 1.1287 + } 1.1288 + 1.1289 + if (NS_FAILED(reason)) 1.1290 + Close(reason); 1.1291 + 1.1292 + // flag the connection as reused here for convenience sake. certainly 1.1293 + // it might be going away instead ;-) 1.1294 + mIsReused = true; 1.1295 +} 1.1296 + 1.1297 +NS_METHOD 1.1298 +nsHttpConnection::ReadFromStream(nsIInputStream *input, 1.1299 + void *closure, 1.1300 + const char *buf, 1.1301 + uint32_t offset, 1.1302 + uint32_t count, 1.1303 + uint32_t *countRead) 1.1304 +{ 1.1305 + // thunk for nsIInputStream instance 1.1306 + nsHttpConnection *conn = (nsHttpConnection *) closure; 1.1307 + return conn->OnReadSegment(buf, count, countRead); 1.1308 +} 1.1309 + 1.1310 +nsresult 1.1311 +nsHttpConnection::OnReadSegment(const char *buf, 1.1312 + uint32_t count, 1.1313 + uint32_t *countRead) 1.1314 +{ 1.1315 + if (count == 0) { 1.1316 + // some ReadSegments implementations will erroneously call the writer 1.1317 + // to consume 0 bytes worth of data. we must protect against this case 1.1318 + // or else we'd end up closing the socket prematurely. 1.1319 + NS_ERROR("bad ReadSegments implementation"); 1.1320 + return NS_ERROR_FAILURE; // stop iterating 1.1321 + } 1.1322 + 1.1323 + nsresult rv = mSocketOut->Write(buf, count, countRead); 1.1324 + if (NS_FAILED(rv)) 1.1325 + mSocketOutCondition = rv; 1.1326 + else if (*countRead == 0) 1.1327 + mSocketOutCondition = NS_BASE_STREAM_CLOSED; 1.1328 + else { 1.1329 + mLastWriteTime = PR_IntervalNow(); 1.1330 + mSocketOutCondition = NS_OK; // reset condition 1.1331 + if (!mProxyConnectInProgress) 1.1332 + mTotalBytesWritten += *countRead; 1.1333 + } 1.1334 + 1.1335 + return mSocketOutCondition; 1.1336 +} 1.1337 + 1.1338 +nsresult 1.1339 +nsHttpConnection::OnSocketWritable() 1.1340 +{ 1.1341 + LOG(("nsHttpConnection::OnSocketWritable [this=%p] host=%s\n", 1.1342 + this, mConnInfo->Host())); 1.1343 + 1.1344 + nsresult rv; 1.1345 + uint32_t n; 1.1346 + bool again = true; 1.1347 + 1.1348 + do { 1.1349 + mSocketOutCondition = NS_OK; 1.1350 + 1.1351 + // If we're doing a proxy connect, then we need to bypass calling into 1.1352 + // the transaction. 1.1353 + // 1.1354 + // NOTE: this code path can't be shared since the transaction doesn't 1.1355 + // implement nsIInputStream. doing so is not worth the added cost of 1.1356 + // extra indirections during normal reading. 1.1357 + // 1.1358 + if (mProxyConnectStream) { 1.1359 + LOG((" writing CONNECT request stream\n")); 1.1360 + rv = mProxyConnectStream->ReadSegments(ReadFromStream, this, 1.1361 + nsIOService::gDefaultSegmentSize, 1.1362 + &n); 1.1363 + } 1.1364 + else if (!EnsureNPNComplete()) { 1.1365 + // When SPDY is disabled this branch is not executed because Activate() 1.1366 + // sets mNPNComplete to true in that case. 1.1367 + 1.1368 + // We are ready to proceed with SSL but the handshake is not done. 1.1369 + // When using NPN to negotiate between HTTPS and SPDY, we need to 1.1370 + // see the results of the handshake to know what bytes to send, so 1.1371 + // we cannot proceed with the request headers. 1.1372 + 1.1373 + rv = NS_OK; 1.1374 + mSocketOutCondition = NS_BASE_STREAM_WOULD_BLOCK; 1.1375 + n = 0; 1.1376 + } 1.1377 + else { 1.1378 + if (!mReportedSpdy) { 1.1379 + mReportedSpdy = true; 1.1380 + gHttpHandler->ConnMgr()->ReportSpdyConnection(this, mEverUsedSpdy); 1.1381 + } 1.1382 + 1.1383 + LOG((" writing transaction request stream\n")); 1.1384 + mProxyConnectInProgress = false; 1.1385 + rv = mTransaction->ReadSegments(this, nsIOService::gDefaultSegmentSize, &n); 1.1386 + } 1.1387 + 1.1388 + LOG((" ReadSegments returned [rv=%x read=%u sock-cond=%x]\n", 1.1389 + rv, n, mSocketOutCondition)); 1.1390 + 1.1391 + // XXX some streams return NS_BASE_STREAM_CLOSED to indicate EOF. 1.1392 + if (rv == NS_BASE_STREAM_CLOSED && !mTransaction->IsDone()) { 1.1393 + rv = NS_OK; 1.1394 + n = 0; 1.1395 + } 1.1396 + 1.1397 + if (NS_FAILED(rv)) { 1.1398 + // if the transaction didn't want to write any more data, then 1.1399 + // wait for the transaction to call ResumeSend. 1.1400 + if (rv == NS_BASE_STREAM_WOULD_BLOCK) 1.1401 + rv = NS_OK; 1.1402 + again = false; 1.1403 + } 1.1404 + else if (NS_FAILED(mSocketOutCondition)) { 1.1405 + if (mSocketOutCondition == NS_BASE_STREAM_WOULD_BLOCK) 1.1406 + rv = mSocketOut->AsyncWait(this, 0, 0, nullptr); // continue writing 1.1407 + else 1.1408 + rv = mSocketOutCondition; 1.1409 + again = false; 1.1410 + } 1.1411 + else if (n == 0) { 1.1412 + rv = NS_OK; 1.1413 + 1.1414 + if (mTransaction) { // in case the ReadSegments stack called CloseTransaction() 1.1415 + // 1.1416 + // at this point we've written out the entire transaction, and now we 1.1417 + // must wait for the server's response. we manufacture a status message 1.1418 + // here to reflect the fact that we are waiting. this message will be 1.1419 + // trumped (overwritten) if the server responds quickly. 1.1420 + // 1.1421 + mTransaction->OnTransportStatus(mSocketTransport, 1.1422 + NS_NET_STATUS_WAITING_FOR, 1.1423 + 0); 1.1424 + 1.1425 + rv = ResumeRecv(); // start reading 1.1426 + } 1.1427 + again = false; 1.1428 + } 1.1429 + // write more to the socket until error or end-of-request... 1.1430 + } while (again); 1.1431 + 1.1432 + return rv; 1.1433 +} 1.1434 + 1.1435 +nsresult 1.1436 +nsHttpConnection::OnWriteSegment(char *buf, 1.1437 + uint32_t count, 1.1438 + uint32_t *countWritten) 1.1439 +{ 1.1440 + if (count == 0) { 1.1441 + // some WriteSegments implementations will erroneously call the reader 1.1442 + // to provide 0 bytes worth of data. we must protect against this case 1.1443 + // or else we'd end up closing the socket prematurely. 1.1444 + NS_ERROR("bad WriteSegments implementation"); 1.1445 + return NS_ERROR_FAILURE; // stop iterating 1.1446 + } 1.1447 + 1.1448 + if (ChaosMode::isActive() && ChaosMode::randomUint32LessThan(2)) { 1.1449 + // read 1...count bytes 1.1450 + count = ChaosMode::randomUint32LessThan(count) + 1; 1.1451 + } 1.1452 + 1.1453 + nsresult rv = mSocketIn->Read(buf, count, countWritten); 1.1454 + if (NS_FAILED(rv)) 1.1455 + mSocketInCondition = rv; 1.1456 + else if (*countWritten == 0) 1.1457 + mSocketInCondition = NS_BASE_STREAM_CLOSED; 1.1458 + else 1.1459 + mSocketInCondition = NS_OK; // reset condition 1.1460 + 1.1461 + return mSocketInCondition; 1.1462 +} 1.1463 + 1.1464 +nsresult 1.1465 +nsHttpConnection::OnSocketReadable() 1.1466 +{ 1.1467 + LOG(("nsHttpConnection::OnSocketReadable [this=%p]\n", this)); 1.1468 + 1.1469 + PRIntervalTime now = PR_IntervalNow(); 1.1470 + PRIntervalTime delta = now - mLastReadTime; 1.1471 + 1.1472 + // Reset mResponseTimeoutEnabled to stop response timeout checks. 1.1473 + mResponseTimeoutEnabled = false; 1.1474 + 1.1475 + if (mKeepAliveMask && (delta >= mMaxHangTime)) { 1.1476 + LOG(("max hang time exceeded!\n")); 1.1477 + // give the handler a chance to create a new persistent connection to 1.1478 + // this host if we've been busy for too long. 1.1479 + mKeepAliveMask = false; 1.1480 + gHttpHandler->ProcessPendingQ(mConnInfo); 1.1481 + } 1.1482 + 1.1483 + // Look for data being sent in bursts with large pauses. If the pauses 1.1484 + // are caused by server bottlenecks such as think-time, disk i/o, or 1.1485 + // cpu exhaustion (as opposed to network latency) then we generate negative 1.1486 + // pipelining feedback to prevent head of line problems 1.1487 + 1.1488 + // Reduce the estimate of the time since last read by up to 1 RTT to 1.1489 + // accommodate exhausted sender TCP congestion windows or minor I/O delays. 1.1490 + 1.1491 + if (delta > mRtt) 1.1492 + delta -= mRtt; 1.1493 + else 1.1494 + delta = 0; 1.1495 + 1.1496 + static const PRIntervalTime k400ms = PR_MillisecondsToInterval(400); 1.1497 + 1.1498 + if (delta >= (mRtt + gHttpHandler->GetPipelineRescheduleTimeout())) { 1.1499 + LOG(("Read delta ms of %u causing slow read major " 1.1500 + "event and pipeline cancellation", 1.1501 + PR_IntervalToMilliseconds(delta))); 1.1502 + 1.1503 + gHttpHandler->ConnMgr()->PipelineFeedbackInfo( 1.1504 + mConnInfo, nsHttpConnectionMgr::BadSlowReadMajor, this, 0); 1.1505 + 1.1506 + if (gHttpHandler->GetPipelineRescheduleOnTimeout() && 1.1507 + mTransaction->PipelineDepth() > 1) { 1.1508 + nsHttpPipeline *pipeline = mTransaction->QueryPipeline(); 1.1509 + MOZ_ASSERT(pipeline, "pipelinedepth > 1 without pipeline"); 1.1510 + // code this defensively for the moment and check for null 1.1511 + // This will reschedule blocked members of the pipeline, but the 1.1512 + // blocking transaction (i.e. response 0) will not be changed. 1.1513 + if (pipeline) { 1.1514 + pipeline->CancelPipeline(NS_ERROR_NET_TIMEOUT); 1.1515 + LOG(("Rescheduling the head of line blocked members of a " 1.1516 + "pipeline because reschedule-timeout idle interval " 1.1517 + "exceeded")); 1.1518 + } 1.1519 + } 1.1520 + } 1.1521 + else if (delta > k400ms) { 1.1522 + gHttpHandler->ConnMgr()->PipelineFeedbackInfo( 1.1523 + mConnInfo, nsHttpConnectionMgr::BadSlowReadMinor, this, 0); 1.1524 + } 1.1525 + 1.1526 + mLastReadTime = now; 1.1527 + 1.1528 + nsresult rv; 1.1529 + uint32_t n; 1.1530 + bool again = true; 1.1531 + 1.1532 + do { 1.1533 + if (!mProxyConnectInProgress && !mNPNComplete) { 1.1534 + // Unless we are setting up a tunnel via CONNECT, prevent reading 1.1535 + // from the socket until the results of NPN 1.1536 + // negotiation are known (which is determined from the write path). 1.1537 + // If the server speaks SPDY it is likely the readable data here is 1.1538 + // a spdy settings frame and without NPN it would be misinterpreted 1.1539 + // as HTTP/* 1.1540 + 1.1541 + LOG(("nsHttpConnection::OnSocketReadable %p return due to inactive " 1.1542 + "tunnel setup but incomplete NPN state\n", this)); 1.1543 + rv = NS_OK; 1.1544 + break; 1.1545 + } 1.1546 + 1.1547 + rv = mTransaction->WriteSegments(this, nsIOService::gDefaultSegmentSize, &n); 1.1548 + if (NS_FAILED(rv)) { 1.1549 + // if the transaction didn't want to take any more data, then 1.1550 + // wait for the transaction to call ResumeRecv. 1.1551 + if (rv == NS_BASE_STREAM_WOULD_BLOCK) 1.1552 + rv = NS_OK; 1.1553 + again = false; 1.1554 + } 1.1555 + else { 1.1556 + mCurrentBytesRead += n; 1.1557 + mTotalBytesRead += n; 1.1558 + if (NS_FAILED(mSocketInCondition)) { 1.1559 + // continue waiting for the socket if necessary... 1.1560 + if (mSocketInCondition == NS_BASE_STREAM_WOULD_BLOCK) 1.1561 + rv = ResumeRecv(); 1.1562 + else 1.1563 + rv = mSocketInCondition; 1.1564 + again = false; 1.1565 + } 1.1566 + } 1.1567 + // read more from the socket until error... 1.1568 + } while (again); 1.1569 + 1.1570 + return rv; 1.1571 +} 1.1572 + 1.1573 +nsresult 1.1574 +nsHttpConnection::SetupProxyConnect() 1.1575 +{ 1.1576 + const char *val; 1.1577 + 1.1578 + LOG(("nsHttpConnection::SetupProxyConnect [this=%p]\n", this)); 1.1579 + 1.1580 + NS_ENSURE_TRUE(!mProxyConnectStream, NS_ERROR_ALREADY_INITIALIZED); 1.1581 + MOZ_ASSERT(!mUsingSpdyVersion, 1.1582 + "SPDY NPN Complete while using proxy connect stream"); 1.1583 + 1.1584 + nsAutoCString buf; 1.1585 + nsresult rv = nsHttpHandler::GenerateHostPort( 1.1586 + nsDependentCString(mConnInfo->Host()), mConnInfo->Port(), buf); 1.1587 + if (NS_FAILED(rv)) 1.1588 + return rv; 1.1589 + 1.1590 + // CONNECT host:port HTTP/1.1 1.1591 + nsHttpRequestHead request; 1.1592 + request.SetMethod(NS_LITERAL_CSTRING("CONNECT")); 1.1593 + request.SetVersion(gHttpHandler->HttpVersion()); 1.1594 + request.SetRequestURI(buf); 1.1595 + request.SetHeader(nsHttp::User_Agent, gHttpHandler->UserAgent()); 1.1596 + 1.1597 + // a CONNECT is always persistent 1.1598 + request.SetHeader(nsHttp::Proxy_Connection, NS_LITERAL_CSTRING("keep-alive")); 1.1599 + request.SetHeader(nsHttp::Connection, NS_LITERAL_CSTRING("keep-alive")); 1.1600 + 1.1601 + // all HTTP/1.1 requests must include a Host header (even though it 1.1602 + // may seem redundant in this case; see bug 82388). 1.1603 + request.SetHeader(nsHttp::Host, buf); 1.1604 + 1.1605 + val = mTransaction->RequestHead()->PeekHeader(nsHttp::Proxy_Authorization); 1.1606 + if (val) { 1.1607 + // we don't know for sure if this authorization is intended for the 1.1608 + // SSL proxy, so we add it just in case. 1.1609 + request.SetHeader(nsHttp::Proxy_Authorization, nsDependentCString(val)); 1.1610 + } 1.1611 + 1.1612 + buf.Truncate(); 1.1613 + request.Flatten(buf, false); 1.1614 + buf.AppendLiteral("\r\n"); 1.1615 + 1.1616 + return NS_NewCStringInputStream(getter_AddRefs(mProxyConnectStream), buf); 1.1617 +} 1.1618 + 1.1619 +nsresult 1.1620 +nsHttpConnection::StartShortLivedTCPKeepalives() 1.1621 +{ 1.1622 + if (mUsingSpdyVersion) { 1.1623 + return NS_OK; 1.1624 + } 1.1625 + MOZ_ASSERT(mSocketTransport); 1.1626 + if (!mSocketTransport) { 1.1627 + return NS_ERROR_NOT_INITIALIZED; 1.1628 + } 1.1629 + 1.1630 + nsresult rv = NS_OK; 1.1631 + int32_t idleTimeS = -1; 1.1632 + int32_t retryIntervalS = -1; 1.1633 + if (gHttpHandler->TCPKeepaliveEnabledForShortLivedConns()) { 1.1634 + // Set the idle time. 1.1635 + idleTimeS = gHttpHandler->GetTCPKeepaliveShortLivedIdleTime(); 1.1636 + LOG(("nsHttpConnection::StartShortLivedTCPKeepalives[%p] " 1.1637 + "idle time[%ds].", this, idleTimeS)); 1.1638 + 1.1639 + retryIntervalS = 1.1640 + std::max<int32_t>((int32_t)PR_IntervalToSeconds(mRtt), 1); 1.1641 + rv = mSocketTransport->SetKeepaliveVals(idleTimeS, retryIntervalS); 1.1642 + if (NS_WARN_IF(NS_FAILED(rv))) { 1.1643 + return rv; 1.1644 + } 1.1645 + rv = mSocketTransport->SetKeepaliveEnabled(true); 1.1646 + mTCPKeepaliveConfig = kTCPKeepaliveShortLivedConfig; 1.1647 + } else { 1.1648 + rv = mSocketTransport->SetKeepaliveEnabled(false); 1.1649 + mTCPKeepaliveConfig = kTCPKeepaliveDisabled; 1.1650 + } 1.1651 + if (NS_WARN_IF(NS_FAILED(rv))) { 1.1652 + return rv; 1.1653 + } 1.1654 + 1.1655 + // Start a timer to move to long-lived keepalive config. 1.1656 + if(!mTCPKeepaliveTransitionTimer) { 1.1657 + mTCPKeepaliveTransitionTimer = 1.1658 + do_CreateInstance("@mozilla.org/timer;1"); 1.1659 + } 1.1660 + 1.1661 + if (mTCPKeepaliveTransitionTimer) { 1.1662 + int32_t time = gHttpHandler->GetTCPKeepaliveShortLivedTime(); 1.1663 + 1.1664 + // Adjust |time| to ensure a full set of keepalive probes can be sent 1.1665 + // at the end of the short-lived phase. 1.1666 + if (gHttpHandler->TCPKeepaliveEnabledForShortLivedConns()) { 1.1667 + if (NS_WARN_IF(!gSocketTransportService)) { 1.1668 + return NS_ERROR_NOT_INITIALIZED; 1.1669 + } 1.1670 + int32_t probeCount = -1; 1.1671 + rv = gSocketTransportService->GetKeepaliveProbeCount(&probeCount); 1.1672 + if (NS_WARN_IF(NS_FAILED(rv))) { 1.1673 + return rv; 1.1674 + } 1.1675 + if (NS_WARN_IF(probeCount <= 0)) { 1.1676 + return NS_ERROR_UNEXPECTED; 1.1677 + } 1.1678 + // Add time for final keepalive probes, and 2 seconds for a buffer. 1.1679 + time += ((probeCount) * retryIntervalS) - (time % idleTimeS) + 2; 1.1680 + } 1.1681 + mTCPKeepaliveTransitionTimer->InitWithFuncCallback( 1.1682 + nsHttpConnection::UpdateTCPKeepalive, 1.1683 + this, 1.1684 + (uint32_t)time*1000, 1.1685 + nsITimer::TYPE_ONE_SHOT); 1.1686 + } else { 1.1687 + NS_WARNING("nsHttpConnection::StartShortLivedTCPKeepalives failed to " 1.1688 + "create timer."); 1.1689 + } 1.1690 + 1.1691 + return NS_OK; 1.1692 +} 1.1693 + 1.1694 +nsresult 1.1695 +nsHttpConnection::StartLongLivedTCPKeepalives() 1.1696 +{ 1.1697 + MOZ_ASSERT(!mUsingSpdyVersion, "Don't use TCP Keepalive with SPDY!"); 1.1698 + if (NS_WARN_IF(mUsingSpdyVersion)) { 1.1699 + return NS_OK; 1.1700 + } 1.1701 + MOZ_ASSERT(mSocketTransport); 1.1702 + if (!mSocketTransport) { 1.1703 + return NS_ERROR_NOT_INITIALIZED; 1.1704 + } 1.1705 + 1.1706 + nsresult rv = NS_OK; 1.1707 + if (gHttpHandler->TCPKeepaliveEnabledForLongLivedConns()) { 1.1708 + // Increase the idle time. 1.1709 + int32_t idleTimeS = gHttpHandler->GetTCPKeepaliveLongLivedIdleTime(); 1.1710 + LOG(("nsHttpConnection::StartLongLivedTCPKeepalives[%p] idle time[%ds]", 1.1711 + this, idleTimeS)); 1.1712 + 1.1713 + int32_t retryIntervalS = 1.1714 + std::max<int32_t>((int32_t)PR_IntervalToSeconds(mRtt), 1); 1.1715 + rv = mSocketTransport->SetKeepaliveVals(idleTimeS, retryIntervalS); 1.1716 + if (NS_WARN_IF(NS_FAILED(rv))) { 1.1717 + return rv; 1.1718 + } 1.1719 + 1.1720 + // Ensure keepalive is enabled, if current status is disabled. 1.1721 + if (mTCPKeepaliveConfig == kTCPKeepaliveDisabled) { 1.1722 + rv = mSocketTransport->SetKeepaliveEnabled(true); 1.1723 + if (NS_WARN_IF(NS_FAILED(rv))) { 1.1724 + return rv; 1.1725 + } 1.1726 + } 1.1727 + mTCPKeepaliveConfig = kTCPKeepaliveLongLivedConfig; 1.1728 + } else { 1.1729 + rv = mSocketTransport->SetKeepaliveEnabled(false); 1.1730 + mTCPKeepaliveConfig = kTCPKeepaliveDisabled; 1.1731 + } 1.1732 + 1.1733 + if (NS_WARN_IF(NS_FAILED(rv))) { 1.1734 + return rv; 1.1735 + } 1.1736 + return NS_OK; 1.1737 +} 1.1738 + 1.1739 +nsresult 1.1740 +nsHttpConnection::DisableTCPKeepalives() 1.1741 +{ 1.1742 + MOZ_ASSERT(mSocketTransport); 1.1743 + if (!mSocketTransport) { 1.1744 + return NS_ERROR_NOT_INITIALIZED; 1.1745 + } 1.1746 + LOG(("nsHttpConnection::DisableTCPKeepalives [%p]", this)); 1.1747 + if (mTCPKeepaliveConfig != kTCPKeepaliveDisabled) { 1.1748 + nsresult rv = mSocketTransport->SetKeepaliveEnabled(false); 1.1749 + if (NS_WARN_IF(NS_FAILED(rv))) { 1.1750 + return rv; 1.1751 + } 1.1752 + mTCPKeepaliveConfig = kTCPKeepaliveDisabled; 1.1753 + } 1.1754 + if (mTCPKeepaliveTransitionTimer) { 1.1755 + mTCPKeepaliveTransitionTimer->Cancel(); 1.1756 + mTCPKeepaliveTransitionTimer = nullptr; 1.1757 + } 1.1758 + return NS_OK; 1.1759 +} 1.1760 + 1.1761 +//----------------------------------------------------------------------------- 1.1762 +// nsHttpConnection::nsISupports 1.1763 +//----------------------------------------------------------------------------- 1.1764 + 1.1765 +NS_IMPL_ISUPPORTS(nsHttpConnection, 1.1766 + nsIInputStreamCallback, 1.1767 + nsIOutputStreamCallback, 1.1768 + nsITransportEventSink, 1.1769 + nsIInterfaceRequestor) 1.1770 + 1.1771 +//----------------------------------------------------------------------------- 1.1772 +// nsHttpConnection::nsIInputStreamCallback 1.1773 +//----------------------------------------------------------------------------- 1.1774 + 1.1775 +// called on the socket transport thread 1.1776 +NS_IMETHODIMP 1.1777 +nsHttpConnection::OnInputStreamReady(nsIAsyncInputStream *in) 1.1778 +{ 1.1779 + MOZ_ASSERT(in == mSocketIn, "unexpected stream"); 1.1780 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.1781 + 1.1782 + if (mIdleMonitoring) { 1.1783 + MOZ_ASSERT(!mTransaction, "Idle Input Event While Active"); 1.1784 + 1.1785 + // The only read event that is protocol compliant for an idle connection 1.1786 + // is an EOF, which we check for with CanReuse(). If the data is 1.1787 + // something else then just ignore it and suspend checking for EOF - 1.1788 + // our normal timers or protocol stack are the place to deal with 1.1789 + // any exception logic. 1.1790 + 1.1791 + if (!CanReuse()) { 1.1792 + LOG(("Server initiated close of idle conn %p\n", this)); 1.1793 + gHttpHandler->ConnMgr()->CloseIdleConnection(this); 1.1794 + return NS_OK; 1.1795 + } 1.1796 + 1.1797 + LOG(("Input data on idle conn %p, but not closing yet\n", this)); 1.1798 + return NS_OK; 1.1799 + } 1.1800 + 1.1801 + // if the transaction was dropped... 1.1802 + if (!mTransaction) { 1.1803 + LOG((" no transaction; ignoring event\n")); 1.1804 + return NS_OK; 1.1805 + } 1.1806 + 1.1807 + nsresult rv = OnSocketReadable(); 1.1808 + if (NS_FAILED(rv)) 1.1809 + CloseTransaction(mTransaction, rv); 1.1810 + 1.1811 + return NS_OK; 1.1812 +} 1.1813 + 1.1814 +//----------------------------------------------------------------------------- 1.1815 +// nsHttpConnection::nsIOutputStreamCallback 1.1816 +//----------------------------------------------------------------------------- 1.1817 + 1.1818 +NS_IMETHODIMP 1.1819 +nsHttpConnection::OnOutputStreamReady(nsIAsyncOutputStream *out) 1.1820 +{ 1.1821 + MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); 1.1822 + MOZ_ASSERT(out == mSocketOut, "unexpected socket"); 1.1823 + 1.1824 + // if the transaction was dropped... 1.1825 + if (!mTransaction) { 1.1826 + LOG((" no transaction; ignoring event\n")); 1.1827 + return NS_OK; 1.1828 + } 1.1829 + 1.1830 + nsresult rv = OnSocketWritable(); 1.1831 + if (NS_FAILED(rv)) 1.1832 + CloseTransaction(mTransaction, rv); 1.1833 + 1.1834 + return NS_OK; 1.1835 +} 1.1836 + 1.1837 +//----------------------------------------------------------------------------- 1.1838 +// nsHttpConnection::nsITransportEventSink 1.1839 +//----------------------------------------------------------------------------- 1.1840 + 1.1841 +NS_IMETHODIMP 1.1842 +nsHttpConnection::OnTransportStatus(nsITransport *trans, 1.1843 + nsresult status, 1.1844 + uint64_t progress, 1.1845 + uint64_t progressMax) 1.1846 +{ 1.1847 + if (mTransaction) 1.1848 + mTransaction->OnTransportStatus(trans, status, progress); 1.1849 + return NS_OK; 1.1850 +} 1.1851 + 1.1852 +//----------------------------------------------------------------------------- 1.1853 +// nsHttpConnection::nsIInterfaceRequestor 1.1854 +//----------------------------------------------------------------------------- 1.1855 + 1.1856 +// not called on the socket transport thread 1.1857 +NS_IMETHODIMP 1.1858 +nsHttpConnection::GetInterface(const nsIID &iid, void **result) 1.1859 +{ 1.1860 + // NOTE: This function is only called on the UI thread via sync proxy from 1.1861 + // the socket transport thread. If that weren't the case, then we'd 1.1862 + // have to worry about the possibility of mTransaction going away 1.1863 + // part-way through this function call. See CloseTransaction. 1.1864 + 1.1865 + // NOTE - there is a bug here, the call to getinterface is proxied off the 1.1866 + // nss thread, not the ui thread as the above comment says. So there is 1.1867 + // indeed a chance of mTransaction going away. bug 615342 1.1868 + 1.1869 + MOZ_ASSERT(PR_GetCurrentThread() != gSocketThread); 1.1870 + 1.1871 + nsCOMPtr<nsIInterfaceRequestor> callbacks; 1.1872 + { 1.1873 + MutexAutoLock lock(mCallbacksLock); 1.1874 + callbacks = mCallbacks; 1.1875 + } 1.1876 + if (callbacks) 1.1877 + return callbacks->GetInterface(iid, result); 1.1878 + return NS_ERROR_NO_INTERFACE; 1.1879 +} 1.1880 + 1.1881 +} // namespace mozilla::net 1.1882 +} // namespace mozilla