netwerk/protocol/http/nsHttpConnection.cpp

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:1a05692872d4
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* vim:set ts=4 sw=4 sts=4 et cin: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 // HttpLog.h should generally be included first
8 #include "HttpLog.h"
9
10 // Log on level :5, instead of default :4.
11 #undef LOG
12 #define LOG(args) LOG5(args)
13 #undef LOG_ENABLED
14 #define LOG_ENABLED() LOG5_ENABLED()
15
16 #include "nsHttpConnection.h"
17 #include "nsHttpRequestHead.h"
18 #include "nsHttpResponseHead.h"
19 #include "nsHttpHandler.h"
20 #include "nsIOService.h"
21 #include "nsISocketTransport.h"
22 #include "nsSocketTransportService2.h"
23 #include "nsISSLSocketControl.h"
24 #include "sslt.h"
25 #include "nsStringStream.h"
26 #include "nsProxyRelease.h"
27 #include "nsPreloadedStream.h"
28 #include "ASpdySession.h"
29 #include "mozilla/Telemetry.h"
30 #include "nsISupportsPriority.h"
31 #include "nsHttpPipeline.h"
32 #include <algorithm>
33 #include "mozilla/ChaosMode.h"
34
35 #ifdef DEBUG
36 // defined by the socket transport service while active
37 extern PRThread *gSocketThread;
38 #endif
39
40 namespace mozilla {
41 namespace net {
42
43 //-----------------------------------------------------------------------------
44 // nsHttpConnection <public>
45 //-----------------------------------------------------------------------------
46
47 nsHttpConnection::nsHttpConnection()
48 : mTransaction(nullptr)
49 , mHttpHandler(gHttpHandler)
50 , mCallbacksLock("nsHttpConnection::mCallbacksLock")
51 , mConsiderReusedAfterInterval(0)
52 , mConsiderReusedAfterEpoch(0)
53 , mCurrentBytesRead(0)
54 , mMaxBytesRead(0)
55 , mTotalBytesRead(0)
56 , mTotalBytesWritten(0)
57 , mKeepAlive(true) // assume to keep-alive by default
58 , mKeepAliveMask(true)
59 , mDontReuse(false)
60 , mSupportsPipelining(false) // assume low-grade server
61 , mIsReused(false)
62 , mCompletedProxyConnect(false)
63 , mLastTransactionExpectedNoContent(false)
64 , mIdleMonitoring(false)
65 , mProxyConnectInProgress(false)
66 , mExperienced(false)
67 , mHttp1xTransactionCount(0)
68 , mRemainingConnectionUses(0xffffffff)
69 , mClassification(nsAHttpTransaction::CLASS_GENERAL)
70 , mNPNComplete(false)
71 , mSetupSSLCalled(false)
72 , mUsingSpdyVersion(0)
73 , mPriority(nsISupportsPriority::PRIORITY_NORMAL)
74 , mReportedSpdy(false)
75 , mEverUsedSpdy(false)
76 , mLastHttpResponseVersion(NS_HTTP_VERSION_1_1)
77 , mTransactionCaps(0)
78 , mResponseTimeoutEnabled(false)
79 , mTCPKeepaliveConfig(kTCPKeepaliveDisabled)
80 {
81 LOG(("Creating nsHttpConnection @%x\n", this));
82
83 // the default timeout is for when this connection has not yet processed a
84 // transaction
85 static const PRIntervalTime k5Sec = PR_SecondsToInterval(5);
86 mIdleTimeout =
87 (k5Sec < gHttpHandler->IdleTimeout()) ? k5Sec : gHttpHandler->IdleTimeout();
88 }
89
90 nsHttpConnection::~nsHttpConnection()
91 {
92 LOG(("Destroying nsHttpConnection @%x\n", this));
93
94 if (!mEverUsedSpdy) {
95 LOG(("nsHttpConnection %p performed %d HTTP/1.x transactions\n",
96 this, mHttp1xTransactionCount));
97 Telemetry::Accumulate(Telemetry::HTTP_REQUEST_PER_CONN,
98 mHttp1xTransactionCount);
99 }
100
101 if (mTotalBytesRead) {
102 uint32_t totalKBRead = static_cast<uint32_t>(mTotalBytesRead >> 10);
103 LOG(("nsHttpConnection %p read %dkb on connection spdy=%d\n",
104 this, totalKBRead, mEverUsedSpdy));
105 Telemetry::Accumulate(mEverUsedSpdy ?
106 Telemetry::SPDY_KBREAD_PER_CONN :
107 Telemetry::HTTP_KBREAD_PER_CONN,
108 totalKBRead);
109 }
110 }
111
112 nsresult
113 nsHttpConnection::Init(nsHttpConnectionInfo *info,
114 uint16_t maxHangTime,
115 nsISocketTransport *transport,
116 nsIAsyncInputStream *instream,
117 nsIAsyncOutputStream *outstream,
118 nsIInterfaceRequestor *callbacks,
119 PRIntervalTime rtt)
120 {
121 MOZ_ASSERT(transport && instream && outstream,
122 "invalid socket information");
123 LOG(("nsHttpConnection::Init [this=%p "
124 "transport=%p instream=%p outstream=%p rtt=%d]\n",
125 this, transport, instream, outstream,
126 PR_IntervalToMilliseconds(rtt)));
127
128 NS_ENSURE_ARG_POINTER(info);
129 NS_ENSURE_TRUE(!mConnInfo, NS_ERROR_ALREADY_INITIALIZED);
130
131 mConnInfo = info;
132 mLastWriteTime = mLastReadTime = PR_IntervalNow();
133 mSupportsPipelining =
134 gHttpHandler->ConnMgr()->SupportsPipelining(mConnInfo);
135 mRtt = rtt;
136 mMaxHangTime = PR_SecondsToInterval(maxHangTime);
137
138 mSocketTransport = transport;
139 mSocketIn = instream;
140 mSocketOut = outstream;
141 nsresult rv = mSocketTransport->SetEventSink(this, nullptr);
142 NS_ENSURE_SUCCESS(rv, rv);
143
144 // See explanation for non-strictness of this operation in SetSecurityCallbacks.
145 mCallbacks = new nsMainThreadPtrHolder<nsIInterfaceRequestor>(callbacks, false);
146 rv = mSocketTransport->SetSecurityCallbacks(this);
147 NS_ENSURE_SUCCESS(rv, rv);
148
149 return NS_OK;
150 }
151
152 void
153 nsHttpConnection::StartSpdy(uint8_t spdyVersion)
154 {
155 LOG(("nsHttpConnection::StartSpdy [this=%p]\n", this));
156
157 MOZ_ASSERT(!mSpdySession);
158
159 mUsingSpdyVersion = spdyVersion;
160 mEverUsedSpdy = true;
161
162 // Setting the connection as reused allows some transactions that fail
163 // with NS_ERROR_NET_RESET to be restarted and SPDY uses that code
164 // to handle clean rejections (such as those that arrived after
165 // a server goaway was generated).
166 mIsReused = true;
167
168 // If mTransaction is a pipeline object it might represent
169 // several requests. If so, we need to unpack that and
170 // pack them all into a new spdy session.
171
172 nsTArray<nsRefPtr<nsAHttpTransaction> > list;
173 nsresult rv = mTransaction->TakeSubTransactions(list);
174
175 if (rv == NS_ERROR_ALREADY_OPENED) {
176 // Has the interface for TakeSubTransactions() changed?
177 LOG(("TakeSubTranscations somehow called after "
178 "nsAHttpTransaction began processing\n"));
179 MOZ_ASSERT(false,
180 "TakeSubTranscations somehow called after "
181 "nsAHttpTransaction began processing");
182 mTransaction->Close(NS_ERROR_ABORT);
183 return;
184 }
185
186 if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) {
187 // Has the interface for TakeSubTransactions() changed?
188 LOG(("unexpected rv from nnsAHttpTransaction::TakeSubTransactions()"));
189 MOZ_ASSERT(false,
190 "unexpected result from "
191 "nsAHttpTransaction::TakeSubTransactions()");
192 mTransaction->Close(NS_ERROR_ABORT);
193 return;
194 }
195
196 if (NS_FAILED(rv)) { // includes NS_ERROR_NOT_IMPLEMENTED
197 MOZ_ASSERT(list.IsEmpty(), "sub transaction list not empty");
198
199 // This is ok - treat mTransaction as a single real request.
200 // Wrap the old http transaction into the new spdy session
201 // as the first stream.
202 mSpdySession = ASpdySession::NewSpdySession(spdyVersion,
203 mTransaction, mSocketTransport,
204 mPriority);
205 LOG(("nsHttpConnection::StartSpdy moves single transaction %p "
206 "into SpdySession %p\n", mTransaction.get(), mSpdySession.get()));
207 }
208 else {
209 int32_t count = list.Length();
210
211 LOG(("nsHttpConnection::StartSpdy moving transaction list len=%d "
212 "into SpdySession %p\n", count, mSpdySession.get()));
213
214 if (!count) {
215 mTransaction->Close(NS_ERROR_ABORT);
216 return;
217 }
218
219 for (int32_t index = 0; index < count; ++index) {
220 if (!mSpdySession) {
221 mSpdySession = ASpdySession::NewSpdySession(spdyVersion,
222 list[index], mSocketTransport,
223 mPriority);
224 }
225 else {
226 // AddStream() cannot fail
227 if (!mSpdySession->AddStream(list[index], mPriority)) {
228 MOZ_ASSERT(false, "SpdySession::AddStream failed");
229 LOG(("SpdySession::AddStream failed\n"));
230 mTransaction->Close(NS_ERROR_ABORT);
231 return;
232 }
233 }
234 }
235 }
236
237 // Disable TCP Keepalives - use SPDY ping instead.
238 rv = DisableTCPKeepalives();
239 if (NS_WARN_IF(NS_FAILED(rv))) {
240 LOG(("nsHttpConnection::StartSpdy [%p] DisableTCPKeepalives failed "
241 "rv[0x%x]", this, rv));
242 }
243
244 mSupportsPipelining = false; // dont use http/1 pipelines with spdy
245 mTransaction = mSpdySession;
246 mIdleTimeout = gHttpHandler->SpdyTimeout();
247 }
248
249 bool
250 nsHttpConnection::EnsureNPNComplete()
251 {
252 // If for some reason the components to check on NPN aren't available,
253 // this function will just return true to continue on and disable SPDY
254
255 MOZ_ASSERT(mSocketTransport);
256 if (!mSocketTransport) {
257 // this cannot happen
258 mNPNComplete = true;
259 return true;
260 }
261
262 if (mNPNComplete)
263 return true;
264
265 nsresult rv;
266
267 nsCOMPtr<nsISupports> securityInfo;
268 nsCOMPtr<nsISSLSocketControl> ssl;
269 nsAutoCString negotiatedNPN;
270
271 rv = mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo));
272 if (NS_FAILED(rv))
273 goto npnComplete;
274
275 ssl = do_QueryInterface(securityInfo, &rv);
276 if (NS_FAILED(rv))
277 goto npnComplete;
278
279 rv = ssl->GetNegotiatedNPN(negotiatedNPN);
280 if (rv == NS_ERROR_NOT_CONNECTED) {
281
282 // By writing 0 bytes to the socket the SSL handshake machine is
283 // pushed forward.
284 uint32_t count = 0;
285 rv = mSocketOut->Write("", 0, &count);
286
287 if (NS_FAILED(rv) && rv != NS_BASE_STREAM_WOULD_BLOCK)
288 goto npnComplete;
289 return false;
290 }
291
292 if (NS_FAILED(rv))
293 goto npnComplete;
294
295 LOG(("nsHttpConnection::EnsureNPNComplete %p [%s] negotiated to '%s'\n",
296 this, mConnInfo->Host(), negotiatedNPN.get()));
297
298 uint8_t spdyVersion;
299 rv = gHttpHandler->SpdyInfo()->GetNPNVersionIndex(negotiatedNPN,
300 &spdyVersion);
301 if (NS_SUCCEEDED(rv))
302 StartSpdy(spdyVersion);
303
304 Telemetry::Accumulate(Telemetry::SPDY_NPN_CONNECT, UsingSpdy());
305
306 npnComplete:
307 LOG(("nsHttpConnection::EnsureNPNComplete setting complete to true"));
308 mNPNComplete = true;
309 return true;
310 }
311
312 // called on the socket thread
313 nsresult
314 nsHttpConnection::Activate(nsAHttpTransaction *trans, uint32_t caps, int32_t pri)
315 {
316 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
317 LOG(("nsHttpConnection::Activate [this=%p trans=%x caps=%x]\n",
318 this, trans, caps));
319
320 if (!trans->IsNullTransaction())
321 mExperienced = true;
322
323 mTransactionCaps = caps;
324 mPriority = pri;
325 if (mTransaction && mUsingSpdyVersion)
326 return AddTransaction(trans, pri);
327
328 NS_ENSURE_ARG_POINTER(trans);
329 NS_ENSURE_TRUE(!mTransaction, NS_ERROR_IN_PROGRESS);
330
331 // reset the read timers to wash away any idle time
332 mLastWriteTime = mLastReadTime = PR_IntervalNow();
333
334 // Update security callbacks
335 nsCOMPtr<nsIInterfaceRequestor> callbacks;
336 trans->GetSecurityCallbacks(getter_AddRefs(callbacks));
337 SetSecurityCallbacks(callbacks);
338
339 SetupSSL(caps);
340
341 // take ownership of the transaction
342 mTransaction = trans;
343
344 MOZ_ASSERT(!mIdleMonitoring, "Activating a connection with an Idle Monitor");
345 mIdleMonitoring = false;
346
347 // set mKeepAlive according to what will be requested
348 mKeepAliveMask = mKeepAlive = (caps & NS_HTTP_ALLOW_KEEPALIVE);
349
350 // need to handle HTTP CONNECT tunnels if this is the first time if
351 // we are tunneling through a proxy
352 nsresult rv = NS_OK;
353 if (mConnInfo->UsingConnect() && !mCompletedProxyConnect) {
354 rv = SetupProxyConnect();
355 if (NS_FAILED(rv))
356 goto failed_activation;
357 mProxyConnectInProgress = true;
358 }
359
360 // Clear the per activation counter
361 mCurrentBytesRead = 0;
362
363 // The overflow state is not needed between activations
364 mInputOverflow = nullptr;
365
366 mResponseTimeoutEnabled = gHttpHandler->ResponseTimeoutEnabled() &&
367 mTransaction->ResponseTimeout() > 0 &&
368 mTransaction->ResponseTimeoutEnabled();
369
370 rv = StartShortLivedTCPKeepalives();
371 if (NS_WARN_IF(NS_FAILED(rv))) {
372 LOG(("nsHttpConnection::Activate [%p] "
373 "StartShortLivedTCPKeepalives failed rv[0x%x]",
374 this, rv));
375 }
376
377 rv = OnOutputStreamReady(mSocketOut);
378
379 failed_activation:
380 if (NS_FAILED(rv)) {
381 mTransaction = nullptr;
382 }
383
384 return rv;
385 }
386
387 void
388 nsHttpConnection::SetupSSL(uint32_t caps)
389 {
390 LOG(("nsHttpConnection::SetupSSL %p caps=0x%X\n", this, caps));
391
392 if (mSetupSSLCalled) // do only once
393 return;
394 mSetupSSLCalled = true;
395
396 if (mNPNComplete)
397 return;
398
399 // we flip this back to false if SetNPNList succeeds at the end
400 // of this function
401 mNPNComplete = true;
402
403 if (!mConnInfo->UsingSSL())
404 return;
405
406 LOG(("nsHttpConnection::SetupSSL Setting up "
407 "Next Protocol Negotiation"));
408 nsCOMPtr<nsISupports> securityInfo;
409 nsresult rv =
410 mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo));
411 if (NS_FAILED(rv))
412 return;
413
414 nsCOMPtr<nsISSLSocketControl> ssl = do_QueryInterface(securityInfo, &rv);
415 if (NS_FAILED(rv))
416 return;
417
418 if (caps & NS_HTTP_ALLOW_RSA_FALSESTART) {
419 LOG(("nsHttpConnection::SetupSSL %p "
420 ">= RSA Key Exchange Expected\n", this));
421 ssl->SetKEAExpected(ssl_kea_rsa);
422 }
423
424 nsTArray<nsCString> protocolArray;
425
426 // The first protocol is used as the fallback if none of the
427 // protocols supported overlap with the server's list.
428 // In the case of overlap, matching priority is driven by
429 // the order of the server's advertisement.
430 protocolArray.AppendElement(NS_LITERAL_CSTRING("http/1.1"));
431
432 if (gHttpHandler->IsSpdyEnabled() &&
433 !(caps & NS_HTTP_DISALLOW_SPDY)) {
434 LOG(("nsHttpConnection::SetupSSL Allow SPDY NPN selection"));
435 for (uint32_t index = 0; index < SpdyInformation::kCount; ++index) {
436 if (gHttpHandler->SpdyInfo()->ProtocolEnabled(index))
437 protocolArray.AppendElement(
438 gHttpHandler->SpdyInfo()->VersionString[index]);
439 }
440 }
441
442 if (NS_SUCCEEDED(ssl->SetNPNList(protocolArray))) {
443 LOG(("nsHttpConnection::Init Setting up SPDY Negotiation OK"));
444 mNPNComplete = false;
445 }
446 }
447
448 nsresult
449 nsHttpConnection::AddTransaction(nsAHttpTransaction *httpTransaction,
450 int32_t priority)
451 {
452 LOG(("nsHttpConnection::AddTransaction for SPDY"));
453
454 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
455 MOZ_ASSERT(mSpdySession && mUsingSpdyVersion,
456 "AddTransaction to live http connection without spdy");
457 MOZ_ASSERT(mTransaction,
458 "AddTransaction to idle http connection");
459
460 if (!mSpdySession->AddStream(httpTransaction, priority)) {
461 MOZ_ASSERT(false, "AddStream should never fail due to"
462 "RoomForMore() admission check");
463 return NS_ERROR_FAILURE;
464 }
465
466 ResumeSend();
467
468 return NS_OK;
469 }
470
471 void
472 nsHttpConnection::Close(nsresult reason)
473 {
474 LOG(("nsHttpConnection::Close [this=%p reason=%x]\n", this, reason));
475
476 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
477
478 // Ensure TCP keepalive timer is stopped.
479 if (mTCPKeepaliveTransitionTimer) {
480 mTCPKeepaliveTransitionTimer->Cancel();
481 mTCPKeepaliveTransitionTimer = nullptr;
482 }
483
484 if (NS_FAILED(reason)) {
485 if (mIdleMonitoring)
486 EndIdleMonitoring();
487
488 if (mSocketTransport) {
489 mSocketTransport->SetEventSink(nullptr, nullptr);
490
491 // If there are bytes sitting in the input queue then read them
492 // into a junk buffer to avoid generating a tcp rst by closing a
493 // socket with data pending. TLS is a classic case of this where
494 // a Alert record might be superfulous to a clean HTTP/SPDY shutdown.
495 // Never block to do this and limit it to a small amount of data.
496 if (mSocketIn) {
497 char buffer[4000];
498 uint32_t count, total = 0;
499 nsresult rv;
500 do {
501 rv = mSocketIn->Read(buffer, 4000, &count);
502 if (NS_SUCCEEDED(rv))
503 total += count;
504 }
505 while (NS_SUCCEEDED(rv) && count > 0 && total < 64000);
506 LOG(("nsHttpConnection::Close drained %d bytes\n", total));
507 }
508
509 mSocketTransport->SetSecurityCallbacks(nullptr);
510 mSocketTransport->Close(reason);
511 if (mSocketOut)
512 mSocketOut->AsyncWait(nullptr, 0, 0, nullptr);
513 }
514 mKeepAlive = false;
515 }
516 }
517
518 // called on the socket thread
519 nsresult
520 nsHttpConnection::ProxyStartSSL()
521 {
522 LOG(("nsHttpConnection::ProxyStartSSL [this=%p]\n", this));
523 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
524
525 nsCOMPtr<nsISupports> securityInfo;
526 nsresult rv = mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo));
527 if (NS_FAILED(rv)) return rv;
528
529 nsCOMPtr<nsISSLSocketControl> ssl = do_QueryInterface(securityInfo, &rv);
530 if (NS_FAILED(rv)) return rv;
531
532 return ssl->ProxyStartSSL();
533 }
534
535 void
536 nsHttpConnection::DontReuse()
537 {
538 mKeepAliveMask = false;
539 mKeepAlive = false;
540 mDontReuse = true;
541 mIdleTimeout = 0;
542 if (mSpdySession)
543 mSpdySession->DontReuse();
544 }
545
546 // Checked by the Connection Manager before scheduling a pipelined transaction
547 bool
548 nsHttpConnection::SupportsPipelining()
549 {
550 if (mTransaction &&
551 mTransaction->PipelineDepth() >= mRemainingConnectionUses) {
552 LOG(("nsHttpConnection::SupportsPipelining this=%p deny pipeline "
553 "because current depth %d exceeds max remaining uses %d\n",
554 this, mTransaction->PipelineDepth(), mRemainingConnectionUses));
555 return false;
556 }
557 return mSupportsPipelining && IsKeepAlive() && !mDontReuse;
558 }
559
560 bool
561 nsHttpConnection::CanReuse()
562 {
563 if (mDontReuse)
564 return false;
565
566 if ((mTransaction ? mTransaction->PipelineDepth() : 0) >=
567 mRemainingConnectionUses) {
568 return false;
569 }
570
571 bool canReuse;
572
573 if (mSpdySession)
574 canReuse = mSpdySession->CanReuse();
575 else
576 canReuse = IsKeepAlive();
577
578 canReuse = canReuse && (IdleTime() < mIdleTimeout) && IsAlive();
579
580 // An idle persistent connection should not have data waiting to be read
581 // before a request is sent. Data here is likely a 408 timeout response
582 // which we would deal with later on through the restart logic, but that
583 // path is more expensive than just closing the socket now.
584
585 uint64_t dataSize;
586 if (canReuse && mSocketIn && !mUsingSpdyVersion && mHttp1xTransactionCount &&
587 NS_SUCCEEDED(mSocketIn->Available(&dataSize)) && dataSize) {
588 LOG(("nsHttpConnection::CanReuse %p %s"
589 "Socket not reusable because read data pending (%llu) on it.\n",
590 this, mConnInfo->Host(), dataSize));
591 canReuse = false;
592 }
593 return canReuse;
594 }
595
596 bool
597 nsHttpConnection::CanDirectlyActivate()
598 {
599 // return true if a new transaction can be addded to ths connection at any
600 // time through Activate(). In practice this means this is a healthy SPDY
601 // connection with room for more concurrent streams.
602
603 return UsingSpdy() && CanReuse() &&
604 mSpdySession && mSpdySession->RoomForMoreStreams();
605 }
606
607 PRIntervalTime
608 nsHttpConnection::IdleTime()
609 {
610 return mSpdySession ?
611 mSpdySession->IdleTime() : (PR_IntervalNow() - mLastReadTime);
612 }
613
614 // returns the number of seconds left before the allowable idle period
615 // expires, or 0 if the period has already expied.
616 uint32_t
617 nsHttpConnection::TimeToLive()
618 {
619 if (IdleTime() >= mIdleTimeout)
620 return 0;
621 uint32_t timeToLive = PR_IntervalToSeconds(mIdleTimeout - IdleTime());
622
623 // a positive amount of time can be rounded to 0. Because 0 is used
624 // as the expiration signal, round all values from 0 to 1 up to 1.
625 if (!timeToLive)
626 timeToLive = 1;
627 return timeToLive;
628 }
629
630 bool
631 nsHttpConnection::IsAlive()
632 {
633 if (!mSocketTransport)
634 return false;
635
636 // SocketTransport::IsAlive can run the SSL state machine, so make sure
637 // the NPN options are set before that happens.
638 SetupSSL(mTransactionCaps);
639
640 bool alive;
641 nsresult rv = mSocketTransport->IsAlive(&alive);
642 if (NS_FAILED(rv))
643 alive = false;
644
645 //#define TEST_RESTART_LOGIC
646 #ifdef TEST_RESTART_LOGIC
647 if (!alive) {
648 LOG(("pretending socket is still alive to test restart logic\n"));
649 alive = true;
650 }
651 #endif
652
653 return alive;
654 }
655
656 bool
657 nsHttpConnection::SupportsPipelining(nsHttpResponseHead *responseHead)
658 {
659 // SPDY supports infinite parallelism, so no need to pipeline.
660 if (mUsingSpdyVersion)
661 return false;
662
663 // assuming connection is HTTP/1.1 with keep-alive enabled
664 if (mConnInfo->UsingHttpProxy() && !mConnInfo->UsingConnect()) {
665 // XXX check for bad proxy servers...
666 return true;
667 }
668
669 // check for bad origin servers
670 const char *val = responseHead->PeekHeader(nsHttp::Server);
671
672 // If there is no server header we will assume it should not be banned
673 // as facebook and some other prominent sites do this
674 if (!val)
675 return true;
676
677 // The blacklist is indexed by the first character. All of these servers are
678 // known to return their identifier as the first thing in the server string,
679 // so we can do a leading match.
680
681 static const char *bad_servers[26][6] = {
682 { nullptr }, { nullptr }, { nullptr }, { nullptr }, // a - d
683 { "EFAServer/", nullptr }, // e
684 { nullptr }, { nullptr }, { nullptr }, { nullptr }, // f - i
685 { nullptr }, { nullptr }, { nullptr }, // j - l
686 { "Microsoft-IIS/4.", "Microsoft-IIS/5.", nullptr }, // m
687 { "Netscape-Enterprise/3.", "Netscape-Enterprise/4.",
688 "Netscape-Enterprise/5.", "Netscape-Enterprise/6.", nullptr }, // n
689 { nullptr }, { nullptr }, { nullptr }, { nullptr }, // o - r
690 { nullptr }, { nullptr }, { nullptr }, { nullptr }, // s - v
691 { "WebLogic 3.", "WebLogic 4.","WebLogic 5.", "WebLogic 6.",
692 "Winstone Servlet Engine v0.", nullptr }, // w
693 { nullptr }, { nullptr }, { nullptr } // x - z
694 };
695
696 int index = val[0] - 'A'; // the whole table begins with capital letters
697 if ((index >= 0) && (index <= 25))
698 {
699 for (int i = 0; bad_servers[index][i] != nullptr; i++) {
700 if (!PL_strncmp (val, bad_servers[index][i], strlen (bad_servers[index][i]))) {
701 LOG(("looks like this server does not support pipelining"));
702 gHttpHandler->ConnMgr()->PipelineFeedbackInfo(
703 mConnInfo, nsHttpConnectionMgr::RedBannedServer, this , 0);
704 return false;
705 }
706 }
707 }
708
709 // ok, let's allow pipelining to this server
710 return true;
711 }
712
713 //----------------------------------------------------------------------------
714 // nsHttpConnection::nsAHttpConnection compatible methods
715 //----------------------------------------------------------------------------
716
717 nsresult
718 nsHttpConnection::OnHeadersAvailable(nsAHttpTransaction *trans,
719 nsHttpRequestHead *requestHead,
720 nsHttpResponseHead *responseHead,
721 bool *reset)
722 {
723 LOG(("nsHttpConnection::OnHeadersAvailable [this=%p trans=%p response-head=%p]\n",
724 this, trans, responseHead));
725
726 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
727 NS_ENSURE_ARG_POINTER(trans);
728 MOZ_ASSERT(responseHead, "No response head?");
729
730 // we won't change our keep-alive policy unless the server has explicitly
731 // told us to do so.
732
733 // inspect the connection headers for keep-alive info provided the
734 // transaction completed successfully. In the case of a non-sensical close
735 // and keep-alive favor the close out of conservatism.
736
737 bool explicitKeepAlive = false;
738 bool explicitClose = responseHead->HasHeaderValue(nsHttp::Connection, "close") ||
739 responseHead->HasHeaderValue(nsHttp::Proxy_Connection, "close");
740 if (!explicitClose)
741 explicitKeepAlive = responseHead->HasHeaderValue(nsHttp::Connection, "keep-alive") ||
742 responseHead->HasHeaderValue(nsHttp::Proxy_Connection, "keep-alive");
743
744 // deal with 408 Server Timeouts
745 uint16_t responseStatus = responseHead->Status();
746 static const PRIntervalTime k1000ms = PR_MillisecondsToInterval(1000);
747 if (responseStatus == 408) {
748 // If this error could be due to a persistent connection reuse then
749 // we pass an error code of NS_ERROR_NET_RESET to
750 // trigger the transaction 'restart' mechanism. We tell it to reset its
751 // response headers so that it will be ready to receive the new response.
752 if (mIsReused && ((PR_IntervalNow() - mLastWriteTime) < k1000ms)) {
753 Close(NS_ERROR_NET_RESET);
754 *reset = true;
755 return NS_OK;
756 }
757
758 // timeouts that are not caused by persistent connection reuse should
759 // not be retried for browser compatibility reasons. bug 907800. The
760 // server driven close is implicit in the 408.
761 explicitClose = true;
762 explicitKeepAlive = false;
763 }
764
765 // reset to default (the server may have changed since we last checked)
766 mSupportsPipelining = false;
767
768 if ((responseHead->Version() < NS_HTTP_VERSION_1_1) ||
769 (requestHead->Version() < NS_HTTP_VERSION_1_1)) {
770 // HTTP/1.0 connections are by default NOT persistent
771 if (explicitKeepAlive)
772 mKeepAlive = true;
773 else
774 mKeepAlive = false;
775
776 // We need at least version 1.1 to use pipelines
777 gHttpHandler->ConnMgr()->PipelineFeedbackInfo(
778 mConnInfo, nsHttpConnectionMgr::RedVersionTooLow, this, 0);
779 }
780 else {
781 // HTTP/1.1 connections are by default persistent
782 if (explicitClose) {
783 mKeepAlive = false;
784
785 // persistent connections are required for pipelining to work - if
786 // this close was not pre-announced then generate the negative
787 // BadExplicitClose feedback
788 if (mRemainingConnectionUses > 1)
789 gHttpHandler->ConnMgr()->PipelineFeedbackInfo(
790 mConnInfo, nsHttpConnectionMgr::BadExplicitClose, this, 0);
791 }
792 else {
793 mKeepAlive = true;
794
795 // Do not support pipelining when we are establishing
796 // an SSL tunnel though an HTTP proxy. Pipelining support
797 // determination must be based on comunication with the
798 // target server in this case. See bug 422016 for futher
799 // details.
800 if (!mProxyConnectStream)
801 mSupportsPipelining = SupportsPipelining(responseHead);
802 }
803 }
804 mKeepAliveMask = mKeepAlive;
805
806 // Update the pipelining status in the connection info object
807 // and also read it back. It is possible the ci status is
808 // locked to false if pipelining has been banned on this ci due to
809 // some kind of observed flaky behavior
810 if (mSupportsPipelining) {
811 // report the pipelining-compatible header to the connection manager
812 // as positive feedback. This will undo 1 penalty point the host
813 // may have accumulated in the past.
814
815 gHttpHandler->ConnMgr()->PipelineFeedbackInfo(
816 mConnInfo, nsHttpConnectionMgr::NeutralExpectedOK, this, 0);
817
818 mSupportsPipelining =
819 gHttpHandler->ConnMgr()->SupportsPipelining(mConnInfo);
820 }
821
822 // If this connection is reserved for revalidations and we are
823 // receiving a document that failed revalidation then switch the
824 // classification to general to avoid pipelining more revalidations behind
825 // it.
826 if (mClassification == nsAHttpTransaction::CLASS_REVALIDATION &&
827 responseStatus != 304) {
828 mClassification = nsAHttpTransaction::CLASS_GENERAL;
829 }
830
831 // if this connection is persistent, then the server may send a "Keep-Alive"
832 // header specifying the maximum number of times the connection can be
833 // reused as well as the maximum amount of time the connection can be idle
834 // before the server will close it. we ignore the max reuse count, because
835 // a "keep-alive" connection is by definition capable of being reused, and
836 // we only care about being able to reuse it once. if a timeout is not
837 // specified then we use our advertized timeout value.
838 bool foundKeepAliveMax = false;
839 if (mKeepAlive) {
840 const char *val = responseHead->PeekHeader(nsHttp::Keep_Alive);
841
842 if (!mUsingSpdyVersion) {
843 const char *cp = PL_strcasestr(val, "timeout=");
844 if (cp)
845 mIdleTimeout = PR_SecondsToInterval((uint32_t) atoi(cp + 8));
846 else
847 mIdleTimeout = gHttpHandler->IdleTimeout();
848
849 cp = PL_strcasestr(val, "max=");
850 if (cp) {
851 int val = atoi(cp + 4);
852 if (val > 0) {
853 foundKeepAliveMax = true;
854 mRemainingConnectionUses = static_cast<uint32_t>(val);
855 }
856 }
857 }
858 else {
859 mIdleTimeout = gHttpHandler->SpdyTimeout();
860 }
861
862 LOG(("Connection can be reused [this=%p idle-timeout=%usec]\n",
863 this, PR_IntervalToSeconds(mIdleTimeout)));
864 }
865
866 if (!foundKeepAliveMax && mRemainingConnectionUses && !mUsingSpdyVersion)
867 --mRemainingConnectionUses;
868
869 // If we're doing a proxy connect, we need to check whether or not
870 // it was successful. If so, we have to reset the transaction and step-up
871 // the socket connection if using SSL. Finally, we have to wake up the
872 // socket write request.
873 if (mProxyConnectStream) {
874 MOZ_ASSERT(!mUsingSpdyVersion,
875 "SPDY NPN Complete while using proxy connect stream");
876 mProxyConnectStream = 0;
877 if (responseStatus == 200) {
878 LOG(("proxy CONNECT succeeded! ssl=%s\n",
879 mConnInfo->UsingSSL() ? "true" :"false"));
880 *reset = true;
881 nsresult rv;
882 if (mConnInfo->UsingSSL()) {
883 rv = ProxyStartSSL();
884 if (NS_FAILED(rv)) // XXX need to handle this for real
885 LOG(("ProxyStartSSL failed [rv=%x]\n", rv));
886 }
887 mCompletedProxyConnect = true;
888 mProxyConnectInProgress = false;
889 rv = mSocketOut->AsyncWait(this, 0, 0, nullptr);
890 // XXX what if this fails -- need to handle this error
891 MOZ_ASSERT(NS_SUCCEEDED(rv), "mSocketOut->AsyncWait failed");
892 }
893 else {
894 LOG(("proxy CONNECT failed! ssl=%s\n",
895 mConnInfo->UsingSSL() ? "true" :"false"));
896 mTransaction->SetProxyConnectFailed();
897 }
898 }
899
900 const char *upgradeReq = requestHead->PeekHeader(nsHttp::Upgrade);
901 // Don't use persistent connection for Upgrade unless there's an auth failure:
902 // some proxies expect to see auth response on persistent connection.
903 if (upgradeReq && responseStatus != 401 && responseStatus != 407) {
904 LOG(("HTTP Upgrade in play - disable keepalive\n"));
905 DontReuse();
906 }
907
908 if (responseStatus == 101) {
909 const char *upgradeResp = responseHead->PeekHeader(nsHttp::Upgrade);
910 if (!upgradeReq || !upgradeResp ||
911 !nsHttp::FindToken(upgradeResp, upgradeReq,
912 HTTP_HEADER_VALUE_SEPS)) {
913 LOG(("HTTP 101 Upgrade header mismatch req = %s, resp = %s\n",
914 upgradeReq, upgradeResp));
915 Close(NS_ERROR_ABORT);
916 }
917 else {
918 LOG(("HTTP Upgrade Response to %s\n", upgradeResp));
919 }
920 }
921
922 mLastHttpResponseVersion = responseHead->Version();
923
924 return NS_OK;
925 }
926
927 bool
928 nsHttpConnection::IsReused()
929 {
930 if (mIsReused)
931 return true;
932 if (!mConsiderReusedAfterInterval)
933 return false;
934
935 // ReusedAfter allows a socket to be consider reused only after a certain
936 // interval of time has passed
937 return (PR_IntervalNow() - mConsiderReusedAfterEpoch) >=
938 mConsiderReusedAfterInterval;
939 }
940
941 void
942 nsHttpConnection::SetIsReusedAfter(uint32_t afterMilliseconds)
943 {
944 mConsiderReusedAfterEpoch = PR_IntervalNow();
945 mConsiderReusedAfterInterval = PR_MillisecondsToInterval(afterMilliseconds);
946 }
947
948 nsresult
949 nsHttpConnection::TakeTransport(nsISocketTransport **aTransport,
950 nsIAsyncInputStream **aInputStream,
951 nsIAsyncOutputStream **aOutputStream)
952 {
953 if (mUsingSpdyVersion)
954 return NS_ERROR_FAILURE;
955 if (mTransaction && !mTransaction->IsDone())
956 return NS_ERROR_IN_PROGRESS;
957 if (!(mSocketTransport && mSocketIn && mSocketOut))
958 return NS_ERROR_NOT_INITIALIZED;
959
960 if (mInputOverflow)
961 mSocketIn = mInputOverflow.forget();
962
963 // Change TCP Keepalive frequency to long-lived if currently short-lived.
964 if (mTCPKeepaliveConfig == kTCPKeepaliveShortLivedConfig) {
965 if (mTCPKeepaliveTransitionTimer) {
966 mTCPKeepaliveTransitionTimer->Cancel();
967 mTCPKeepaliveTransitionTimer = nullptr;
968 }
969 nsresult rv = StartLongLivedTCPKeepalives();
970 LOG(("nsHttpConnection::TakeTransport [%p] calling "
971 "StartLongLivedTCPKeepalives", this));
972 if (NS_WARN_IF(NS_FAILED(rv))) {
973 LOG(("nsHttpConnection::TakeTransport [%p] "
974 "StartLongLivedTCPKeepalives failed rv[0x%x]", this, rv));
975 }
976 }
977
978 NS_IF_ADDREF(*aTransport = mSocketTransport);
979 NS_IF_ADDREF(*aInputStream = mSocketIn);
980 NS_IF_ADDREF(*aOutputStream = mSocketOut);
981
982 mSocketTransport->SetSecurityCallbacks(nullptr);
983 mSocketTransport->SetEventSink(nullptr, nullptr);
984 mSocketTransport = nullptr;
985 mSocketIn = nullptr;
986 mSocketOut = nullptr;
987
988 return NS_OK;
989 }
990
991 uint32_t
992 nsHttpConnection::ReadTimeoutTick(PRIntervalTime now)
993 {
994 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
995
996 // make sure timer didn't tick before Activate()
997 if (!mTransaction)
998 return UINT32_MAX;
999
1000 // Spdy implements some timeout handling using the SPDY ping frame.
1001 if (mSpdySession) {
1002 return mSpdySession->ReadTimeoutTick(now);
1003 }
1004
1005 uint32_t nextTickAfter = UINT32_MAX;
1006 // Timeout if the response is taking too long to arrive.
1007 if (mResponseTimeoutEnabled) {
1008 NS_WARN_IF_FALSE(gHttpHandler->ResponseTimeoutEnabled(),
1009 "Timing out a response, but response timeout is disabled!");
1010
1011 PRIntervalTime initialResponseDelta = now - mLastWriteTime;
1012
1013 if (initialResponseDelta > mTransaction->ResponseTimeout()) {
1014 LOG(("canceling transaction: no response for %ums: timeout is %dms\n",
1015 PR_IntervalToMilliseconds(initialResponseDelta),
1016 PR_IntervalToMilliseconds(mTransaction->ResponseTimeout())));
1017
1018 mResponseTimeoutEnabled = false;
1019
1020 // This will also close the connection
1021 CloseTransaction(mTransaction, NS_ERROR_NET_TIMEOUT);
1022 return UINT32_MAX;
1023 }
1024 nextTickAfter = PR_IntervalToSeconds(mTransaction->ResponseTimeout()) -
1025 PR_IntervalToSeconds(initialResponseDelta);
1026 nextTickAfter = std::max(nextTickAfter, 1U);
1027 }
1028
1029 if (!gHttpHandler->GetPipelineRescheduleOnTimeout())
1030 return nextTickAfter;
1031
1032 PRIntervalTime delta = now - mLastReadTime;
1033
1034 // we replicate some of the checks both here and in OnSocketReadable() as
1035 // they will be discovered under different conditions. The ones here
1036 // will generally be discovered if we are totally hung and OSR does
1037 // not get called at all, however OSR discovers them with lower latency
1038 // if the issue is just very slow (but not stalled) reading.
1039 //
1040 // Right now we only take action if pipelining is involved, but this would
1041 // be the place to add general read timeout handling if it is desired.
1042
1043 uint32_t pipelineDepth = mTransaction->PipelineDepth();
1044 if (pipelineDepth > 1) {
1045 // if we have pipelines outstanding (not just an idle connection)
1046 // then get a fairly quick tick
1047 nextTickAfter = 1;
1048 }
1049
1050 if (delta >= gHttpHandler->GetPipelineRescheduleTimeout() &&
1051 pipelineDepth > 1) {
1052
1053 // this just reschedules blocked transactions. no transaction
1054 // is aborted completely.
1055 LOG(("cancelling pipeline due to a %ums stall - depth %d\n",
1056 PR_IntervalToMilliseconds(delta), pipelineDepth));
1057
1058 nsHttpPipeline *pipeline = mTransaction->QueryPipeline();
1059 MOZ_ASSERT(pipeline, "pipelinedepth > 1 without pipeline");
1060 // code this defensively for the moment and check for null in opt build
1061 // This will reschedule blocked members of the pipeline, but the
1062 // blocking transaction (i.e. response 0) will not be changed.
1063 if (pipeline) {
1064 pipeline->CancelPipeline(NS_ERROR_NET_TIMEOUT);
1065 LOG(("Rescheduling the head of line blocked members of a pipeline "
1066 "because reschedule-timeout idle interval exceeded"));
1067 }
1068 }
1069
1070 if (delta < gHttpHandler->GetPipelineTimeout())
1071 return nextTickAfter;
1072
1073 if (pipelineDepth <= 1 && !mTransaction->PipelinePosition())
1074 return nextTickAfter;
1075
1076 // nothing has transpired on this pipelined socket for many
1077 // seconds. Call that a total stall and close the transaction.
1078 // There is a chance the transaction will be restarted again
1079 // depending on its state.. that will come back araound
1080 // without pipelining on, so this won't loop.
1081
1082 LOG(("canceling transaction stalled for %ums on a pipeline "
1083 "of depth %d and scheduled originally at pos %d\n",
1084 PR_IntervalToMilliseconds(delta),
1085 pipelineDepth, mTransaction->PipelinePosition()));
1086
1087 // This will also close the connection
1088 CloseTransaction(mTransaction, NS_ERROR_NET_TIMEOUT);
1089 return UINT32_MAX;
1090 }
1091
1092 void
1093 nsHttpConnection::UpdateTCPKeepalive(nsITimer *aTimer, void *aClosure)
1094 {
1095 MOZ_ASSERT(aTimer);
1096 MOZ_ASSERT(aClosure);
1097
1098 nsHttpConnection *self = static_cast<nsHttpConnection*>(aClosure);
1099
1100 if (NS_WARN_IF(self->mUsingSpdyVersion)) {
1101 return;
1102 }
1103
1104 // Do not reduce keepalive probe frequency for idle connections.
1105 if (self->mIdleMonitoring) {
1106 return;
1107 }
1108
1109 nsresult rv = self->StartLongLivedTCPKeepalives();
1110 if (NS_WARN_IF(NS_FAILED(rv))) {
1111 LOG(("nsHttpConnection::UpdateTCPKeepalive [%p] "
1112 "StartLongLivedTCPKeepalives failed rv[0x%x]",
1113 self, rv));
1114 }
1115 }
1116
1117 void
1118 nsHttpConnection::GetSecurityInfo(nsISupports **secinfo)
1119 {
1120 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
1121
1122 if (mSocketTransport) {
1123 if (NS_FAILED(mSocketTransport->GetSecurityInfo(secinfo)))
1124 *secinfo = nullptr;
1125 }
1126 }
1127
1128 void
1129 nsHttpConnection::SetSecurityCallbacks(nsIInterfaceRequestor* aCallbacks)
1130 {
1131 MutexAutoLock lock(mCallbacksLock);
1132 // This is called both on and off the main thread. For JS-implemented
1133 // callbacks, we requires that the call happen on the main thread, but
1134 // for C++-implemented callbacks we don't care. Use a pointer holder with
1135 // strict checking disabled.
1136 mCallbacks = new nsMainThreadPtrHolder<nsIInterfaceRequestor>(aCallbacks, false);
1137 }
1138
1139 nsresult
1140 nsHttpConnection::PushBack(const char *data, uint32_t length)
1141 {
1142 LOG(("nsHttpConnection::PushBack [this=%p, length=%d]\n", this, length));
1143
1144 if (mInputOverflow) {
1145 NS_ERROR("nsHttpConnection::PushBack only one buffer supported");
1146 return NS_ERROR_UNEXPECTED;
1147 }
1148
1149 mInputOverflow = new nsPreloadedStream(mSocketIn, data, length);
1150 return NS_OK;
1151 }
1152
1153 nsresult
1154 nsHttpConnection::ResumeSend()
1155 {
1156 LOG(("nsHttpConnection::ResumeSend [this=%p]\n", this));
1157
1158 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
1159
1160 if (mSocketOut)
1161 return mSocketOut->AsyncWait(this, 0, 0, nullptr);
1162
1163 NS_NOTREACHED("no socket output stream");
1164 return NS_ERROR_UNEXPECTED;
1165 }
1166
1167 nsresult
1168 nsHttpConnection::ResumeRecv()
1169 {
1170 LOG(("nsHttpConnection::ResumeRecv [this=%p]\n", this));
1171
1172 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
1173
1174 // the mLastReadTime timestamp is used for finding slowish readers
1175 // and can be pretty sensitive. For that reason we actually reset it
1176 // when we ask to read (resume recv()) so that when we get called back
1177 // with actual read data in OnSocketReadable() we are only measuring
1178 // the latency between those two acts and not all the processing that
1179 // may get done before the ResumeRecv() call
1180 mLastReadTime = PR_IntervalNow();
1181
1182 if (mSocketIn)
1183 return mSocketIn->AsyncWait(this, 0, 0, nullptr);
1184
1185 NS_NOTREACHED("no socket input stream");
1186 return NS_ERROR_UNEXPECTED;
1187 }
1188
1189
1190 class nsHttpConnectionForceRecv : public nsRunnable
1191 {
1192 public:
1193 nsHttpConnectionForceRecv(nsHttpConnection *aConn)
1194 : mConn(aConn) {}
1195
1196 NS_IMETHOD Run()
1197 {
1198 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
1199
1200 if (!mConn->mSocketIn)
1201 return NS_OK;
1202 return mConn->OnInputStreamReady(mConn->mSocketIn);
1203 }
1204 private:
1205 nsRefPtr<nsHttpConnection> mConn;
1206 };
1207
1208 // trigger an asynchronous read
1209 nsresult
1210 nsHttpConnection::ForceRecv()
1211 {
1212 LOG(("nsHttpConnection::ForceRecv [this=%p]\n", this));
1213 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
1214
1215 return NS_DispatchToCurrentThread(new nsHttpConnectionForceRecv(this));
1216 }
1217
1218 void
1219 nsHttpConnection::BeginIdleMonitoring()
1220 {
1221 LOG(("nsHttpConnection::BeginIdleMonitoring [this=%p]\n", this));
1222 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
1223 MOZ_ASSERT(!mTransaction, "BeginIdleMonitoring() while active");
1224 MOZ_ASSERT(!mUsingSpdyVersion, "Idle monitoring of spdy not allowed");
1225
1226 LOG(("Entering Idle Monitoring Mode [this=%p]", this));
1227 mIdleMonitoring = true;
1228 if (mSocketIn)
1229 mSocketIn->AsyncWait(this, 0, 0, nullptr);
1230 }
1231
1232 void
1233 nsHttpConnection::EndIdleMonitoring()
1234 {
1235 LOG(("nsHttpConnection::EndIdleMonitoring [this=%p]\n", this));
1236 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
1237 MOZ_ASSERT(!mTransaction, "EndIdleMonitoring() while active");
1238
1239 if (mIdleMonitoring) {
1240 LOG(("Leaving Idle Monitoring Mode [this=%p]", this));
1241 mIdleMonitoring = false;
1242 if (mSocketIn)
1243 mSocketIn->AsyncWait(nullptr, 0, 0, nullptr);
1244 }
1245 }
1246
1247 //-----------------------------------------------------------------------------
1248 // nsHttpConnection <private>
1249 //-----------------------------------------------------------------------------
1250
1251 void
1252 nsHttpConnection::CloseTransaction(nsAHttpTransaction *trans, nsresult reason)
1253 {
1254 LOG(("nsHttpConnection::CloseTransaction[this=%p trans=%x reason=%x]\n",
1255 this, trans, reason));
1256
1257 MOZ_ASSERT(trans == mTransaction, "wrong transaction");
1258 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
1259
1260 if (mCurrentBytesRead > mMaxBytesRead)
1261 mMaxBytesRead = mCurrentBytesRead;
1262
1263 // mask this error code because its not a real error.
1264 if (reason == NS_BASE_STREAM_CLOSED)
1265 reason = NS_OK;
1266
1267 if (mUsingSpdyVersion) {
1268 DontReuse();
1269 // if !mSpdySession then mUsingSpdyVersion must be false for canreuse()
1270 mUsingSpdyVersion = 0;
1271 mSpdySession = nullptr;
1272 }
1273
1274 if (mTransaction) {
1275 mHttp1xTransactionCount += mTransaction->Http1xTransactionCount();
1276
1277 mTransaction->Close(reason);
1278 mTransaction = nullptr;
1279 }
1280
1281 {
1282 MutexAutoLock lock(mCallbacksLock);
1283 mCallbacks = nullptr;
1284 }
1285
1286 if (NS_FAILED(reason))
1287 Close(reason);
1288
1289 // flag the connection as reused here for convenience sake. certainly
1290 // it might be going away instead ;-)
1291 mIsReused = true;
1292 }
1293
1294 NS_METHOD
1295 nsHttpConnection::ReadFromStream(nsIInputStream *input,
1296 void *closure,
1297 const char *buf,
1298 uint32_t offset,
1299 uint32_t count,
1300 uint32_t *countRead)
1301 {
1302 // thunk for nsIInputStream instance
1303 nsHttpConnection *conn = (nsHttpConnection *) closure;
1304 return conn->OnReadSegment(buf, count, countRead);
1305 }
1306
1307 nsresult
1308 nsHttpConnection::OnReadSegment(const char *buf,
1309 uint32_t count,
1310 uint32_t *countRead)
1311 {
1312 if (count == 0) {
1313 // some ReadSegments implementations will erroneously call the writer
1314 // to consume 0 bytes worth of data. we must protect against this case
1315 // or else we'd end up closing the socket prematurely.
1316 NS_ERROR("bad ReadSegments implementation");
1317 return NS_ERROR_FAILURE; // stop iterating
1318 }
1319
1320 nsresult rv = mSocketOut->Write(buf, count, countRead);
1321 if (NS_FAILED(rv))
1322 mSocketOutCondition = rv;
1323 else if (*countRead == 0)
1324 mSocketOutCondition = NS_BASE_STREAM_CLOSED;
1325 else {
1326 mLastWriteTime = PR_IntervalNow();
1327 mSocketOutCondition = NS_OK; // reset condition
1328 if (!mProxyConnectInProgress)
1329 mTotalBytesWritten += *countRead;
1330 }
1331
1332 return mSocketOutCondition;
1333 }
1334
1335 nsresult
1336 nsHttpConnection::OnSocketWritable()
1337 {
1338 LOG(("nsHttpConnection::OnSocketWritable [this=%p] host=%s\n",
1339 this, mConnInfo->Host()));
1340
1341 nsresult rv;
1342 uint32_t n;
1343 bool again = true;
1344
1345 do {
1346 mSocketOutCondition = NS_OK;
1347
1348 // If we're doing a proxy connect, then we need to bypass calling into
1349 // the transaction.
1350 //
1351 // NOTE: this code path can't be shared since the transaction doesn't
1352 // implement nsIInputStream. doing so is not worth the added cost of
1353 // extra indirections during normal reading.
1354 //
1355 if (mProxyConnectStream) {
1356 LOG((" writing CONNECT request stream\n"));
1357 rv = mProxyConnectStream->ReadSegments(ReadFromStream, this,
1358 nsIOService::gDefaultSegmentSize,
1359 &n);
1360 }
1361 else if (!EnsureNPNComplete()) {
1362 // When SPDY is disabled this branch is not executed because Activate()
1363 // sets mNPNComplete to true in that case.
1364
1365 // We are ready to proceed with SSL but the handshake is not done.
1366 // When using NPN to negotiate between HTTPS and SPDY, we need to
1367 // see the results of the handshake to know what bytes to send, so
1368 // we cannot proceed with the request headers.
1369
1370 rv = NS_OK;
1371 mSocketOutCondition = NS_BASE_STREAM_WOULD_BLOCK;
1372 n = 0;
1373 }
1374 else {
1375 if (!mReportedSpdy) {
1376 mReportedSpdy = true;
1377 gHttpHandler->ConnMgr()->ReportSpdyConnection(this, mEverUsedSpdy);
1378 }
1379
1380 LOG((" writing transaction request stream\n"));
1381 mProxyConnectInProgress = false;
1382 rv = mTransaction->ReadSegments(this, nsIOService::gDefaultSegmentSize, &n);
1383 }
1384
1385 LOG((" ReadSegments returned [rv=%x read=%u sock-cond=%x]\n",
1386 rv, n, mSocketOutCondition));
1387
1388 // XXX some streams return NS_BASE_STREAM_CLOSED to indicate EOF.
1389 if (rv == NS_BASE_STREAM_CLOSED && !mTransaction->IsDone()) {
1390 rv = NS_OK;
1391 n = 0;
1392 }
1393
1394 if (NS_FAILED(rv)) {
1395 // if the transaction didn't want to write any more data, then
1396 // wait for the transaction to call ResumeSend.
1397 if (rv == NS_BASE_STREAM_WOULD_BLOCK)
1398 rv = NS_OK;
1399 again = false;
1400 }
1401 else if (NS_FAILED(mSocketOutCondition)) {
1402 if (mSocketOutCondition == NS_BASE_STREAM_WOULD_BLOCK)
1403 rv = mSocketOut->AsyncWait(this, 0, 0, nullptr); // continue writing
1404 else
1405 rv = mSocketOutCondition;
1406 again = false;
1407 }
1408 else if (n == 0) {
1409 rv = NS_OK;
1410
1411 if (mTransaction) { // in case the ReadSegments stack called CloseTransaction()
1412 //
1413 // at this point we've written out the entire transaction, and now we
1414 // must wait for the server's response. we manufacture a status message
1415 // here to reflect the fact that we are waiting. this message will be
1416 // trumped (overwritten) if the server responds quickly.
1417 //
1418 mTransaction->OnTransportStatus(mSocketTransport,
1419 NS_NET_STATUS_WAITING_FOR,
1420 0);
1421
1422 rv = ResumeRecv(); // start reading
1423 }
1424 again = false;
1425 }
1426 // write more to the socket until error or end-of-request...
1427 } while (again);
1428
1429 return rv;
1430 }
1431
1432 nsresult
1433 nsHttpConnection::OnWriteSegment(char *buf,
1434 uint32_t count,
1435 uint32_t *countWritten)
1436 {
1437 if (count == 0) {
1438 // some WriteSegments implementations will erroneously call the reader
1439 // to provide 0 bytes worth of data. we must protect against this case
1440 // or else we'd end up closing the socket prematurely.
1441 NS_ERROR("bad WriteSegments implementation");
1442 return NS_ERROR_FAILURE; // stop iterating
1443 }
1444
1445 if (ChaosMode::isActive() && ChaosMode::randomUint32LessThan(2)) {
1446 // read 1...count bytes
1447 count = ChaosMode::randomUint32LessThan(count) + 1;
1448 }
1449
1450 nsresult rv = mSocketIn->Read(buf, count, countWritten);
1451 if (NS_FAILED(rv))
1452 mSocketInCondition = rv;
1453 else if (*countWritten == 0)
1454 mSocketInCondition = NS_BASE_STREAM_CLOSED;
1455 else
1456 mSocketInCondition = NS_OK; // reset condition
1457
1458 return mSocketInCondition;
1459 }
1460
1461 nsresult
1462 nsHttpConnection::OnSocketReadable()
1463 {
1464 LOG(("nsHttpConnection::OnSocketReadable [this=%p]\n", this));
1465
1466 PRIntervalTime now = PR_IntervalNow();
1467 PRIntervalTime delta = now - mLastReadTime;
1468
1469 // Reset mResponseTimeoutEnabled to stop response timeout checks.
1470 mResponseTimeoutEnabled = false;
1471
1472 if (mKeepAliveMask && (delta >= mMaxHangTime)) {
1473 LOG(("max hang time exceeded!\n"));
1474 // give the handler a chance to create a new persistent connection to
1475 // this host if we've been busy for too long.
1476 mKeepAliveMask = false;
1477 gHttpHandler->ProcessPendingQ(mConnInfo);
1478 }
1479
1480 // Look for data being sent in bursts with large pauses. If the pauses
1481 // are caused by server bottlenecks such as think-time, disk i/o, or
1482 // cpu exhaustion (as opposed to network latency) then we generate negative
1483 // pipelining feedback to prevent head of line problems
1484
1485 // Reduce the estimate of the time since last read by up to 1 RTT to
1486 // accommodate exhausted sender TCP congestion windows or minor I/O delays.
1487
1488 if (delta > mRtt)
1489 delta -= mRtt;
1490 else
1491 delta = 0;
1492
1493 static const PRIntervalTime k400ms = PR_MillisecondsToInterval(400);
1494
1495 if (delta >= (mRtt + gHttpHandler->GetPipelineRescheduleTimeout())) {
1496 LOG(("Read delta ms of %u causing slow read major "
1497 "event and pipeline cancellation",
1498 PR_IntervalToMilliseconds(delta)));
1499
1500 gHttpHandler->ConnMgr()->PipelineFeedbackInfo(
1501 mConnInfo, nsHttpConnectionMgr::BadSlowReadMajor, this, 0);
1502
1503 if (gHttpHandler->GetPipelineRescheduleOnTimeout() &&
1504 mTransaction->PipelineDepth() > 1) {
1505 nsHttpPipeline *pipeline = mTransaction->QueryPipeline();
1506 MOZ_ASSERT(pipeline, "pipelinedepth > 1 without pipeline");
1507 // code this defensively for the moment and check for null
1508 // This will reschedule blocked members of the pipeline, but the
1509 // blocking transaction (i.e. response 0) will not be changed.
1510 if (pipeline) {
1511 pipeline->CancelPipeline(NS_ERROR_NET_TIMEOUT);
1512 LOG(("Rescheduling the head of line blocked members of a "
1513 "pipeline because reschedule-timeout idle interval "
1514 "exceeded"));
1515 }
1516 }
1517 }
1518 else if (delta > k400ms) {
1519 gHttpHandler->ConnMgr()->PipelineFeedbackInfo(
1520 mConnInfo, nsHttpConnectionMgr::BadSlowReadMinor, this, 0);
1521 }
1522
1523 mLastReadTime = now;
1524
1525 nsresult rv;
1526 uint32_t n;
1527 bool again = true;
1528
1529 do {
1530 if (!mProxyConnectInProgress && !mNPNComplete) {
1531 // Unless we are setting up a tunnel via CONNECT, prevent reading
1532 // from the socket until the results of NPN
1533 // negotiation are known (which is determined from the write path).
1534 // If the server speaks SPDY it is likely the readable data here is
1535 // a spdy settings frame and without NPN it would be misinterpreted
1536 // as HTTP/*
1537
1538 LOG(("nsHttpConnection::OnSocketReadable %p return due to inactive "
1539 "tunnel setup but incomplete NPN state\n", this));
1540 rv = NS_OK;
1541 break;
1542 }
1543
1544 rv = mTransaction->WriteSegments(this, nsIOService::gDefaultSegmentSize, &n);
1545 if (NS_FAILED(rv)) {
1546 // if the transaction didn't want to take any more data, then
1547 // wait for the transaction to call ResumeRecv.
1548 if (rv == NS_BASE_STREAM_WOULD_BLOCK)
1549 rv = NS_OK;
1550 again = false;
1551 }
1552 else {
1553 mCurrentBytesRead += n;
1554 mTotalBytesRead += n;
1555 if (NS_FAILED(mSocketInCondition)) {
1556 // continue waiting for the socket if necessary...
1557 if (mSocketInCondition == NS_BASE_STREAM_WOULD_BLOCK)
1558 rv = ResumeRecv();
1559 else
1560 rv = mSocketInCondition;
1561 again = false;
1562 }
1563 }
1564 // read more from the socket until error...
1565 } while (again);
1566
1567 return rv;
1568 }
1569
1570 nsresult
1571 nsHttpConnection::SetupProxyConnect()
1572 {
1573 const char *val;
1574
1575 LOG(("nsHttpConnection::SetupProxyConnect [this=%p]\n", this));
1576
1577 NS_ENSURE_TRUE(!mProxyConnectStream, NS_ERROR_ALREADY_INITIALIZED);
1578 MOZ_ASSERT(!mUsingSpdyVersion,
1579 "SPDY NPN Complete while using proxy connect stream");
1580
1581 nsAutoCString buf;
1582 nsresult rv = nsHttpHandler::GenerateHostPort(
1583 nsDependentCString(mConnInfo->Host()), mConnInfo->Port(), buf);
1584 if (NS_FAILED(rv))
1585 return rv;
1586
1587 // CONNECT host:port HTTP/1.1
1588 nsHttpRequestHead request;
1589 request.SetMethod(NS_LITERAL_CSTRING("CONNECT"));
1590 request.SetVersion(gHttpHandler->HttpVersion());
1591 request.SetRequestURI(buf);
1592 request.SetHeader(nsHttp::User_Agent, gHttpHandler->UserAgent());
1593
1594 // a CONNECT is always persistent
1595 request.SetHeader(nsHttp::Proxy_Connection, NS_LITERAL_CSTRING("keep-alive"));
1596 request.SetHeader(nsHttp::Connection, NS_LITERAL_CSTRING("keep-alive"));
1597
1598 // all HTTP/1.1 requests must include a Host header (even though it
1599 // may seem redundant in this case; see bug 82388).
1600 request.SetHeader(nsHttp::Host, buf);
1601
1602 val = mTransaction->RequestHead()->PeekHeader(nsHttp::Proxy_Authorization);
1603 if (val) {
1604 // we don't know for sure if this authorization is intended for the
1605 // SSL proxy, so we add it just in case.
1606 request.SetHeader(nsHttp::Proxy_Authorization, nsDependentCString(val));
1607 }
1608
1609 buf.Truncate();
1610 request.Flatten(buf, false);
1611 buf.AppendLiteral("\r\n");
1612
1613 return NS_NewCStringInputStream(getter_AddRefs(mProxyConnectStream), buf);
1614 }
1615
1616 nsresult
1617 nsHttpConnection::StartShortLivedTCPKeepalives()
1618 {
1619 if (mUsingSpdyVersion) {
1620 return NS_OK;
1621 }
1622 MOZ_ASSERT(mSocketTransport);
1623 if (!mSocketTransport) {
1624 return NS_ERROR_NOT_INITIALIZED;
1625 }
1626
1627 nsresult rv = NS_OK;
1628 int32_t idleTimeS = -1;
1629 int32_t retryIntervalS = -1;
1630 if (gHttpHandler->TCPKeepaliveEnabledForShortLivedConns()) {
1631 // Set the idle time.
1632 idleTimeS = gHttpHandler->GetTCPKeepaliveShortLivedIdleTime();
1633 LOG(("nsHttpConnection::StartShortLivedTCPKeepalives[%p] "
1634 "idle time[%ds].", this, idleTimeS));
1635
1636 retryIntervalS =
1637 std::max<int32_t>((int32_t)PR_IntervalToSeconds(mRtt), 1);
1638 rv = mSocketTransport->SetKeepaliveVals(idleTimeS, retryIntervalS);
1639 if (NS_WARN_IF(NS_FAILED(rv))) {
1640 return rv;
1641 }
1642 rv = mSocketTransport->SetKeepaliveEnabled(true);
1643 mTCPKeepaliveConfig = kTCPKeepaliveShortLivedConfig;
1644 } else {
1645 rv = mSocketTransport->SetKeepaliveEnabled(false);
1646 mTCPKeepaliveConfig = kTCPKeepaliveDisabled;
1647 }
1648 if (NS_WARN_IF(NS_FAILED(rv))) {
1649 return rv;
1650 }
1651
1652 // Start a timer to move to long-lived keepalive config.
1653 if(!mTCPKeepaliveTransitionTimer) {
1654 mTCPKeepaliveTransitionTimer =
1655 do_CreateInstance("@mozilla.org/timer;1");
1656 }
1657
1658 if (mTCPKeepaliveTransitionTimer) {
1659 int32_t time = gHttpHandler->GetTCPKeepaliveShortLivedTime();
1660
1661 // Adjust |time| to ensure a full set of keepalive probes can be sent
1662 // at the end of the short-lived phase.
1663 if (gHttpHandler->TCPKeepaliveEnabledForShortLivedConns()) {
1664 if (NS_WARN_IF(!gSocketTransportService)) {
1665 return NS_ERROR_NOT_INITIALIZED;
1666 }
1667 int32_t probeCount = -1;
1668 rv = gSocketTransportService->GetKeepaliveProbeCount(&probeCount);
1669 if (NS_WARN_IF(NS_FAILED(rv))) {
1670 return rv;
1671 }
1672 if (NS_WARN_IF(probeCount <= 0)) {
1673 return NS_ERROR_UNEXPECTED;
1674 }
1675 // Add time for final keepalive probes, and 2 seconds for a buffer.
1676 time += ((probeCount) * retryIntervalS) - (time % idleTimeS) + 2;
1677 }
1678 mTCPKeepaliveTransitionTimer->InitWithFuncCallback(
1679 nsHttpConnection::UpdateTCPKeepalive,
1680 this,
1681 (uint32_t)time*1000,
1682 nsITimer::TYPE_ONE_SHOT);
1683 } else {
1684 NS_WARNING("nsHttpConnection::StartShortLivedTCPKeepalives failed to "
1685 "create timer.");
1686 }
1687
1688 return NS_OK;
1689 }
1690
1691 nsresult
1692 nsHttpConnection::StartLongLivedTCPKeepalives()
1693 {
1694 MOZ_ASSERT(!mUsingSpdyVersion, "Don't use TCP Keepalive with SPDY!");
1695 if (NS_WARN_IF(mUsingSpdyVersion)) {
1696 return NS_OK;
1697 }
1698 MOZ_ASSERT(mSocketTransport);
1699 if (!mSocketTransport) {
1700 return NS_ERROR_NOT_INITIALIZED;
1701 }
1702
1703 nsresult rv = NS_OK;
1704 if (gHttpHandler->TCPKeepaliveEnabledForLongLivedConns()) {
1705 // Increase the idle time.
1706 int32_t idleTimeS = gHttpHandler->GetTCPKeepaliveLongLivedIdleTime();
1707 LOG(("nsHttpConnection::StartLongLivedTCPKeepalives[%p] idle time[%ds]",
1708 this, idleTimeS));
1709
1710 int32_t retryIntervalS =
1711 std::max<int32_t>((int32_t)PR_IntervalToSeconds(mRtt), 1);
1712 rv = mSocketTransport->SetKeepaliveVals(idleTimeS, retryIntervalS);
1713 if (NS_WARN_IF(NS_FAILED(rv))) {
1714 return rv;
1715 }
1716
1717 // Ensure keepalive is enabled, if current status is disabled.
1718 if (mTCPKeepaliveConfig == kTCPKeepaliveDisabled) {
1719 rv = mSocketTransport->SetKeepaliveEnabled(true);
1720 if (NS_WARN_IF(NS_FAILED(rv))) {
1721 return rv;
1722 }
1723 }
1724 mTCPKeepaliveConfig = kTCPKeepaliveLongLivedConfig;
1725 } else {
1726 rv = mSocketTransport->SetKeepaliveEnabled(false);
1727 mTCPKeepaliveConfig = kTCPKeepaliveDisabled;
1728 }
1729
1730 if (NS_WARN_IF(NS_FAILED(rv))) {
1731 return rv;
1732 }
1733 return NS_OK;
1734 }
1735
1736 nsresult
1737 nsHttpConnection::DisableTCPKeepalives()
1738 {
1739 MOZ_ASSERT(mSocketTransport);
1740 if (!mSocketTransport) {
1741 return NS_ERROR_NOT_INITIALIZED;
1742 }
1743 LOG(("nsHttpConnection::DisableTCPKeepalives [%p]", this));
1744 if (mTCPKeepaliveConfig != kTCPKeepaliveDisabled) {
1745 nsresult rv = mSocketTransport->SetKeepaliveEnabled(false);
1746 if (NS_WARN_IF(NS_FAILED(rv))) {
1747 return rv;
1748 }
1749 mTCPKeepaliveConfig = kTCPKeepaliveDisabled;
1750 }
1751 if (mTCPKeepaliveTransitionTimer) {
1752 mTCPKeepaliveTransitionTimer->Cancel();
1753 mTCPKeepaliveTransitionTimer = nullptr;
1754 }
1755 return NS_OK;
1756 }
1757
1758 //-----------------------------------------------------------------------------
1759 // nsHttpConnection::nsISupports
1760 //-----------------------------------------------------------------------------
1761
1762 NS_IMPL_ISUPPORTS(nsHttpConnection,
1763 nsIInputStreamCallback,
1764 nsIOutputStreamCallback,
1765 nsITransportEventSink,
1766 nsIInterfaceRequestor)
1767
1768 //-----------------------------------------------------------------------------
1769 // nsHttpConnection::nsIInputStreamCallback
1770 //-----------------------------------------------------------------------------
1771
1772 // called on the socket transport thread
1773 NS_IMETHODIMP
1774 nsHttpConnection::OnInputStreamReady(nsIAsyncInputStream *in)
1775 {
1776 MOZ_ASSERT(in == mSocketIn, "unexpected stream");
1777 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
1778
1779 if (mIdleMonitoring) {
1780 MOZ_ASSERT(!mTransaction, "Idle Input Event While Active");
1781
1782 // The only read event that is protocol compliant for an idle connection
1783 // is an EOF, which we check for with CanReuse(). If the data is
1784 // something else then just ignore it and suspend checking for EOF -
1785 // our normal timers or protocol stack are the place to deal with
1786 // any exception logic.
1787
1788 if (!CanReuse()) {
1789 LOG(("Server initiated close of idle conn %p\n", this));
1790 gHttpHandler->ConnMgr()->CloseIdleConnection(this);
1791 return NS_OK;
1792 }
1793
1794 LOG(("Input data on idle conn %p, but not closing yet\n", this));
1795 return NS_OK;
1796 }
1797
1798 // if the transaction was dropped...
1799 if (!mTransaction) {
1800 LOG((" no transaction; ignoring event\n"));
1801 return NS_OK;
1802 }
1803
1804 nsresult rv = OnSocketReadable();
1805 if (NS_FAILED(rv))
1806 CloseTransaction(mTransaction, rv);
1807
1808 return NS_OK;
1809 }
1810
1811 //-----------------------------------------------------------------------------
1812 // nsHttpConnection::nsIOutputStreamCallback
1813 //-----------------------------------------------------------------------------
1814
1815 NS_IMETHODIMP
1816 nsHttpConnection::OnOutputStreamReady(nsIAsyncOutputStream *out)
1817 {
1818 MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
1819 MOZ_ASSERT(out == mSocketOut, "unexpected socket");
1820
1821 // if the transaction was dropped...
1822 if (!mTransaction) {
1823 LOG((" no transaction; ignoring event\n"));
1824 return NS_OK;
1825 }
1826
1827 nsresult rv = OnSocketWritable();
1828 if (NS_FAILED(rv))
1829 CloseTransaction(mTransaction, rv);
1830
1831 return NS_OK;
1832 }
1833
1834 //-----------------------------------------------------------------------------
1835 // nsHttpConnection::nsITransportEventSink
1836 //-----------------------------------------------------------------------------
1837
1838 NS_IMETHODIMP
1839 nsHttpConnection::OnTransportStatus(nsITransport *trans,
1840 nsresult status,
1841 uint64_t progress,
1842 uint64_t progressMax)
1843 {
1844 if (mTransaction)
1845 mTransaction->OnTransportStatus(trans, status, progress);
1846 return NS_OK;
1847 }
1848
1849 //-----------------------------------------------------------------------------
1850 // nsHttpConnection::nsIInterfaceRequestor
1851 //-----------------------------------------------------------------------------
1852
1853 // not called on the socket transport thread
1854 NS_IMETHODIMP
1855 nsHttpConnection::GetInterface(const nsIID &iid, void **result)
1856 {
1857 // NOTE: This function is only called on the UI thread via sync proxy from
1858 // the socket transport thread. If that weren't the case, then we'd
1859 // have to worry about the possibility of mTransaction going away
1860 // part-way through this function call. See CloseTransaction.
1861
1862 // NOTE - there is a bug here, the call to getinterface is proxied off the
1863 // nss thread, not the ui thread as the above comment says. So there is
1864 // indeed a chance of mTransaction going away. bug 615342
1865
1866 MOZ_ASSERT(PR_GetCurrentThread() != gSocketThread);
1867
1868 nsCOMPtr<nsIInterfaceRequestor> callbacks;
1869 {
1870 MutexAutoLock lock(mCallbacksLock);
1871 callbacks = mCallbacks;
1872 }
1873 if (callbacks)
1874 return callbacks->GetInterface(iid, result);
1875 return NS_ERROR_NO_INTERFACE;
1876 }
1877
1878 } // namespace mozilla::net
1879 } // namespace mozilla

mercurial