michael@0: /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ michael@0: /* vim:set ts=4 sw=4 sts=4 et cin: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: // HttpLog.h should generally be included first michael@0: #include "HttpLog.h" michael@0: michael@0: // Log on level :5, instead of default :4. michael@0: #undef LOG michael@0: #define LOG(args) LOG5(args) michael@0: #undef LOG_ENABLED michael@0: #define LOG_ENABLED() LOG5_ENABLED() michael@0: michael@0: #include "nsHttpConnection.h" michael@0: #include "nsHttpRequestHead.h" michael@0: #include "nsHttpResponseHead.h" michael@0: #include "nsHttpHandler.h" michael@0: #include "nsIOService.h" michael@0: #include "nsISocketTransport.h" michael@0: #include "nsSocketTransportService2.h" michael@0: #include "nsISSLSocketControl.h" michael@0: #include "sslt.h" michael@0: #include "nsStringStream.h" michael@0: #include "nsProxyRelease.h" michael@0: #include "nsPreloadedStream.h" michael@0: #include "ASpdySession.h" michael@0: #include "mozilla/Telemetry.h" michael@0: #include "nsISupportsPriority.h" michael@0: #include "nsHttpPipeline.h" michael@0: #include michael@0: #include "mozilla/ChaosMode.h" michael@0: michael@0: #ifdef DEBUG michael@0: // defined by the socket transport service while active michael@0: extern PRThread *gSocketThread; michael@0: #endif michael@0: michael@0: namespace mozilla { michael@0: namespace net { michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: // nsHttpConnection michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: nsHttpConnection::nsHttpConnection() michael@0: : mTransaction(nullptr) michael@0: , mHttpHandler(gHttpHandler) michael@0: , mCallbacksLock("nsHttpConnection::mCallbacksLock") michael@0: , mConsiderReusedAfterInterval(0) michael@0: , mConsiderReusedAfterEpoch(0) michael@0: , mCurrentBytesRead(0) michael@0: , mMaxBytesRead(0) michael@0: , mTotalBytesRead(0) michael@0: , mTotalBytesWritten(0) michael@0: , mKeepAlive(true) // assume to keep-alive by default michael@0: , mKeepAliveMask(true) michael@0: , mDontReuse(false) michael@0: , mSupportsPipelining(false) // assume low-grade server michael@0: , mIsReused(false) michael@0: , mCompletedProxyConnect(false) michael@0: , mLastTransactionExpectedNoContent(false) michael@0: , mIdleMonitoring(false) michael@0: , mProxyConnectInProgress(false) michael@0: , mExperienced(false) michael@0: , mHttp1xTransactionCount(0) michael@0: , mRemainingConnectionUses(0xffffffff) michael@0: , mClassification(nsAHttpTransaction::CLASS_GENERAL) michael@0: , mNPNComplete(false) michael@0: , mSetupSSLCalled(false) michael@0: , mUsingSpdyVersion(0) michael@0: , mPriority(nsISupportsPriority::PRIORITY_NORMAL) michael@0: , mReportedSpdy(false) michael@0: , mEverUsedSpdy(false) michael@0: , mLastHttpResponseVersion(NS_HTTP_VERSION_1_1) michael@0: , mTransactionCaps(0) michael@0: , mResponseTimeoutEnabled(false) michael@0: , mTCPKeepaliveConfig(kTCPKeepaliveDisabled) michael@0: { michael@0: LOG(("Creating nsHttpConnection @%x\n", this)); michael@0: michael@0: // the default timeout is for when this connection has not yet processed a michael@0: // transaction michael@0: static const PRIntervalTime k5Sec = PR_SecondsToInterval(5); michael@0: mIdleTimeout = michael@0: (k5Sec < gHttpHandler->IdleTimeout()) ? k5Sec : gHttpHandler->IdleTimeout(); michael@0: } michael@0: michael@0: nsHttpConnection::~nsHttpConnection() michael@0: { michael@0: LOG(("Destroying nsHttpConnection @%x\n", this)); michael@0: michael@0: if (!mEverUsedSpdy) { michael@0: LOG(("nsHttpConnection %p performed %d HTTP/1.x transactions\n", michael@0: this, mHttp1xTransactionCount)); michael@0: Telemetry::Accumulate(Telemetry::HTTP_REQUEST_PER_CONN, michael@0: mHttp1xTransactionCount); michael@0: } michael@0: michael@0: if (mTotalBytesRead) { michael@0: uint32_t totalKBRead = static_cast(mTotalBytesRead >> 10); michael@0: LOG(("nsHttpConnection %p read %dkb on connection spdy=%d\n", michael@0: this, totalKBRead, mEverUsedSpdy)); michael@0: Telemetry::Accumulate(mEverUsedSpdy ? michael@0: Telemetry::SPDY_KBREAD_PER_CONN : michael@0: Telemetry::HTTP_KBREAD_PER_CONN, michael@0: totalKBRead); michael@0: } michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::Init(nsHttpConnectionInfo *info, michael@0: uint16_t maxHangTime, michael@0: nsISocketTransport *transport, michael@0: nsIAsyncInputStream *instream, michael@0: nsIAsyncOutputStream *outstream, michael@0: nsIInterfaceRequestor *callbacks, michael@0: PRIntervalTime rtt) michael@0: { michael@0: MOZ_ASSERT(transport && instream && outstream, michael@0: "invalid socket information"); michael@0: LOG(("nsHttpConnection::Init [this=%p " michael@0: "transport=%p instream=%p outstream=%p rtt=%d]\n", michael@0: this, transport, instream, outstream, michael@0: PR_IntervalToMilliseconds(rtt))); michael@0: michael@0: NS_ENSURE_ARG_POINTER(info); michael@0: NS_ENSURE_TRUE(!mConnInfo, NS_ERROR_ALREADY_INITIALIZED); michael@0: michael@0: mConnInfo = info; michael@0: mLastWriteTime = mLastReadTime = PR_IntervalNow(); michael@0: mSupportsPipelining = michael@0: gHttpHandler->ConnMgr()->SupportsPipelining(mConnInfo); michael@0: mRtt = rtt; michael@0: mMaxHangTime = PR_SecondsToInterval(maxHangTime); michael@0: michael@0: mSocketTransport = transport; michael@0: mSocketIn = instream; michael@0: mSocketOut = outstream; michael@0: nsresult rv = mSocketTransport->SetEventSink(this, nullptr); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: // See explanation for non-strictness of this operation in SetSecurityCallbacks. michael@0: mCallbacks = new nsMainThreadPtrHolder(callbacks, false); michael@0: rv = mSocketTransport->SetSecurityCallbacks(this); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: void michael@0: nsHttpConnection::StartSpdy(uint8_t spdyVersion) michael@0: { michael@0: LOG(("nsHttpConnection::StartSpdy [this=%p]\n", this)); michael@0: michael@0: MOZ_ASSERT(!mSpdySession); michael@0: michael@0: mUsingSpdyVersion = spdyVersion; michael@0: mEverUsedSpdy = true; michael@0: michael@0: // Setting the connection as reused allows some transactions that fail michael@0: // with NS_ERROR_NET_RESET to be restarted and SPDY uses that code michael@0: // to handle clean rejections (such as those that arrived after michael@0: // a server goaway was generated). michael@0: mIsReused = true; michael@0: michael@0: // If mTransaction is a pipeline object it might represent michael@0: // several requests. If so, we need to unpack that and michael@0: // pack them all into a new spdy session. michael@0: michael@0: nsTArray > list; michael@0: nsresult rv = mTransaction->TakeSubTransactions(list); michael@0: michael@0: if (rv == NS_ERROR_ALREADY_OPENED) { michael@0: // Has the interface for TakeSubTransactions() changed? michael@0: LOG(("TakeSubTranscations somehow called after " michael@0: "nsAHttpTransaction began processing\n")); michael@0: MOZ_ASSERT(false, michael@0: "TakeSubTranscations somehow called after " michael@0: "nsAHttpTransaction began processing"); michael@0: mTransaction->Close(NS_ERROR_ABORT); michael@0: return; michael@0: } michael@0: michael@0: if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) { michael@0: // Has the interface for TakeSubTransactions() changed? michael@0: LOG(("unexpected rv from nnsAHttpTransaction::TakeSubTransactions()")); michael@0: MOZ_ASSERT(false, michael@0: "unexpected result from " michael@0: "nsAHttpTransaction::TakeSubTransactions()"); michael@0: mTransaction->Close(NS_ERROR_ABORT); michael@0: return; michael@0: } michael@0: michael@0: if (NS_FAILED(rv)) { // includes NS_ERROR_NOT_IMPLEMENTED michael@0: MOZ_ASSERT(list.IsEmpty(), "sub transaction list not empty"); michael@0: michael@0: // This is ok - treat mTransaction as a single real request. michael@0: // Wrap the old http transaction into the new spdy session michael@0: // as the first stream. michael@0: mSpdySession = ASpdySession::NewSpdySession(spdyVersion, michael@0: mTransaction, mSocketTransport, michael@0: mPriority); michael@0: LOG(("nsHttpConnection::StartSpdy moves single transaction %p " michael@0: "into SpdySession %p\n", mTransaction.get(), mSpdySession.get())); michael@0: } michael@0: else { michael@0: int32_t count = list.Length(); michael@0: michael@0: LOG(("nsHttpConnection::StartSpdy moving transaction list len=%d " michael@0: "into SpdySession %p\n", count, mSpdySession.get())); michael@0: michael@0: if (!count) { michael@0: mTransaction->Close(NS_ERROR_ABORT); michael@0: return; michael@0: } michael@0: michael@0: for (int32_t index = 0; index < count; ++index) { michael@0: if (!mSpdySession) { michael@0: mSpdySession = ASpdySession::NewSpdySession(spdyVersion, michael@0: list[index], mSocketTransport, michael@0: mPriority); michael@0: } michael@0: else { michael@0: // AddStream() cannot fail michael@0: if (!mSpdySession->AddStream(list[index], mPriority)) { michael@0: MOZ_ASSERT(false, "SpdySession::AddStream failed"); michael@0: LOG(("SpdySession::AddStream failed\n")); michael@0: mTransaction->Close(NS_ERROR_ABORT); michael@0: return; michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Disable TCP Keepalives - use SPDY ping instead. michael@0: rv = DisableTCPKeepalives(); michael@0: if (NS_WARN_IF(NS_FAILED(rv))) { michael@0: LOG(("nsHttpConnection::StartSpdy [%p] DisableTCPKeepalives failed " michael@0: "rv[0x%x]", this, rv)); michael@0: } michael@0: michael@0: mSupportsPipelining = false; // dont use http/1 pipelines with spdy michael@0: mTransaction = mSpdySession; michael@0: mIdleTimeout = gHttpHandler->SpdyTimeout(); michael@0: } michael@0: michael@0: bool michael@0: nsHttpConnection::EnsureNPNComplete() michael@0: { michael@0: // If for some reason the components to check on NPN aren't available, michael@0: // this function will just return true to continue on and disable SPDY michael@0: michael@0: MOZ_ASSERT(mSocketTransport); michael@0: if (!mSocketTransport) { michael@0: // this cannot happen michael@0: mNPNComplete = true; michael@0: return true; michael@0: } michael@0: michael@0: if (mNPNComplete) michael@0: return true; michael@0: michael@0: nsresult rv; michael@0: michael@0: nsCOMPtr securityInfo; michael@0: nsCOMPtr ssl; michael@0: nsAutoCString negotiatedNPN; michael@0: michael@0: rv = mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo)); michael@0: if (NS_FAILED(rv)) michael@0: goto npnComplete; michael@0: michael@0: ssl = do_QueryInterface(securityInfo, &rv); michael@0: if (NS_FAILED(rv)) michael@0: goto npnComplete; michael@0: michael@0: rv = ssl->GetNegotiatedNPN(negotiatedNPN); michael@0: if (rv == NS_ERROR_NOT_CONNECTED) { michael@0: michael@0: // By writing 0 bytes to the socket the SSL handshake machine is michael@0: // pushed forward. michael@0: uint32_t count = 0; michael@0: rv = mSocketOut->Write("", 0, &count); michael@0: michael@0: if (NS_FAILED(rv) && rv != NS_BASE_STREAM_WOULD_BLOCK) michael@0: goto npnComplete; michael@0: return false; michael@0: } michael@0: michael@0: if (NS_FAILED(rv)) michael@0: goto npnComplete; michael@0: michael@0: LOG(("nsHttpConnection::EnsureNPNComplete %p [%s] negotiated to '%s'\n", michael@0: this, mConnInfo->Host(), negotiatedNPN.get())); michael@0: michael@0: uint8_t spdyVersion; michael@0: rv = gHttpHandler->SpdyInfo()->GetNPNVersionIndex(negotiatedNPN, michael@0: &spdyVersion); michael@0: if (NS_SUCCEEDED(rv)) michael@0: StartSpdy(spdyVersion); michael@0: michael@0: Telemetry::Accumulate(Telemetry::SPDY_NPN_CONNECT, UsingSpdy()); michael@0: michael@0: npnComplete: michael@0: LOG(("nsHttpConnection::EnsureNPNComplete setting complete to true")); michael@0: mNPNComplete = true; michael@0: return true; michael@0: } michael@0: michael@0: // called on the socket thread michael@0: nsresult michael@0: nsHttpConnection::Activate(nsAHttpTransaction *trans, uint32_t caps, int32_t pri) michael@0: { michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: LOG(("nsHttpConnection::Activate [this=%p trans=%x caps=%x]\n", michael@0: this, trans, caps)); michael@0: michael@0: if (!trans->IsNullTransaction()) michael@0: mExperienced = true; michael@0: michael@0: mTransactionCaps = caps; michael@0: mPriority = pri; michael@0: if (mTransaction && mUsingSpdyVersion) michael@0: return AddTransaction(trans, pri); michael@0: michael@0: NS_ENSURE_ARG_POINTER(trans); michael@0: NS_ENSURE_TRUE(!mTransaction, NS_ERROR_IN_PROGRESS); michael@0: michael@0: // reset the read timers to wash away any idle time michael@0: mLastWriteTime = mLastReadTime = PR_IntervalNow(); michael@0: michael@0: // Update security callbacks michael@0: nsCOMPtr callbacks; michael@0: trans->GetSecurityCallbacks(getter_AddRefs(callbacks)); michael@0: SetSecurityCallbacks(callbacks); michael@0: michael@0: SetupSSL(caps); michael@0: michael@0: // take ownership of the transaction michael@0: mTransaction = trans; michael@0: michael@0: MOZ_ASSERT(!mIdleMonitoring, "Activating a connection with an Idle Monitor"); michael@0: mIdleMonitoring = false; michael@0: michael@0: // set mKeepAlive according to what will be requested michael@0: mKeepAliveMask = mKeepAlive = (caps & NS_HTTP_ALLOW_KEEPALIVE); michael@0: michael@0: // need to handle HTTP CONNECT tunnels if this is the first time if michael@0: // we are tunneling through a proxy michael@0: nsresult rv = NS_OK; michael@0: if (mConnInfo->UsingConnect() && !mCompletedProxyConnect) { michael@0: rv = SetupProxyConnect(); michael@0: if (NS_FAILED(rv)) michael@0: goto failed_activation; michael@0: mProxyConnectInProgress = true; michael@0: } michael@0: michael@0: // Clear the per activation counter michael@0: mCurrentBytesRead = 0; michael@0: michael@0: // The overflow state is not needed between activations michael@0: mInputOverflow = nullptr; michael@0: michael@0: mResponseTimeoutEnabled = gHttpHandler->ResponseTimeoutEnabled() && michael@0: mTransaction->ResponseTimeout() > 0 && michael@0: mTransaction->ResponseTimeoutEnabled(); michael@0: michael@0: rv = StartShortLivedTCPKeepalives(); michael@0: if (NS_WARN_IF(NS_FAILED(rv))) { michael@0: LOG(("nsHttpConnection::Activate [%p] " michael@0: "StartShortLivedTCPKeepalives failed rv[0x%x]", michael@0: this, rv)); michael@0: } michael@0: michael@0: rv = OnOutputStreamReady(mSocketOut); michael@0: michael@0: failed_activation: michael@0: if (NS_FAILED(rv)) { michael@0: mTransaction = nullptr; michael@0: } michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: void michael@0: nsHttpConnection::SetupSSL(uint32_t caps) michael@0: { michael@0: LOG(("nsHttpConnection::SetupSSL %p caps=0x%X\n", this, caps)); michael@0: michael@0: if (mSetupSSLCalled) // do only once michael@0: return; michael@0: mSetupSSLCalled = true; michael@0: michael@0: if (mNPNComplete) michael@0: return; michael@0: michael@0: // we flip this back to false if SetNPNList succeeds at the end michael@0: // of this function michael@0: mNPNComplete = true; michael@0: michael@0: if (!mConnInfo->UsingSSL()) michael@0: return; michael@0: michael@0: LOG(("nsHttpConnection::SetupSSL Setting up " michael@0: "Next Protocol Negotiation")); michael@0: nsCOMPtr securityInfo; michael@0: nsresult rv = michael@0: mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo)); michael@0: if (NS_FAILED(rv)) michael@0: return; michael@0: michael@0: nsCOMPtr ssl = do_QueryInterface(securityInfo, &rv); michael@0: if (NS_FAILED(rv)) michael@0: return; michael@0: michael@0: if (caps & NS_HTTP_ALLOW_RSA_FALSESTART) { michael@0: LOG(("nsHttpConnection::SetupSSL %p " michael@0: ">= RSA Key Exchange Expected\n", this)); michael@0: ssl->SetKEAExpected(ssl_kea_rsa); michael@0: } michael@0: michael@0: nsTArray protocolArray; michael@0: michael@0: // The first protocol is used as the fallback if none of the michael@0: // protocols supported overlap with the server's list. michael@0: // In the case of overlap, matching priority is driven by michael@0: // the order of the server's advertisement. michael@0: protocolArray.AppendElement(NS_LITERAL_CSTRING("http/1.1")); michael@0: michael@0: if (gHttpHandler->IsSpdyEnabled() && michael@0: !(caps & NS_HTTP_DISALLOW_SPDY)) { michael@0: LOG(("nsHttpConnection::SetupSSL Allow SPDY NPN selection")); michael@0: for (uint32_t index = 0; index < SpdyInformation::kCount; ++index) { michael@0: if (gHttpHandler->SpdyInfo()->ProtocolEnabled(index)) michael@0: protocolArray.AppendElement( michael@0: gHttpHandler->SpdyInfo()->VersionString[index]); michael@0: } michael@0: } michael@0: michael@0: if (NS_SUCCEEDED(ssl->SetNPNList(protocolArray))) { michael@0: LOG(("nsHttpConnection::Init Setting up SPDY Negotiation OK")); michael@0: mNPNComplete = false; michael@0: } michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::AddTransaction(nsAHttpTransaction *httpTransaction, michael@0: int32_t priority) michael@0: { michael@0: LOG(("nsHttpConnection::AddTransaction for SPDY")); michael@0: michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: MOZ_ASSERT(mSpdySession && mUsingSpdyVersion, michael@0: "AddTransaction to live http connection without spdy"); michael@0: MOZ_ASSERT(mTransaction, michael@0: "AddTransaction to idle http connection"); michael@0: michael@0: if (!mSpdySession->AddStream(httpTransaction, priority)) { michael@0: MOZ_ASSERT(false, "AddStream should never fail due to" michael@0: "RoomForMore() admission check"); michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: michael@0: ResumeSend(); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: void michael@0: nsHttpConnection::Close(nsresult reason) michael@0: { michael@0: LOG(("nsHttpConnection::Close [this=%p reason=%x]\n", this, reason)); michael@0: michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: michael@0: // Ensure TCP keepalive timer is stopped. michael@0: if (mTCPKeepaliveTransitionTimer) { michael@0: mTCPKeepaliveTransitionTimer->Cancel(); michael@0: mTCPKeepaliveTransitionTimer = nullptr; michael@0: } michael@0: michael@0: if (NS_FAILED(reason)) { michael@0: if (mIdleMonitoring) michael@0: EndIdleMonitoring(); michael@0: michael@0: if (mSocketTransport) { michael@0: mSocketTransport->SetEventSink(nullptr, nullptr); michael@0: michael@0: // If there are bytes sitting in the input queue then read them michael@0: // into a junk buffer to avoid generating a tcp rst by closing a michael@0: // socket with data pending. TLS is a classic case of this where michael@0: // a Alert record might be superfulous to a clean HTTP/SPDY shutdown. michael@0: // Never block to do this and limit it to a small amount of data. michael@0: if (mSocketIn) { michael@0: char buffer[4000]; michael@0: uint32_t count, total = 0; michael@0: nsresult rv; michael@0: do { michael@0: rv = mSocketIn->Read(buffer, 4000, &count); michael@0: if (NS_SUCCEEDED(rv)) michael@0: total += count; michael@0: } michael@0: while (NS_SUCCEEDED(rv) && count > 0 && total < 64000); michael@0: LOG(("nsHttpConnection::Close drained %d bytes\n", total)); michael@0: } michael@0: michael@0: mSocketTransport->SetSecurityCallbacks(nullptr); michael@0: mSocketTransport->Close(reason); michael@0: if (mSocketOut) michael@0: mSocketOut->AsyncWait(nullptr, 0, 0, nullptr); michael@0: } michael@0: mKeepAlive = false; michael@0: } michael@0: } michael@0: michael@0: // called on the socket thread michael@0: nsresult michael@0: nsHttpConnection::ProxyStartSSL() michael@0: { michael@0: LOG(("nsHttpConnection::ProxyStartSSL [this=%p]\n", this)); michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: michael@0: nsCOMPtr securityInfo; michael@0: nsresult rv = mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo)); michael@0: if (NS_FAILED(rv)) return rv; michael@0: michael@0: nsCOMPtr ssl = do_QueryInterface(securityInfo, &rv); michael@0: if (NS_FAILED(rv)) return rv; michael@0: michael@0: return ssl->ProxyStartSSL(); michael@0: } michael@0: michael@0: void michael@0: nsHttpConnection::DontReuse() michael@0: { michael@0: mKeepAliveMask = false; michael@0: mKeepAlive = false; michael@0: mDontReuse = true; michael@0: mIdleTimeout = 0; michael@0: if (mSpdySession) michael@0: mSpdySession->DontReuse(); michael@0: } michael@0: michael@0: // Checked by the Connection Manager before scheduling a pipelined transaction michael@0: bool michael@0: nsHttpConnection::SupportsPipelining() michael@0: { michael@0: if (mTransaction && michael@0: mTransaction->PipelineDepth() >= mRemainingConnectionUses) { michael@0: LOG(("nsHttpConnection::SupportsPipelining this=%p deny pipeline " michael@0: "because current depth %d exceeds max remaining uses %d\n", michael@0: this, mTransaction->PipelineDepth(), mRemainingConnectionUses)); michael@0: return false; michael@0: } michael@0: return mSupportsPipelining && IsKeepAlive() && !mDontReuse; michael@0: } michael@0: michael@0: bool michael@0: nsHttpConnection::CanReuse() michael@0: { michael@0: if (mDontReuse) michael@0: return false; michael@0: michael@0: if ((mTransaction ? mTransaction->PipelineDepth() : 0) >= michael@0: mRemainingConnectionUses) { michael@0: return false; michael@0: } michael@0: michael@0: bool canReuse; michael@0: michael@0: if (mSpdySession) michael@0: canReuse = mSpdySession->CanReuse(); michael@0: else michael@0: canReuse = IsKeepAlive(); michael@0: michael@0: canReuse = canReuse && (IdleTime() < mIdleTimeout) && IsAlive(); michael@0: michael@0: // An idle persistent connection should not have data waiting to be read michael@0: // before a request is sent. Data here is likely a 408 timeout response michael@0: // which we would deal with later on through the restart logic, but that michael@0: // path is more expensive than just closing the socket now. michael@0: michael@0: uint64_t dataSize; michael@0: if (canReuse && mSocketIn && !mUsingSpdyVersion && mHttp1xTransactionCount && michael@0: NS_SUCCEEDED(mSocketIn->Available(&dataSize)) && dataSize) { michael@0: LOG(("nsHttpConnection::CanReuse %p %s" michael@0: "Socket not reusable because read data pending (%llu) on it.\n", michael@0: this, mConnInfo->Host(), dataSize)); michael@0: canReuse = false; michael@0: } michael@0: return canReuse; michael@0: } michael@0: michael@0: bool michael@0: nsHttpConnection::CanDirectlyActivate() michael@0: { michael@0: // return true if a new transaction can be addded to ths connection at any michael@0: // time through Activate(). In practice this means this is a healthy SPDY michael@0: // connection with room for more concurrent streams. michael@0: michael@0: return UsingSpdy() && CanReuse() && michael@0: mSpdySession && mSpdySession->RoomForMoreStreams(); michael@0: } michael@0: michael@0: PRIntervalTime michael@0: nsHttpConnection::IdleTime() michael@0: { michael@0: return mSpdySession ? michael@0: mSpdySession->IdleTime() : (PR_IntervalNow() - mLastReadTime); michael@0: } michael@0: michael@0: // returns the number of seconds left before the allowable idle period michael@0: // expires, or 0 if the period has already expied. michael@0: uint32_t michael@0: nsHttpConnection::TimeToLive() michael@0: { michael@0: if (IdleTime() >= mIdleTimeout) michael@0: return 0; michael@0: uint32_t timeToLive = PR_IntervalToSeconds(mIdleTimeout - IdleTime()); michael@0: michael@0: // a positive amount of time can be rounded to 0. Because 0 is used michael@0: // as the expiration signal, round all values from 0 to 1 up to 1. michael@0: if (!timeToLive) michael@0: timeToLive = 1; michael@0: return timeToLive; michael@0: } michael@0: michael@0: bool michael@0: nsHttpConnection::IsAlive() michael@0: { michael@0: if (!mSocketTransport) michael@0: return false; michael@0: michael@0: // SocketTransport::IsAlive can run the SSL state machine, so make sure michael@0: // the NPN options are set before that happens. michael@0: SetupSSL(mTransactionCaps); michael@0: michael@0: bool alive; michael@0: nsresult rv = mSocketTransport->IsAlive(&alive); michael@0: if (NS_FAILED(rv)) michael@0: alive = false; michael@0: michael@0: //#define TEST_RESTART_LOGIC michael@0: #ifdef TEST_RESTART_LOGIC michael@0: if (!alive) { michael@0: LOG(("pretending socket is still alive to test restart logic\n")); michael@0: alive = true; michael@0: } michael@0: #endif michael@0: michael@0: return alive; michael@0: } michael@0: michael@0: bool michael@0: nsHttpConnection::SupportsPipelining(nsHttpResponseHead *responseHead) michael@0: { michael@0: // SPDY supports infinite parallelism, so no need to pipeline. michael@0: if (mUsingSpdyVersion) michael@0: return false; michael@0: michael@0: // assuming connection is HTTP/1.1 with keep-alive enabled michael@0: if (mConnInfo->UsingHttpProxy() && !mConnInfo->UsingConnect()) { michael@0: // XXX check for bad proxy servers... michael@0: return true; michael@0: } michael@0: michael@0: // check for bad origin servers michael@0: const char *val = responseHead->PeekHeader(nsHttp::Server); michael@0: michael@0: // If there is no server header we will assume it should not be banned michael@0: // as facebook and some other prominent sites do this michael@0: if (!val) michael@0: return true; michael@0: michael@0: // The blacklist is indexed by the first character. All of these servers are michael@0: // known to return their identifier as the first thing in the server string, michael@0: // so we can do a leading match. michael@0: michael@0: static const char *bad_servers[26][6] = { michael@0: { nullptr }, { nullptr }, { nullptr }, { nullptr }, // a - d michael@0: { "EFAServer/", nullptr }, // e michael@0: { nullptr }, { nullptr }, { nullptr }, { nullptr }, // f - i michael@0: { nullptr }, { nullptr }, { nullptr }, // j - l michael@0: { "Microsoft-IIS/4.", "Microsoft-IIS/5.", nullptr }, // m michael@0: { "Netscape-Enterprise/3.", "Netscape-Enterprise/4.", michael@0: "Netscape-Enterprise/5.", "Netscape-Enterprise/6.", nullptr }, // n michael@0: { nullptr }, { nullptr }, { nullptr }, { nullptr }, // o - r michael@0: { nullptr }, { nullptr }, { nullptr }, { nullptr }, // s - v michael@0: { "WebLogic 3.", "WebLogic 4.","WebLogic 5.", "WebLogic 6.", michael@0: "Winstone Servlet Engine v0.", nullptr }, // w michael@0: { nullptr }, { nullptr }, { nullptr } // x - z michael@0: }; michael@0: michael@0: int index = val[0] - 'A'; // the whole table begins with capital letters michael@0: if ((index >= 0) && (index <= 25)) michael@0: { michael@0: for (int i = 0; bad_servers[index][i] != nullptr; i++) { michael@0: if (!PL_strncmp (val, bad_servers[index][i], strlen (bad_servers[index][i]))) { michael@0: LOG(("looks like this server does not support pipelining")); michael@0: gHttpHandler->ConnMgr()->PipelineFeedbackInfo( michael@0: mConnInfo, nsHttpConnectionMgr::RedBannedServer, this , 0); michael@0: return false; michael@0: } michael@0: } michael@0: } michael@0: michael@0: // ok, let's allow pipelining to this server michael@0: return true; michael@0: } michael@0: michael@0: //---------------------------------------------------------------------------- michael@0: // nsHttpConnection::nsAHttpConnection compatible methods michael@0: //---------------------------------------------------------------------------- michael@0: michael@0: nsresult michael@0: nsHttpConnection::OnHeadersAvailable(nsAHttpTransaction *trans, michael@0: nsHttpRequestHead *requestHead, michael@0: nsHttpResponseHead *responseHead, michael@0: bool *reset) michael@0: { michael@0: LOG(("nsHttpConnection::OnHeadersAvailable [this=%p trans=%p response-head=%p]\n", michael@0: this, trans, responseHead)); michael@0: michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: NS_ENSURE_ARG_POINTER(trans); michael@0: MOZ_ASSERT(responseHead, "No response head?"); michael@0: michael@0: // we won't change our keep-alive policy unless the server has explicitly michael@0: // told us to do so. michael@0: michael@0: // inspect the connection headers for keep-alive info provided the michael@0: // transaction completed successfully. In the case of a non-sensical close michael@0: // and keep-alive favor the close out of conservatism. michael@0: michael@0: bool explicitKeepAlive = false; michael@0: bool explicitClose = responseHead->HasHeaderValue(nsHttp::Connection, "close") || michael@0: responseHead->HasHeaderValue(nsHttp::Proxy_Connection, "close"); michael@0: if (!explicitClose) michael@0: explicitKeepAlive = responseHead->HasHeaderValue(nsHttp::Connection, "keep-alive") || michael@0: responseHead->HasHeaderValue(nsHttp::Proxy_Connection, "keep-alive"); michael@0: michael@0: // deal with 408 Server Timeouts michael@0: uint16_t responseStatus = responseHead->Status(); michael@0: static const PRIntervalTime k1000ms = PR_MillisecondsToInterval(1000); michael@0: if (responseStatus == 408) { michael@0: // If this error could be due to a persistent connection reuse then michael@0: // we pass an error code of NS_ERROR_NET_RESET to michael@0: // trigger the transaction 'restart' mechanism. We tell it to reset its michael@0: // response headers so that it will be ready to receive the new response. michael@0: if (mIsReused && ((PR_IntervalNow() - mLastWriteTime) < k1000ms)) { michael@0: Close(NS_ERROR_NET_RESET); michael@0: *reset = true; michael@0: return NS_OK; michael@0: } michael@0: michael@0: // timeouts that are not caused by persistent connection reuse should michael@0: // not be retried for browser compatibility reasons. bug 907800. The michael@0: // server driven close is implicit in the 408. michael@0: explicitClose = true; michael@0: explicitKeepAlive = false; michael@0: } michael@0: michael@0: // reset to default (the server may have changed since we last checked) michael@0: mSupportsPipelining = false; michael@0: michael@0: if ((responseHead->Version() < NS_HTTP_VERSION_1_1) || michael@0: (requestHead->Version() < NS_HTTP_VERSION_1_1)) { michael@0: // HTTP/1.0 connections are by default NOT persistent michael@0: if (explicitKeepAlive) michael@0: mKeepAlive = true; michael@0: else michael@0: mKeepAlive = false; michael@0: michael@0: // We need at least version 1.1 to use pipelines michael@0: gHttpHandler->ConnMgr()->PipelineFeedbackInfo( michael@0: mConnInfo, nsHttpConnectionMgr::RedVersionTooLow, this, 0); michael@0: } michael@0: else { michael@0: // HTTP/1.1 connections are by default persistent michael@0: if (explicitClose) { michael@0: mKeepAlive = false; michael@0: michael@0: // persistent connections are required for pipelining to work - if michael@0: // this close was not pre-announced then generate the negative michael@0: // BadExplicitClose feedback michael@0: if (mRemainingConnectionUses > 1) michael@0: gHttpHandler->ConnMgr()->PipelineFeedbackInfo( michael@0: mConnInfo, nsHttpConnectionMgr::BadExplicitClose, this, 0); michael@0: } michael@0: else { michael@0: mKeepAlive = true; michael@0: michael@0: // Do not support pipelining when we are establishing michael@0: // an SSL tunnel though an HTTP proxy. Pipelining support michael@0: // determination must be based on comunication with the michael@0: // target server in this case. See bug 422016 for futher michael@0: // details. michael@0: if (!mProxyConnectStream) michael@0: mSupportsPipelining = SupportsPipelining(responseHead); michael@0: } michael@0: } michael@0: mKeepAliveMask = mKeepAlive; michael@0: michael@0: // Update the pipelining status in the connection info object michael@0: // and also read it back. It is possible the ci status is michael@0: // locked to false if pipelining has been banned on this ci due to michael@0: // some kind of observed flaky behavior michael@0: if (mSupportsPipelining) { michael@0: // report the pipelining-compatible header to the connection manager michael@0: // as positive feedback. This will undo 1 penalty point the host michael@0: // may have accumulated in the past. michael@0: michael@0: gHttpHandler->ConnMgr()->PipelineFeedbackInfo( michael@0: mConnInfo, nsHttpConnectionMgr::NeutralExpectedOK, this, 0); michael@0: michael@0: mSupportsPipelining = michael@0: gHttpHandler->ConnMgr()->SupportsPipelining(mConnInfo); michael@0: } michael@0: michael@0: // If this connection is reserved for revalidations and we are michael@0: // receiving a document that failed revalidation then switch the michael@0: // classification to general to avoid pipelining more revalidations behind michael@0: // it. michael@0: if (mClassification == nsAHttpTransaction::CLASS_REVALIDATION && michael@0: responseStatus != 304) { michael@0: mClassification = nsAHttpTransaction::CLASS_GENERAL; michael@0: } michael@0: michael@0: // if this connection is persistent, then the server may send a "Keep-Alive" michael@0: // header specifying the maximum number of times the connection can be michael@0: // reused as well as the maximum amount of time the connection can be idle michael@0: // before the server will close it. we ignore the max reuse count, because michael@0: // a "keep-alive" connection is by definition capable of being reused, and michael@0: // we only care about being able to reuse it once. if a timeout is not michael@0: // specified then we use our advertized timeout value. michael@0: bool foundKeepAliveMax = false; michael@0: if (mKeepAlive) { michael@0: const char *val = responseHead->PeekHeader(nsHttp::Keep_Alive); michael@0: michael@0: if (!mUsingSpdyVersion) { michael@0: const char *cp = PL_strcasestr(val, "timeout="); michael@0: if (cp) michael@0: mIdleTimeout = PR_SecondsToInterval((uint32_t) atoi(cp + 8)); michael@0: else michael@0: mIdleTimeout = gHttpHandler->IdleTimeout(); michael@0: michael@0: cp = PL_strcasestr(val, "max="); michael@0: if (cp) { michael@0: int val = atoi(cp + 4); michael@0: if (val > 0) { michael@0: foundKeepAliveMax = true; michael@0: mRemainingConnectionUses = static_cast(val); michael@0: } michael@0: } michael@0: } michael@0: else { michael@0: mIdleTimeout = gHttpHandler->SpdyTimeout(); michael@0: } michael@0: michael@0: LOG(("Connection can be reused [this=%p idle-timeout=%usec]\n", michael@0: this, PR_IntervalToSeconds(mIdleTimeout))); michael@0: } michael@0: michael@0: if (!foundKeepAliveMax && mRemainingConnectionUses && !mUsingSpdyVersion) michael@0: --mRemainingConnectionUses; michael@0: michael@0: // If we're doing a proxy connect, we need to check whether or not michael@0: // it was successful. If so, we have to reset the transaction and step-up michael@0: // the socket connection if using SSL. Finally, we have to wake up the michael@0: // socket write request. michael@0: if (mProxyConnectStream) { michael@0: MOZ_ASSERT(!mUsingSpdyVersion, michael@0: "SPDY NPN Complete while using proxy connect stream"); michael@0: mProxyConnectStream = 0; michael@0: if (responseStatus == 200) { michael@0: LOG(("proxy CONNECT succeeded! ssl=%s\n", michael@0: mConnInfo->UsingSSL() ? "true" :"false")); michael@0: *reset = true; michael@0: nsresult rv; michael@0: if (mConnInfo->UsingSSL()) { michael@0: rv = ProxyStartSSL(); michael@0: if (NS_FAILED(rv)) // XXX need to handle this for real michael@0: LOG(("ProxyStartSSL failed [rv=%x]\n", rv)); michael@0: } michael@0: mCompletedProxyConnect = true; michael@0: mProxyConnectInProgress = false; michael@0: rv = mSocketOut->AsyncWait(this, 0, 0, nullptr); michael@0: // XXX what if this fails -- need to handle this error michael@0: MOZ_ASSERT(NS_SUCCEEDED(rv), "mSocketOut->AsyncWait failed"); michael@0: } michael@0: else { michael@0: LOG(("proxy CONNECT failed! ssl=%s\n", michael@0: mConnInfo->UsingSSL() ? "true" :"false")); michael@0: mTransaction->SetProxyConnectFailed(); michael@0: } michael@0: } michael@0: michael@0: const char *upgradeReq = requestHead->PeekHeader(nsHttp::Upgrade); michael@0: // Don't use persistent connection for Upgrade unless there's an auth failure: michael@0: // some proxies expect to see auth response on persistent connection. michael@0: if (upgradeReq && responseStatus != 401 && responseStatus != 407) { michael@0: LOG(("HTTP Upgrade in play - disable keepalive\n")); michael@0: DontReuse(); michael@0: } michael@0: michael@0: if (responseStatus == 101) { michael@0: const char *upgradeResp = responseHead->PeekHeader(nsHttp::Upgrade); michael@0: if (!upgradeReq || !upgradeResp || michael@0: !nsHttp::FindToken(upgradeResp, upgradeReq, michael@0: HTTP_HEADER_VALUE_SEPS)) { michael@0: LOG(("HTTP 101 Upgrade header mismatch req = %s, resp = %s\n", michael@0: upgradeReq, upgradeResp)); michael@0: Close(NS_ERROR_ABORT); michael@0: } michael@0: else { michael@0: LOG(("HTTP Upgrade Response to %s\n", upgradeResp)); michael@0: } michael@0: } michael@0: michael@0: mLastHttpResponseVersion = responseHead->Version(); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: bool michael@0: nsHttpConnection::IsReused() michael@0: { michael@0: if (mIsReused) michael@0: return true; michael@0: if (!mConsiderReusedAfterInterval) michael@0: return false; michael@0: michael@0: // ReusedAfter allows a socket to be consider reused only after a certain michael@0: // interval of time has passed michael@0: return (PR_IntervalNow() - mConsiderReusedAfterEpoch) >= michael@0: mConsiderReusedAfterInterval; michael@0: } michael@0: michael@0: void michael@0: nsHttpConnection::SetIsReusedAfter(uint32_t afterMilliseconds) michael@0: { michael@0: mConsiderReusedAfterEpoch = PR_IntervalNow(); michael@0: mConsiderReusedAfterInterval = PR_MillisecondsToInterval(afterMilliseconds); michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::TakeTransport(nsISocketTransport **aTransport, michael@0: nsIAsyncInputStream **aInputStream, michael@0: nsIAsyncOutputStream **aOutputStream) michael@0: { michael@0: if (mUsingSpdyVersion) michael@0: return NS_ERROR_FAILURE; michael@0: if (mTransaction && !mTransaction->IsDone()) michael@0: return NS_ERROR_IN_PROGRESS; michael@0: if (!(mSocketTransport && mSocketIn && mSocketOut)) michael@0: return NS_ERROR_NOT_INITIALIZED; michael@0: michael@0: if (mInputOverflow) michael@0: mSocketIn = mInputOverflow.forget(); michael@0: michael@0: // Change TCP Keepalive frequency to long-lived if currently short-lived. michael@0: if (mTCPKeepaliveConfig == kTCPKeepaliveShortLivedConfig) { michael@0: if (mTCPKeepaliveTransitionTimer) { michael@0: mTCPKeepaliveTransitionTimer->Cancel(); michael@0: mTCPKeepaliveTransitionTimer = nullptr; michael@0: } michael@0: nsresult rv = StartLongLivedTCPKeepalives(); michael@0: LOG(("nsHttpConnection::TakeTransport [%p] calling " michael@0: "StartLongLivedTCPKeepalives", this)); michael@0: if (NS_WARN_IF(NS_FAILED(rv))) { michael@0: LOG(("nsHttpConnection::TakeTransport [%p] " michael@0: "StartLongLivedTCPKeepalives failed rv[0x%x]", this, rv)); michael@0: } michael@0: } michael@0: michael@0: NS_IF_ADDREF(*aTransport = mSocketTransport); michael@0: NS_IF_ADDREF(*aInputStream = mSocketIn); michael@0: NS_IF_ADDREF(*aOutputStream = mSocketOut); michael@0: michael@0: mSocketTransport->SetSecurityCallbacks(nullptr); michael@0: mSocketTransport->SetEventSink(nullptr, nullptr); michael@0: mSocketTransport = nullptr; michael@0: mSocketIn = nullptr; michael@0: mSocketOut = nullptr; michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: uint32_t michael@0: nsHttpConnection::ReadTimeoutTick(PRIntervalTime now) michael@0: { michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: michael@0: // make sure timer didn't tick before Activate() michael@0: if (!mTransaction) michael@0: return UINT32_MAX; michael@0: michael@0: // Spdy implements some timeout handling using the SPDY ping frame. michael@0: if (mSpdySession) { michael@0: return mSpdySession->ReadTimeoutTick(now); michael@0: } michael@0: michael@0: uint32_t nextTickAfter = UINT32_MAX; michael@0: // Timeout if the response is taking too long to arrive. michael@0: if (mResponseTimeoutEnabled) { michael@0: NS_WARN_IF_FALSE(gHttpHandler->ResponseTimeoutEnabled(), michael@0: "Timing out a response, but response timeout is disabled!"); michael@0: michael@0: PRIntervalTime initialResponseDelta = now - mLastWriteTime; michael@0: michael@0: if (initialResponseDelta > mTransaction->ResponseTimeout()) { michael@0: LOG(("canceling transaction: no response for %ums: timeout is %dms\n", michael@0: PR_IntervalToMilliseconds(initialResponseDelta), michael@0: PR_IntervalToMilliseconds(mTransaction->ResponseTimeout()))); michael@0: michael@0: mResponseTimeoutEnabled = false; michael@0: michael@0: // This will also close the connection michael@0: CloseTransaction(mTransaction, NS_ERROR_NET_TIMEOUT); michael@0: return UINT32_MAX; michael@0: } michael@0: nextTickAfter = PR_IntervalToSeconds(mTransaction->ResponseTimeout()) - michael@0: PR_IntervalToSeconds(initialResponseDelta); michael@0: nextTickAfter = std::max(nextTickAfter, 1U); michael@0: } michael@0: michael@0: if (!gHttpHandler->GetPipelineRescheduleOnTimeout()) michael@0: return nextTickAfter; michael@0: michael@0: PRIntervalTime delta = now - mLastReadTime; michael@0: michael@0: // we replicate some of the checks both here and in OnSocketReadable() as michael@0: // they will be discovered under different conditions. The ones here michael@0: // will generally be discovered if we are totally hung and OSR does michael@0: // not get called at all, however OSR discovers them with lower latency michael@0: // if the issue is just very slow (but not stalled) reading. michael@0: // michael@0: // Right now we only take action if pipelining is involved, but this would michael@0: // be the place to add general read timeout handling if it is desired. michael@0: michael@0: uint32_t pipelineDepth = mTransaction->PipelineDepth(); michael@0: if (pipelineDepth > 1) { michael@0: // if we have pipelines outstanding (not just an idle connection) michael@0: // then get a fairly quick tick michael@0: nextTickAfter = 1; michael@0: } michael@0: michael@0: if (delta >= gHttpHandler->GetPipelineRescheduleTimeout() && michael@0: pipelineDepth > 1) { michael@0: michael@0: // this just reschedules blocked transactions. no transaction michael@0: // is aborted completely. michael@0: LOG(("cancelling pipeline due to a %ums stall - depth %d\n", michael@0: PR_IntervalToMilliseconds(delta), pipelineDepth)); michael@0: michael@0: nsHttpPipeline *pipeline = mTransaction->QueryPipeline(); michael@0: MOZ_ASSERT(pipeline, "pipelinedepth > 1 without pipeline"); michael@0: // code this defensively for the moment and check for null in opt build michael@0: // This will reschedule blocked members of the pipeline, but the michael@0: // blocking transaction (i.e. response 0) will not be changed. michael@0: if (pipeline) { michael@0: pipeline->CancelPipeline(NS_ERROR_NET_TIMEOUT); michael@0: LOG(("Rescheduling the head of line blocked members of a pipeline " michael@0: "because reschedule-timeout idle interval exceeded")); michael@0: } michael@0: } michael@0: michael@0: if (delta < gHttpHandler->GetPipelineTimeout()) michael@0: return nextTickAfter; michael@0: michael@0: if (pipelineDepth <= 1 && !mTransaction->PipelinePosition()) michael@0: return nextTickAfter; michael@0: michael@0: // nothing has transpired on this pipelined socket for many michael@0: // seconds. Call that a total stall and close the transaction. michael@0: // There is a chance the transaction will be restarted again michael@0: // depending on its state.. that will come back araound michael@0: // without pipelining on, so this won't loop. michael@0: michael@0: LOG(("canceling transaction stalled for %ums on a pipeline " michael@0: "of depth %d and scheduled originally at pos %d\n", michael@0: PR_IntervalToMilliseconds(delta), michael@0: pipelineDepth, mTransaction->PipelinePosition())); michael@0: michael@0: // This will also close the connection michael@0: CloseTransaction(mTransaction, NS_ERROR_NET_TIMEOUT); michael@0: return UINT32_MAX; michael@0: } michael@0: michael@0: void michael@0: nsHttpConnection::UpdateTCPKeepalive(nsITimer *aTimer, void *aClosure) michael@0: { michael@0: MOZ_ASSERT(aTimer); michael@0: MOZ_ASSERT(aClosure); michael@0: michael@0: nsHttpConnection *self = static_cast(aClosure); michael@0: michael@0: if (NS_WARN_IF(self->mUsingSpdyVersion)) { michael@0: return; michael@0: } michael@0: michael@0: // Do not reduce keepalive probe frequency for idle connections. michael@0: if (self->mIdleMonitoring) { michael@0: return; michael@0: } michael@0: michael@0: nsresult rv = self->StartLongLivedTCPKeepalives(); michael@0: if (NS_WARN_IF(NS_FAILED(rv))) { michael@0: LOG(("nsHttpConnection::UpdateTCPKeepalive [%p] " michael@0: "StartLongLivedTCPKeepalives failed rv[0x%x]", michael@0: self, rv)); michael@0: } michael@0: } michael@0: michael@0: void michael@0: nsHttpConnection::GetSecurityInfo(nsISupports **secinfo) michael@0: { michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: michael@0: if (mSocketTransport) { michael@0: if (NS_FAILED(mSocketTransport->GetSecurityInfo(secinfo))) michael@0: *secinfo = nullptr; michael@0: } michael@0: } michael@0: michael@0: void michael@0: nsHttpConnection::SetSecurityCallbacks(nsIInterfaceRequestor* aCallbacks) michael@0: { michael@0: MutexAutoLock lock(mCallbacksLock); michael@0: // This is called both on and off the main thread. For JS-implemented michael@0: // callbacks, we requires that the call happen on the main thread, but michael@0: // for C++-implemented callbacks we don't care. Use a pointer holder with michael@0: // strict checking disabled. michael@0: mCallbacks = new nsMainThreadPtrHolder(aCallbacks, false); michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::PushBack(const char *data, uint32_t length) michael@0: { michael@0: LOG(("nsHttpConnection::PushBack [this=%p, length=%d]\n", this, length)); michael@0: michael@0: if (mInputOverflow) { michael@0: NS_ERROR("nsHttpConnection::PushBack only one buffer supported"); michael@0: return NS_ERROR_UNEXPECTED; michael@0: } michael@0: michael@0: mInputOverflow = new nsPreloadedStream(mSocketIn, data, length); michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::ResumeSend() michael@0: { michael@0: LOG(("nsHttpConnection::ResumeSend [this=%p]\n", this)); michael@0: michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: michael@0: if (mSocketOut) michael@0: return mSocketOut->AsyncWait(this, 0, 0, nullptr); michael@0: michael@0: NS_NOTREACHED("no socket output stream"); michael@0: return NS_ERROR_UNEXPECTED; michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::ResumeRecv() michael@0: { michael@0: LOG(("nsHttpConnection::ResumeRecv [this=%p]\n", this)); michael@0: michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: michael@0: // the mLastReadTime timestamp is used for finding slowish readers michael@0: // and can be pretty sensitive. For that reason we actually reset it michael@0: // when we ask to read (resume recv()) so that when we get called back michael@0: // with actual read data in OnSocketReadable() we are only measuring michael@0: // the latency between those two acts and not all the processing that michael@0: // may get done before the ResumeRecv() call michael@0: mLastReadTime = PR_IntervalNow(); michael@0: michael@0: if (mSocketIn) michael@0: return mSocketIn->AsyncWait(this, 0, 0, nullptr); michael@0: michael@0: NS_NOTREACHED("no socket input stream"); michael@0: return NS_ERROR_UNEXPECTED; michael@0: } michael@0: michael@0: michael@0: class nsHttpConnectionForceRecv : public nsRunnable michael@0: { michael@0: public: michael@0: nsHttpConnectionForceRecv(nsHttpConnection *aConn) michael@0: : mConn(aConn) {} michael@0: michael@0: NS_IMETHOD Run() michael@0: { michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: michael@0: if (!mConn->mSocketIn) michael@0: return NS_OK; michael@0: return mConn->OnInputStreamReady(mConn->mSocketIn); michael@0: } michael@0: private: michael@0: nsRefPtr mConn; michael@0: }; michael@0: michael@0: // trigger an asynchronous read michael@0: nsresult michael@0: nsHttpConnection::ForceRecv() michael@0: { michael@0: LOG(("nsHttpConnection::ForceRecv [this=%p]\n", this)); michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: michael@0: return NS_DispatchToCurrentThread(new nsHttpConnectionForceRecv(this)); michael@0: } michael@0: michael@0: void michael@0: nsHttpConnection::BeginIdleMonitoring() michael@0: { michael@0: LOG(("nsHttpConnection::BeginIdleMonitoring [this=%p]\n", this)); michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: MOZ_ASSERT(!mTransaction, "BeginIdleMonitoring() while active"); michael@0: MOZ_ASSERT(!mUsingSpdyVersion, "Idle monitoring of spdy not allowed"); michael@0: michael@0: LOG(("Entering Idle Monitoring Mode [this=%p]", this)); michael@0: mIdleMonitoring = true; michael@0: if (mSocketIn) michael@0: mSocketIn->AsyncWait(this, 0, 0, nullptr); michael@0: } michael@0: michael@0: void michael@0: nsHttpConnection::EndIdleMonitoring() michael@0: { michael@0: LOG(("nsHttpConnection::EndIdleMonitoring [this=%p]\n", this)); michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: MOZ_ASSERT(!mTransaction, "EndIdleMonitoring() while active"); michael@0: michael@0: if (mIdleMonitoring) { michael@0: LOG(("Leaving Idle Monitoring Mode [this=%p]", this)); michael@0: mIdleMonitoring = false; michael@0: if (mSocketIn) michael@0: mSocketIn->AsyncWait(nullptr, 0, 0, nullptr); michael@0: } michael@0: } michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: // nsHttpConnection michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: void michael@0: nsHttpConnection::CloseTransaction(nsAHttpTransaction *trans, nsresult reason) michael@0: { michael@0: LOG(("nsHttpConnection::CloseTransaction[this=%p trans=%x reason=%x]\n", michael@0: this, trans, reason)); michael@0: michael@0: MOZ_ASSERT(trans == mTransaction, "wrong transaction"); michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: michael@0: if (mCurrentBytesRead > mMaxBytesRead) michael@0: mMaxBytesRead = mCurrentBytesRead; michael@0: michael@0: // mask this error code because its not a real error. michael@0: if (reason == NS_BASE_STREAM_CLOSED) michael@0: reason = NS_OK; michael@0: michael@0: if (mUsingSpdyVersion) { michael@0: DontReuse(); michael@0: // if !mSpdySession then mUsingSpdyVersion must be false for canreuse() michael@0: mUsingSpdyVersion = 0; michael@0: mSpdySession = nullptr; michael@0: } michael@0: michael@0: if (mTransaction) { michael@0: mHttp1xTransactionCount += mTransaction->Http1xTransactionCount(); michael@0: michael@0: mTransaction->Close(reason); michael@0: mTransaction = nullptr; michael@0: } michael@0: michael@0: { michael@0: MutexAutoLock lock(mCallbacksLock); michael@0: mCallbacks = nullptr; michael@0: } michael@0: michael@0: if (NS_FAILED(reason)) michael@0: Close(reason); michael@0: michael@0: // flag the connection as reused here for convenience sake. certainly michael@0: // it might be going away instead ;-) michael@0: mIsReused = true; michael@0: } michael@0: michael@0: NS_METHOD michael@0: nsHttpConnection::ReadFromStream(nsIInputStream *input, michael@0: void *closure, michael@0: const char *buf, michael@0: uint32_t offset, michael@0: uint32_t count, michael@0: uint32_t *countRead) michael@0: { michael@0: // thunk for nsIInputStream instance michael@0: nsHttpConnection *conn = (nsHttpConnection *) closure; michael@0: return conn->OnReadSegment(buf, count, countRead); michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::OnReadSegment(const char *buf, michael@0: uint32_t count, michael@0: uint32_t *countRead) michael@0: { michael@0: if (count == 0) { michael@0: // some ReadSegments implementations will erroneously call the writer michael@0: // to consume 0 bytes worth of data. we must protect against this case michael@0: // or else we'd end up closing the socket prematurely. michael@0: NS_ERROR("bad ReadSegments implementation"); michael@0: return NS_ERROR_FAILURE; // stop iterating michael@0: } michael@0: michael@0: nsresult rv = mSocketOut->Write(buf, count, countRead); michael@0: if (NS_FAILED(rv)) michael@0: mSocketOutCondition = rv; michael@0: else if (*countRead == 0) michael@0: mSocketOutCondition = NS_BASE_STREAM_CLOSED; michael@0: else { michael@0: mLastWriteTime = PR_IntervalNow(); michael@0: mSocketOutCondition = NS_OK; // reset condition michael@0: if (!mProxyConnectInProgress) michael@0: mTotalBytesWritten += *countRead; michael@0: } michael@0: michael@0: return mSocketOutCondition; michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::OnSocketWritable() michael@0: { michael@0: LOG(("nsHttpConnection::OnSocketWritable [this=%p] host=%s\n", michael@0: this, mConnInfo->Host())); michael@0: michael@0: nsresult rv; michael@0: uint32_t n; michael@0: bool again = true; michael@0: michael@0: do { michael@0: mSocketOutCondition = NS_OK; michael@0: michael@0: // If we're doing a proxy connect, then we need to bypass calling into michael@0: // the transaction. michael@0: // michael@0: // NOTE: this code path can't be shared since the transaction doesn't michael@0: // implement nsIInputStream. doing so is not worth the added cost of michael@0: // extra indirections during normal reading. michael@0: // michael@0: if (mProxyConnectStream) { michael@0: LOG((" writing CONNECT request stream\n")); michael@0: rv = mProxyConnectStream->ReadSegments(ReadFromStream, this, michael@0: nsIOService::gDefaultSegmentSize, michael@0: &n); michael@0: } michael@0: else if (!EnsureNPNComplete()) { michael@0: // When SPDY is disabled this branch is not executed because Activate() michael@0: // sets mNPNComplete to true in that case. michael@0: michael@0: // We are ready to proceed with SSL but the handshake is not done. michael@0: // When using NPN to negotiate between HTTPS and SPDY, we need to michael@0: // see the results of the handshake to know what bytes to send, so michael@0: // we cannot proceed with the request headers. michael@0: michael@0: rv = NS_OK; michael@0: mSocketOutCondition = NS_BASE_STREAM_WOULD_BLOCK; michael@0: n = 0; michael@0: } michael@0: else { michael@0: if (!mReportedSpdy) { michael@0: mReportedSpdy = true; michael@0: gHttpHandler->ConnMgr()->ReportSpdyConnection(this, mEverUsedSpdy); michael@0: } michael@0: michael@0: LOG((" writing transaction request stream\n")); michael@0: mProxyConnectInProgress = false; michael@0: rv = mTransaction->ReadSegments(this, nsIOService::gDefaultSegmentSize, &n); michael@0: } michael@0: michael@0: LOG((" ReadSegments returned [rv=%x read=%u sock-cond=%x]\n", michael@0: rv, n, mSocketOutCondition)); michael@0: michael@0: // XXX some streams return NS_BASE_STREAM_CLOSED to indicate EOF. michael@0: if (rv == NS_BASE_STREAM_CLOSED && !mTransaction->IsDone()) { michael@0: rv = NS_OK; michael@0: n = 0; michael@0: } michael@0: michael@0: if (NS_FAILED(rv)) { michael@0: // if the transaction didn't want to write any more data, then michael@0: // wait for the transaction to call ResumeSend. michael@0: if (rv == NS_BASE_STREAM_WOULD_BLOCK) michael@0: rv = NS_OK; michael@0: again = false; michael@0: } michael@0: else if (NS_FAILED(mSocketOutCondition)) { michael@0: if (mSocketOutCondition == NS_BASE_STREAM_WOULD_BLOCK) michael@0: rv = mSocketOut->AsyncWait(this, 0, 0, nullptr); // continue writing michael@0: else michael@0: rv = mSocketOutCondition; michael@0: again = false; michael@0: } michael@0: else if (n == 0) { michael@0: rv = NS_OK; michael@0: michael@0: if (mTransaction) { // in case the ReadSegments stack called CloseTransaction() michael@0: // michael@0: // at this point we've written out the entire transaction, and now we michael@0: // must wait for the server's response. we manufacture a status message michael@0: // here to reflect the fact that we are waiting. this message will be michael@0: // trumped (overwritten) if the server responds quickly. michael@0: // michael@0: mTransaction->OnTransportStatus(mSocketTransport, michael@0: NS_NET_STATUS_WAITING_FOR, michael@0: 0); michael@0: michael@0: rv = ResumeRecv(); // start reading michael@0: } michael@0: again = false; michael@0: } michael@0: // write more to the socket until error or end-of-request... michael@0: } while (again); michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::OnWriteSegment(char *buf, michael@0: uint32_t count, michael@0: uint32_t *countWritten) michael@0: { michael@0: if (count == 0) { michael@0: // some WriteSegments implementations will erroneously call the reader michael@0: // to provide 0 bytes worth of data. we must protect against this case michael@0: // or else we'd end up closing the socket prematurely. michael@0: NS_ERROR("bad WriteSegments implementation"); michael@0: return NS_ERROR_FAILURE; // stop iterating michael@0: } michael@0: michael@0: if (ChaosMode::isActive() && ChaosMode::randomUint32LessThan(2)) { michael@0: // read 1...count bytes michael@0: count = ChaosMode::randomUint32LessThan(count) + 1; michael@0: } michael@0: michael@0: nsresult rv = mSocketIn->Read(buf, count, countWritten); michael@0: if (NS_FAILED(rv)) michael@0: mSocketInCondition = rv; michael@0: else if (*countWritten == 0) michael@0: mSocketInCondition = NS_BASE_STREAM_CLOSED; michael@0: else michael@0: mSocketInCondition = NS_OK; // reset condition michael@0: michael@0: return mSocketInCondition; michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::OnSocketReadable() michael@0: { michael@0: LOG(("nsHttpConnection::OnSocketReadable [this=%p]\n", this)); michael@0: michael@0: PRIntervalTime now = PR_IntervalNow(); michael@0: PRIntervalTime delta = now - mLastReadTime; michael@0: michael@0: // Reset mResponseTimeoutEnabled to stop response timeout checks. michael@0: mResponseTimeoutEnabled = false; michael@0: michael@0: if (mKeepAliveMask && (delta >= mMaxHangTime)) { michael@0: LOG(("max hang time exceeded!\n")); michael@0: // give the handler a chance to create a new persistent connection to michael@0: // this host if we've been busy for too long. michael@0: mKeepAliveMask = false; michael@0: gHttpHandler->ProcessPendingQ(mConnInfo); michael@0: } michael@0: michael@0: // Look for data being sent in bursts with large pauses. If the pauses michael@0: // are caused by server bottlenecks such as think-time, disk i/o, or michael@0: // cpu exhaustion (as opposed to network latency) then we generate negative michael@0: // pipelining feedback to prevent head of line problems michael@0: michael@0: // Reduce the estimate of the time since last read by up to 1 RTT to michael@0: // accommodate exhausted sender TCP congestion windows or minor I/O delays. michael@0: michael@0: if (delta > mRtt) michael@0: delta -= mRtt; michael@0: else michael@0: delta = 0; michael@0: michael@0: static const PRIntervalTime k400ms = PR_MillisecondsToInterval(400); michael@0: michael@0: if (delta >= (mRtt + gHttpHandler->GetPipelineRescheduleTimeout())) { michael@0: LOG(("Read delta ms of %u causing slow read major " michael@0: "event and pipeline cancellation", michael@0: PR_IntervalToMilliseconds(delta))); michael@0: michael@0: gHttpHandler->ConnMgr()->PipelineFeedbackInfo( michael@0: mConnInfo, nsHttpConnectionMgr::BadSlowReadMajor, this, 0); michael@0: michael@0: if (gHttpHandler->GetPipelineRescheduleOnTimeout() && michael@0: mTransaction->PipelineDepth() > 1) { michael@0: nsHttpPipeline *pipeline = mTransaction->QueryPipeline(); michael@0: MOZ_ASSERT(pipeline, "pipelinedepth > 1 without pipeline"); michael@0: // code this defensively for the moment and check for null michael@0: // This will reschedule blocked members of the pipeline, but the michael@0: // blocking transaction (i.e. response 0) will not be changed. michael@0: if (pipeline) { michael@0: pipeline->CancelPipeline(NS_ERROR_NET_TIMEOUT); michael@0: LOG(("Rescheduling the head of line blocked members of a " michael@0: "pipeline because reschedule-timeout idle interval " michael@0: "exceeded")); michael@0: } michael@0: } michael@0: } michael@0: else if (delta > k400ms) { michael@0: gHttpHandler->ConnMgr()->PipelineFeedbackInfo( michael@0: mConnInfo, nsHttpConnectionMgr::BadSlowReadMinor, this, 0); michael@0: } michael@0: michael@0: mLastReadTime = now; michael@0: michael@0: nsresult rv; michael@0: uint32_t n; michael@0: bool again = true; michael@0: michael@0: do { michael@0: if (!mProxyConnectInProgress && !mNPNComplete) { michael@0: // Unless we are setting up a tunnel via CONNECT, prevent reading michael@0: // from the socket until the results of NPN michael@0: // negotiation are known (which is determined from the write path). michael@0: // If the server speaks SPDY it is likely the readable data here is michael@0: // a spdy settings frame and without NPN it would be misinterpreted michael@0: // as HTTP/* michael@0: michael@0: LOG(("nsHttpConnection::OnSocketReadable %p return due to inactive " michael@0: "tunnel setup but incomplete NPN state\n", this)); michael@0: rv = NS_OK; michael@0: break; michael@0: } michael@0: michael@0: rv = mTransaction->WriteSegments(this, nsIOService::gDefaultSegmentSize, &n); michael@0: if (NS_FAILED(rv)) { michael@0: // if the transaction didn't want to take any more data, then michael@0: // wait for the transaction to call ResumeRecv. michael@0: if (rv == NS_BASE_STREAM_WOULD_BLOCK) michael@0: rv = NS_OK; michael@0: again = false; michael@0: } michael@0: else { michael@0: mCurrentBytesRead += n; michael@0: mTotalBytesRead += n; michael@0: if (NS_FAILED(mSocketInCondition)) { michael@0: // continue waiting for the socket if necessary... michael@0: if (mSocketInCondition == NS_BASE_STREAM_WOULD_BLOCK) michael@0: rv = ResumeRecv(); michael@0: else michael@0: rv = mSocketInCondition; michael@0: again = false; michael@0: } michael@0: } michael@0: // read more from the socket until error... michael@0: } while (again); michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::SetupProxyConnect() michael@0: { michael@0: const char *val; michael@0: michael@0: LOG(("nsHttpConnection::SetupProxyConnect [this=%p]\n", this)); michael@0: michael@0: NS_ENSURE_TRUE(!mProxyConnectStream, NS_ERROR_ALREADY_INITIALIZED); michael@0: MOZ_ASSERT(!mUsingSpdyVersion, michael@0: "SPDY NPN Complete while using proxy connect stream"); michael@0: michael@0: nsAutoCString buf; michael@0: nsresult rv = nsHttpHandler::GenerateHostPort( michael@0: nsDependentCString(mConnInfo->Host()), mConnInfo->Port(), buf); michael@0: if (NS_FAILED(rv)) michael@0: return rv; michael@0: michael@0: // CONNECT host:port HTTP/1.1 michael@0: nsHttpRequestHead request; michael@0: request.SetMethod(NS_LITERAL_CSTRING("CONNECT")); michael@0: request.SetVersion(gHttpHandler->HttpVersion()); michael@0: request.SetRequestURI(buf); michael@0: request.SetHeader(nsHttp::User_Agent, gHttpHandler->UserAgent()); michael@0: michael@0: // a CONNECT is always persistent michael@0: request.SetHeader(nsHttp::Proxy_Connection, NS_LITERAL_CSTRING("keep-alive")); michael@0: request.SetHeader(nsHttp::Connection, NS_LITERAL_CSTRING("keep-alive")); michael@0: michael@0: // all HTTP/1.1 requests must include a Host header (even though it michael@0: // may seem redundant in this case; see bug 82388). michael@0: request.SetHeader(nsHttp::Host, buf); michael@0: michael@0: val = mTransaction->RequestHead()->PeekHeader(nsHttp::Proxy_Authorization); michael@0: if (val) { michael@0: // we don't know for sure if this authorization is intended for the michael@0: // SSL proxy, so we add it just in case. michael@0: request.SetHeader(nsHttp::Proxy_Authorization, nsDependentCString(val)); michael@0: } michael@0: michael@0: buf.Truncate(); michael@0: request.Flatten(buf, false); michael@0: buf.AppendLiteral("\r\n"); michael@0: michael@0: return NS_NewCStringInputStream(getter_AddRefs(mProxyConnectStream), buf); michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::StartShortLivedTCPKeepalives() michael@0: { michael@0: if (mUsingSpdyVersion) { michael@0: return NS_OK; michael@0: } michael@0: MOZ_ASSERT(mSocketTransport); michael@0: if (!mSocketTransport) { michael@0: return NS_ERROR_NOT_INITIALIZED; michael@0: } michael@0: michael@0: nsresult rv = NS_OK; michael@0: int32_t idleTimeS = -1; michael@0: int32_t retryIntervalS = -1; michael@0: if (gHttpHandler->TCPKeepaliveEnabledForShortLivedConns()) { michael@0: // Set the idle time. michael@0: idleTimeS = gHttpHandler->GetTCPKeepaliveShortLivedIdleTime(); michael@0: LOG(("nsHttpConnection::StartShortLivedTCPKeepalives[%p] " michael@0: "idle time[%ds].", this, idleTimeS)); michael@0: michael@0: retryIntervalS = michael@0: std::max((int32_t)PR_IntervalToSeconds(mRtt), 1); michael@0: rv = mSocketTransport->SetKeepaliveVals(idleTimeS, retryIntervalS); michael@0: if (NS_WARN_IF(NS_FAILED(rv))) { michael@0: return rv; michael@0: } michael@0: rv = mSocketTransport->SetKeepaliveEnabled(true); michael@0: mTCPKeepaliveConfig = kTCPKeepaliveShortLivedConfig; michael@0: } else { michael@0: rv = mSocketTransport->SetKeepaliveEnabled(false); michael@0: mTCPKeepaliveConfig = kTCPKeepaliveDisabled; michael@0: } michael@0: if (NS_WARN_IF(NS_FAILED(rv))) { michael@0: return rv; michael@0: } michael@0: michael@0: // Start a timer to move to long-lived keepalive config. michael@0: if(!mTCPKeepaliveTransitionTimer) { michael@0: mTCPKeepaliveTransitionTimer = michael@0: do_CreateInstance("@mozilla.org/timer;1"); michael@0: } michael@0: michael@0: if (mTCPKeepaliveTransitionTimer) { michael@0: int32_t time = gHttpHandler->GetTCPKeepaliveShortLivedTime(); michael@0: michael@0: // Adjust |time| to ensure a full set of keepalive probes can be sent michael@0: // at the end of the short-lived phase. michael@0: if (gHttpHandler->TCPKeepaliveEnabledForShortLivedConns()) { michael@0: if (NS_WARN_IF(!gSocketTransportService)) { michael@0: return NS_ERROR_NOT_INITIALIZED; michael@0: } michael@0: int32_t probeCount = -1; michael@0: rv = gSocketTransportService->GetKeepaliveProbeCount(&probeCount); michael@0: if (NS_WARN_IF(NS_FAILED(rv))) { michael@0: return rv; michael@0: } michael@0: if (NS_WARN_IF(probeCount <= 0)) { michael@0: return NS_ERROR_UNEXPECTED; michael@0: } michael@0: // Add time for final keepalive probes, and 2 seconds for a buffer. michael@0: time += ((probeCount) * retryIntervalS) - (time % idleTimeS) + 2; michael@0: } michael@0: mTCPKeepaliveTransitionTimer->InitWithFuncCallback( michael@0: nsHttpConnection::UpdateTCPKeepalive, michael@0: this, michael@0: (uint32_t)time*1000, michael@0: nsITimer::TYPE_ONE_SHOT); michael@0: } else { michael@0: NS_WARNING("nsHttpConnection::StartShortLivedTCPKeepalives failed to " michael@0: "create timer."); michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::StartLongLivedTCPKeepalives() michael@0: { michael@0: MOZ_ASSERT(!mUsingSpdyVersion, "Don't use TCP Keepalive with SPDY!"); michael@0: if (NS_WARN_IF(mUsingSpdyVersion)) { michael@0: return NS_OK; michael@0: } michael@0: MOZ_ASSERT(mSocketTransport); michael@0: if (!mSocketTransport) { michael@0: return NS_ERROR_NOT_INITIALIZED; michael@0: } michael@0: michael@0: nsresult rv = NS_OK; michael@0: if (gHttpHandler->TCPKeepaliveEnabledForLongLivedConns()) { michael@0: // Increase the idle time. michael@0: int32_t idleTimeS = gHttpHandler->GetTCPKeepaliveLongLivedIdleTime(); michael@0: LOG(("nsHttpConnection::StartLongLivedTCPKeepalives[%p] idle time[%ds]", michael@0: this, idleTimeS)); michael@0: michael@0: int32_t retryIntervalS = michael@0: std::max((int32_t)PR_IntervalToSeconds(mRtt), 1); michael@0: rv = mSocketTransport->SetKeepaliveVals(idleTimeS, retryIntervalS); michael@0: if (NS_WARN_IF(NS_FAILED(rv))) { michael@0: return rv; michael@0: } michael@0: michael@0: // Ensure keepalive is enabled, if current status is disabled. michael@0: if (mTCPKeepaliveConfig == kTCPKeepaliveDisabled) { michael@0: rv = mSocketTransport->SetKeepaliveEnabled(true); michael@0: if (NS_WARN_IF(NS_FAILED(rv))) { michael@0: return rv; michael@0: } michael@0: } michael@0: mTCPKeepaliveConfig = kTCPKeepaliveLongLivedConfig; michael@0: } else { michael@0: rv = mSocketTransport->SetKeepaliveEnabled(false); michael@0: mTCPKeepaliveConfig = kTCPKeepaliveDisabled; michael@0: } michael@0: michael@0: if (NS_WARN_IF(NS_FAILED(rv))) { michael@0: return rv; michael@0: } michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult michael@0: nsHttpConnection::DisableTCPKeepalives() michael@0: { michael@0: MOZ_ASSERT(mSocketTransport); michael@0: if (!mSocketTransport) { michael@0: return NS_ERROR_NOT_INITIALIZED; michael@0: } michael@0: LOG(("nsHttpConnection::DisableTCPKeepalives [%p]", this)); michael@0: if (mTCPKeepaliveConfig != kTCPKeepaliveDisabled) { michael@0: nsresult rv = mSocketTransport->SetKeepaliveEnabled(false); michael@0: if (NS_WARN_IF(NS_FAILED(rv))) { michael@0: return rv; michael@0: } michael@0: mTCPKeepaliveConfig = kTCPKeepaliveDisabled; michael@0: } michael@0: if (mTCPKeepaliveTransitionTimer) { michael@0: mTCPKeepaliveTransitionTimer->Cancel(); michael@0: mTCPKeepaliveTransitionTimer = nullptr; michael@0: } michael@0: return NS_OK; michael@0: } michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: // nsHttpConnection::nsISupports michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: NS_IMPL_ISUPPORTS(nsHttpConnection, michael@0: nsIInputStreamCallback, michael@0: nsIOutputStreamCallback, michael@0: nsITransportEventSink, michael@0: nsIInterfaceRequestor) michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: // nsHttpConnection::nsIInputStreamCallback michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: // called on the socket transport thread michael@0: NS_IMETHODIMP michael@0: nsHttpConnection::OnInputStreamReady(nsIAsyncInputStream *in) michael@0: { michael@0: MOZ_ASSERT(in == mSocketIn, "unexpected stream"); michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: michael@0: if (mIdleMonitoring) { michael@0: MOZ_ASSERT(!mTransaction, "Idle Input Event While Active"); michael@0: michael@0: // The only read event that is protocol compliant for an idle connection michael@0: // is an EOF, which we check for with CanReuse(). If the data is michael@0: // something else then just ignore it and suspend checking for EOF - michael@0: // our normal timers or protocol stack are the place to deal with michael@0: // any exception logic. michael@0: michael@0: if (!CanReuse()) { michael@0: LOG(("Server initiated close of idle conn %p\n", this)); michael@0: gHttpHandler->ConnMgr()->CloseIdleConnection(this); michael@0: return NS_OK; michael@0: } michael@0: michael@0: LOG(("Input data on idle conn %p, but not closing yet\n", this)); michael@0: return NS_OK; michael@0: } michael@0: michael@0: // if the transaction was dropped... michael@0: if (!mTransaction) { michael@0: LOG((" no transaction; ignoring event\n")); michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult rv = OnSocketReadable(); michael@0: if (NS_FAILED(rv)) michael@0: CloseTransaction(mTransaction, rv); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: // nsHttpConnection::nsIOutputStreamCallback michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: NS_IMETHODIMP michael@0: nsHttpConnection::OnOutputStreamReady(nsIAsyncOutputStream *out) michael@0: { michael@0: MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread); michael@0: MOZ_ASSERT(out == mSocketOut, "unexpected socket"); michael@0: michael@0: // if the transaction was dropped... michael@0: if (!mTransaction) { michael@0: LOG((" no transaction; ignoring event\n")); michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult rv = OnSocketWritable(); michael@0: if (NS_FAILED(rv)) michael@0: CloseTransaction(mTransaction, rv); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: // nsHttpConnection::nsITransportEventSink michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: NS_IMETHODIMP michael@0: nsHttpConnection::OnTransportStatus(nsITransport *trans, michael@0: nsresult status, michael@0: uint64_t progress, michael@0: uint64_t progressMax) michael@0: { michael@0: if (mTransaction) michael@0: mTransaction->OnTransportStatus(trans, status, progress); michael@0: return NS_OK; michael@0: } michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: // nsHttpConnection::nsIInterfaceRequestor michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: // not called on the socket transport thread michael@0: NS_IMETHODIMP michael@0: nsHttpConnection::GetInterface(const nsIID &iid, void **result) michael@0: { michael@0: // NOTE: This function is only called on the UI thread via sync proxy from michael@0: // the socket transport thread. If that weren't the case, then we'd michael@0: // have to worry about the possibility of mTransaction going away michael@0: // part-way through this function call. See CloseTransaction. michael@0: michael@0: // NOTE - there is a bug here, the call to getinterface is proxied off the michael@0: // nss thread, not the ui thread as the above comment says. So there is michael@0: // indeed a chance of mTransaction going away. bug 615342 michael@0: michael@0: MOZ_ASSERT(PR_GetCurrentThread() != gSocketThread); michael@0: michael@0: nsCOMPtr callbacks; michael@0: { michael@0: MutexAutoLock lock(mCallbacksLock); michael@0: callbacks = mCallbacks; michael@0: } michael@0: if (callbacks) michael@0: return callbacks->GetInterface(iid, result); michael@0: return NS_ERROR_NO_INTERFACE; michael@0: } michael@0: michael@0: } // namespace mozilla::net michael@0: } // namespace mozilla