Bug 458256. Use LoadLibraryW instead of LoadLibrary (patch by DougT). r+sr=vlad
[wine-gecko.git] / netwerk / protocol / http / src / nsHttpConnection.cpp
blob47f0e1cd9439478aa10b5af46e383c5e559d9083
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 /* ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
16 * The Original Code is Mozilla.
18 * The Initial Developer of the Original Code is
19 * Netscape Communications.
20 * Portions created by the Initial Developer are Copyright (C) 2001
21 * the Initial Developer. All Rights Reserved.
23 * Contributor(s):
24 * Darin Fisher <darin@netscape.com> (original author)
26 * Alternatively, the contents of this file may be used under the terms of
27 * either the GNU General Public License Version 2 or later (the "GPL"), or
28 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29 * in which case the provisions of the GPL or the LGPL are applicable instead
30 * of those above. If you wish to allow use of your version of this file only
31 * under the terms of either the GPL or the LGPL, and not to allow others to
32 * use your version of this file under the terms of the MPL, indicate your
33 * decision by deleting the provisions above and replace them with the notice
34 * and other provisions required by the GPL or the LGPL. If you do not delete
35 * the provisions above, a recipient may use your version of this file under
36 * the terms of any one of the MPL, the GPL or the LGPL.
38 * ***** END LICENSE BLOCK ***** */
40 #include "nsHttpConnection.h"
41 #include "nsHttpTransaction.h"
42 #include "nsHttpRequestHead.h"
43 #include "nsHttpResponseHead.h"
44 #include "nsHttpHandler.h"
45 #include "nsISocketTransportService.h"
46 #include "nsISocketTransport.h"
47 #include "nsIServiceManager.h"
48 #include "nsISSLSocketControl.h"
49 #include "nsStringStream.h"
50 #include "netCore.h"
51 #include "nsNetCID.h"
52 #include "nsAutoLock.h"
53 #include "prmem.h"
55 #ifdef DEBUG
56 // defined by the socket transport service while active
57 extern PRThread *gSocketThread;
58 #endif
60 static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID);
62 //-----------------------------------------------------------------------------
63 // nsHttpConnection <public>
64 //-----------------------------------------------------------------------------
66 nsHttpConnection::nsHttpConnection()
67 : mTransaction(nsnull)
68 , mConnInfo(nsnull)
69 , mLock(nsnull)
70 , mLastReadTime(0)
71 , mIdleTimeout(0)
72 , mKeepAlive(PR_TRUE) // assume to keep-alive by default
73 , mKeepAliveMask(PR_TRUE)
74 , mSupportsPipelining(PR_FALSE) // assume low-grade server
75 , mIsReused(PR_FALSE)
76 , mCompletedSSLConnect(PR_FALSE)
78 LOG(("Creating nsHttpConnection @%x\n", this));
80 // grab a reference to the handler to ensure that it doesn't go away.
81 nsHttpHandler *handler = gHttpHandler;
82 NS_ADDREF(handler);
85 nsHttpConnection::~nsHttpConnection()
87 LOG(("Destroying nsHttpConnection @%x\n", this));
89 NS_IF_RELEASE(mConnInfo);
90 NS_IF_RELEASE(mTransaction);
92 if (mLock) {
93 PR_DestroyLock(mLock);
94 mLock = nsnull;
97 // release our reference to the handler
98 nsHttpHandler *handler = gHttpHandler;
99 NS_RELEASE(handler);
102 nsresult
103 nsHttpConnection::Init(nsHttpConnectionInfo *info, PRUint16 maxHangTime)
105 LOG(("nsHttpConnection::Init [this=%x]\n", this));
107 NS_ENSURE_ARG_POINTER(info);
108 NS_ENSURE_TRUE(!mConnInfo, NS_ERROR_ALREADY_INITIALIZED);
110 mLock = PR_NewLock();
111 if (!mLock)
112 return NS_ERROR_OUT_OF_MEMORY;
114 mConnInfo = info;
115 NS_ADDREF(mConnInfo);
117 mMaxHangTime = maxHangTime;
118 mLastReadTime = NowInSeconds();
119 return NS_OK;
122 // called on the socket thread
123 nsresult
124 nsHttpConnection::Activate(nsAHttpTransaction *trans, PRUint8 caps)
126 nsresult rv;
128 LOG(("nsHttpConnection::Activate [this=%x trans=%x caps=%x]\n",
129 this, trans, caps));
131 NS_ENSURE_ARG_POINTER(trans);
132 NS_ENSURE_TRUE(!mTransaction, NS_ERROR_IN_PROGRESS);
134 // take ownership of the transaction
135 mTransaction = trans;
136 NS_ADDREF(mTransaction);
138 // set mKeepAlive according to what will be requested
139 mKeepAliveMask = mKeepAlive = (caps & NS_HTTP_ALLOW_KEEPALIVE);
141 // if we don't have a socket transport then create a new one
142 if (!mSocketTransport) {
143 rv = CreateTransport();
144 if (NS_FAILED(rv))
145 goto loser;
148 // need to handle SSL proxy CONNECT if this is the first time.
149 if (mConnInfo->UsingSSL() && mConnInfo->UsingHttpProxy() && !mCompletedSSLConnect) {
150 rv = SetupSSLProxyConnect();
151 if (NS_FAILED(rv))
152 goto loser;
155 // wait for the output stream to be readable
156 rv = mSocketOut->AsyncWait(this, 0, 0, nsnull);
157 if (NS_SUCCEEDED(rv))
158 return rv;
160 loser:
161 NS_RELEASE(mTransaction);
162 return rv;
165 void
166 nsHttpConnection::Close(nsresult reason)
168 LOG(("nsHttpConnection::Close [this=%x reason=%x]\n", this, reason));
170 NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
172 if (NS_FAILED(reason)) {
173 if (mSocketTransport) {
174 mSocketTransport->SetSecurityCallbacks(nsnull);
175 mSocketTransport->SetEventSink(nsnull, nsnull);
176 mSocketTransport->Close(reason);
178 mKeepAlive = PR_FALSE;
182 // called on the socket thread
183 nsresult
184 nsHttpConnection::ProxyStartSSL()
186 LOG(("nsHttpConnection::ProxyStartSSL [this=%x]\n", this));
187 #ifdef DEBUG
188 NS_PRECONDITION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
189 #endif
191 nsCOMPtr<nsISupports> securityInfo;
192 nsresult rv = mSocketTransport->GetSecurityInfo(getter_AddRefs(securityInfo));
193 if (NS_FAILED(rv)) return rv;
195 nsCOMPtr<nsISSLSocketControl> ssl = do_QueryInterface(securityInfo, &rv);
196 if (NS_FAILED(rv)) return rv;
198 return ssl->ProxyStartSSL();
201 PRBool
202 nsHttpConnection::CanReuse()
204 return IsKeepAlive() && (NowInSeconds() - mLastReadTime < mIdleTimeout)
205 && IsAlive();
208 PRBool
209 nsHttpConnection::IsAlive()
211 if (!mSocketTransport)
212 return PR_FALSE;
214 PRBool alive;
215 nsresult rv = mSocketTransport->IsAlive(&alive);
216 if (NS_FAILED(rv))
217 alive = PR_FALSE;
219 //#define TEST_RESTART_LOGIC
220 #ifdef TEST_RESTART_LOGIC
221 if (!alive) {
222 LOG(("pretending socket is still alive to test restart logic\n"));
223 alive = PR_TRUE;
225 #endif
227 return alive;
230 PRBool
231 nsHttpConnection::SupportsPipelining(nsHttpResponseHead *responseHead)
233 // XXX there should be a strict mode available that disables this
234 // blacklisting.
236 // assuming connection is HTTP/1.1 with keep-alive enabled
237 if (mConnInfo->UsingHttpProxy() && !mConnInfo->UsingSSL()) {
238 // XXX check for bad proxy servers...
239 return PR_TRUE;
242 // XXX what about checking for a Via header? (transparent proxies)
244 // check for bad origin servers
245 const char *val = responseHead->PeekHeader(nsHttp::Server);
246 if (!val)
247 return PR_FALSE; // no header, no love
249 // the list of servers known to do bad things with pipelined requests
250 static const char *bad_servers[] = {
251 "Microsoft-IIS/4.",
252 "Microsoft-IIS/5.",
253 "Netscape-Enterprise/3.",
254 nsnull
257 for (const char **server = bad_servers; *server; ++server) {
258 if (PL_strcasestr(val, *server) != nsnull) {
259 LOG(("looks like this server does not support pipelining"));
260 return PR_FALSE;
264 // ok, let's allow pipelining to this server
265 return PR_TRUE;
268 //----------------------------------------------------------------------------
269 // nsHttpConnection::nsAHttpConnection compatible methods
270 //----------------------------------------------------------------------------
272 nsresult
273 nsHttpConnection::OnHeadersAvailable(nsAHttpTransaction *trans,
274 nsHttpRequestHead *requestHead,
275 nsHttpResponseHead *responseHead,
276 PRBool *reset)
278 LOG(("nsHttpConnection::OnHeadersAvailable [this=%p trans=%p response-head=%p]\n",
279 this, trans, responseHead));
281 NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
282 NS_ENSURE_ARG_POINTER(trans);
283 NS_ASSERTION(responseHead, "No response head?");
285 // If the server issued an explicit timeout, then we need to close down the
286 // socket transport. We pass an error code of NS_ERROR_NET_RESET to
287 // trigger the transactions 'restart' mechanism. We tell it to reset its
288 // response headers so that it will be ready to receive the new response.
289 if (responseHead->Status() == 408) {
290 Close(NS_ERROR_NET_RESET);
291 *reset = PR_TRUE;
292 return NS_OK;
295 // we won't change our keep-alive policy unless the server has explicitly
296 // told us to do so.
298 // inspect the connection headers for keep-alive info provided the
299 // transaction completed successfully.
300 const char *val = responseHead->PeekHeader(nsHttp::Connection);
301 if (!val)
302 val = responseHead->PeekHeader(nsHttp::Proxy_Connection);
304 // reset to default (the server may have changed since we last checked)
305 mSupportsPipelining = PR_FALSE;
307 if ((responseHead->Version() < NS_HTTP_VERSION_1_1) ||
308 (requestHead->Version() < NS_HTTP_VERSION_1_1)) {
309 // HTTP/1.0 connections are by default NOT persistent
310 if (val && !PL_strcasecmp(val, "keep-alive"))
311 mKeepAlive = PR_TRUE;
312 else
313 mKeepAlive = PR_FALSE;
315 else {
316 // HTTP/1.1 connections are by default persistent
317 if (val && !PL_strcasecmp(val, "close"))
318 mKeepAlive = PR_FALSE;
319 else {
320 mKeepAlive = PR_TRUE;
322 // Do not support pipelining when we are establishing
323 // an SSL tunnel though an HTTP proxy. Pipelining support
324 // determination must be based on comunication with the
325 // target server in this case. See bug 422016 for futher
326 // details.
327 if (!mSSLProxyConnectStream)
328 mSupportsPipelining = SupportsPipelining(responseHead);
331 mKeepAliveMask = mKeepAlive;
333 // if this connection is persistent, then the server may send a "Keep-Alive"
334 // header specifying the maximum number of times the connection can be
335 // reused as well as the maximum amount of time the connection can be idle
336 // before the server will close it. we ignore the max reuse count, because
337 // a "keep-alive" connection is by definition capable of being reused, and
338 // we only care about being able to reuse it once. if a timeout is not
339 // specified then we use our advertized timeout value.
340 if (mKeepAlive) {
341 val = responseHead->PeekHeader(nsHttp::Keep_Alive);
343 const char *cp = PL_strcasestr(val, "timeout=");
344 if (cp)
345 mIdleTimeout = (PRUint32) atoi(cp + 8);
346 else
347 mIdleTimeout = gHttpHandler->IdleTimeout();
349 LOG(("Connection can be reused [this=%x idle-timeout=%u]\n", this, mIdleTimeout));
352 // if we're doing an SSL proxy connect, then we need to check whether or not
353 // the connect was successful. if so, then we have to reset the transaction
354 // and step-up the socket connection to SSL. finally, we have to wake up the
355 // socket write request.
356 if (mSSLProxyConnectStream) {
357 mSSLProxyConnectStream = 0;
358 if (responseHead->Status() == 200) {
359 LOG(("SSL proxy CONNECT succeeded!\n"));
360 *reset = PR_TRUE;
361 nsresult rv = ProxyStartSSL();
362 if (NS_FAILED(rv)) // XXX need to handle this for real
363 LOG(("ProxyStartSSL failed [rv=%x]\n", rv));
364 mCompletedSSLConnect = PR_TRUE;
365 rv = mSocketOut->AsyncWait(this, 0, 0, nsnull);
366 // XXX what if this fails -- need to handle this error
367 NS_ASSERTION(NS_SUCCEEDED(rv), "mSocketOut->AsyncWait failed");
369 else {
370 LOG(("SSL proxy CONNECT failed!\n"));
371 // NOTE: this cast is valid since this connection cannot be
372 // processing a transaction pipeline until after the first HTTP/1.1
373 // response.
374 nsHttpTransaction *trans =
375 static_cast<nsHttpTransaction *>(mTransaction);
376 trans->SetSSLConnectFailed();
380 return NS_OK;
383 void
384 nsHttpConnection::GetSecurityInfo(nsISupports **secinfo)
386 NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
388 if (mSocketTransport) {
389 if (NS_FAILED(mSocketTransport->GetSecurityInfo(secinfo)))
390 *secinfo = nsnull;
394 nsresult
395 nsHttpConnection::ResumeSend()
397 LOG(("nsHttpConnection::ResumeSend [this=%p]\n", this));
399 NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
401 if (mSocketOut)
402 return mSocketOut->AsyncWait(this, 0, 0, nsnull);
404 NS_NOTREACHED("no socket output stream");
405 return NS_ERROR_UNEXPECTED;
408 nsresult
409 nsHttpConnection::ResumeRecv()
411 LOG(("nsHttpConnection::ResumeRecv [this=%p]\n", this));
413 NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
415 if (mSocketIn)
416 return mSocketIn->AsyncWait(this, 0, 0, nsnull);
418 NS_NOTREACHED("no socket input stream");
419 return NS_ERROR_UNEXPECTED;
422 //-----------------------------------------------------------------------------
423 // nsHttpConnection <private>
424 //-----------------------------------------------------------------------------
426 nsresult
427 nsHttpConnection::CreateTransport()
429 nsresult rv;
431 NS_PRECONDITION(!mSocketTransport, "unexpected");
433 nsCOMPtr<nsISocketTransportService> sts =
434 do_GetService(kSocketTransportServiceCID, &rv);
435 if (NS_FAILED(rv)) return rv;
437 // configure the socket type based on the connection type requested.
438 const char* types[1];
440 if (mConnInfo->UsingSSL())
441 types[0] = "ssl";
442 else
443 types[0] = gHttpHandler->DefaultSocketType();
445 nsCOMPtr<nsISocketTransport> strans;
446 PRUint32 typeCount = (types[0] != nsnull);
448 rv = sts->CreateTransport(types, typeCount,
449 nsDependentCString(mConnInfo->Host()),
450 mConnInfo->Port(),
451 mConnInfo->ProxyInfo(),
452 getter_AddRefs(strans));
453 if (NS_FAILED(rv)) return rv;
455 // NOTE: these create cyclical references, which we break inside
456 // nsHttpConnection::Close
457 rv = strans->SetEventSink(this, nsnull);
458 if (NS_FAILED(rv)) return rv;
459 rv = strans->SetSecurityCallbacks(this);
460 if (NS_FAILED(rv)) return rv;
462 // next open the socket streams
463 nsCOMPtr<nsIOutputStream> sout;
464 rv = strans->OpenOutputStream(nsITransport::OPEN_UNBUFFERED, 0, 0,
465 getter_AddRefs(sout));
466 if (NS_FAILED(rv)) return rv;
467 nsCOMPtr<nsIInputStream> sin;
468 rv = strans->OpenInputStream(nsITransport::OPEN_UNBUFFERED, 0, 0,
469 getter_AddRefs(sin));
470 if (NS_FAILED(rv)) return rv;
472 mSocketTransport = strans;
473 mSocketIn = do_QueryInterface(sin);
474 mSocketOut = do_QueryInterface(sout);
475 return NS_OK;
478 void
479 nsHttpConnection::CloseTransaction(nsAHttpTransaction *trans, nsresult reason)
481 LOG(("nsHttpConnection::CloseTransaction[this=%x trans=%x reason=%x]\n",
482 this, trans, reason));
484 NS_ASSERTION(trans == mTransaction, "wrong transaction");
485 NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
487 // mask this error code because its not a real error.
488 if (reason == NS_BASE_STREAM_CLOSED)
489 reason = NS_OK;
491 mTransaction->Close(reason);
493 NS_RELEASE(mTransaction);
494 mTransaction = 0;
496 if (NS_FAILED(reason))
497 Close(reason);
499 // flag the connection as reused here for convenience sake. certainly
500 // it might be going away instead ;-)
501 mIsReused = PR_TRUE;
504 NS_METHOD
505 nsHttpConnection::ReadFromStream(nsIInputStream *input,
506 void *closure,
507 const char *buf,
508 PRUint32 offset,
509 PRUint32 count,
510 PRUint32 *countRead)
512 // thunk for nsIInputStream instance
513 nsHttpConnection *conn = (nsHttpConnection *) closure;
514 return conn->OnReadSegment(buf, count, countRead);
517 nsresult
518 nsHttpConnection::OnReadSegment(const char *buf,
519 PRUint32 count,
520 PRUint32 *countRead)
522 if (count == 0) {
523 // some ReadSegments implementations will erroneously call the writer
524 // to consume 0 bytes worth of data. we must protect against this case
525 // or else we'd end up closing the socket prematurely.
526 NS_ERROR("bad ReadSegments implementation");
527 return NS_ERROR_FAILURE; // stop iterating
530 nsresult rv = mSocketOut->Write(buf, count, countRead);
531 if (NS_FAILED(rv))
532 mSocketOutCondition = rv;
533 else if (*countRead == 0)
534 mSocketOutCondition = NS_BASE_STREAM_CLOSED;
535 else
536 mSocketOutCondition = NS_OK; // reset condition
538 return mSocketOutCondition;
541 nsresult
542 nsHttpConnection::OnSocketWritable()
544 LOG(("nsHttpConnection::OnSocketWritable [this=%x]\n", this));
546 nsresult rv;
547 PRUint32 n;
548 PRBool again = PR_TRUE;
550 do {
551 // if we're doing an SSL proxy connect, then we need to bypass calling
552 // into the transaction.
554 // NOTE: this code path can't be shared since the transaction doesn't
555 // implement nsIInputStream. doing so is not worth the added cost of
556 // extra indirections during normal reading.
558 if (mSSLProxyConnectStream) {
559 LOG((" writing CONNECT request stream\n"));
560 rv = mSSLProxyConnectStream->ReadSegments(ReadFromStream, this,
561 NS_HTTP_SEGMENT_SIZE, &n);
563 else {
564 LOG((" writing transaction request stream\n"));
565 rv = mTransaction->ReadSegments(this, NS_HTTP_SEGMENT_SIZE, &n);
568 LOG((" ReadSegments returned [rv=%x read=%u sock-cond=%x]\n",
569 rv, n, mSocketOutCondition));
571 // XXX some streams return NS_BASE_STREAM_CLOSED to indicate EOF.
572 if (rv == NS_BASE_STREAM_CLOSED) {
573 rv = NS_OK;
574 n = 0;
577 if (NS_FAILED(rv)) {
578 // if the transaction didn't want to write any more data, then
579 // wait for the transaction to call ResumeSend.
580 if (rv == NS_BASE_STREAM_WOULD_BLOCK)
581 rv = NS_OK;
582 again = PR_FALSE;
584 else if (NS_FAILED(mSocketOutCondition)) {
585 if (mSocketOutCondition == NS_BASE_STREAM_WOULD_BLOCK)
586 rv = mSocketOut->AsyncWait(this, 0, 0, nsnull); // continue writing
587 else
588 rv = mSocketOutCondition;
589 again = PR_FALSE;
591 else if (n == 0) {
593 // at this point we've written out the entire transaction, and now we
594 // must wait for the server's response. we manufacture a status message
595 // here to reflect the fact that we are waiting. this message will be
596 // trumped (overwritten) if the server responds quickly.
598 mTransaction->OnTransportStatus(nsISocketTransport::STATUS_WAITING_FOR,
599 LL_ZERO);
601 rv = mSocketIn->AsyncWait(this, 0, 0, nsnull); // start reading
602 again = PR_FALSE;
604 // write more to the socket until error or end-of-request...
605 } while (again);
607 return rv;
610 nsresult
611 nsHttpConnection::OnWriteSegment(char *buf,
612 PRUint32 count,
613 PRUint32 *countWritten)
615 if (count == 0) {
616 // some WriteSegments implementations will erroneously call the reader
617 // to provide 0 bytes worth of data. we must protect against this case
618 // or else we'd end up closing the socket prematurely.
619 NS_ERROR("bad WriteSegments implementation");
620 return NS_ERROR_FAILURE; // stop iterating
623 nsresult rv = mSocketIn->Read(buf, count, countWritten);
624 if (NS_FAILED(rv))
625 mSocketInCondition = rv;
626 else if (*countWritten == 0)
627 mSocketInCondition = NS_BASE_STREAM_CLOSED;
628 else
629 mSocketInCondition = NS_OK; // reset condition
631 return mSocketInCondition;
634 nsresult
635 nsHttpConnection::OnSocketReadable()
637 LOG(("nsHttpConnection::OnSocketReadable [this=%x]\n", this));
639 PRUint32 now = NowInSeconds();
641 if (mKeepAliveMask && (now - mLastReadTime >= PRUint32(mMaxHangTime))) {
642 LOG(("max hang time exceeded!\n"));
643 // give the handler a chance to create a new persistent connection to
644 // this host if we've been busy for too long.
645 mKeepAliveMask = PR_FALSE;
646 gHttpHandler->ProcessPendingQ(mConnInfo);
648 mLastReadTime = now;
650 nsresult rv;
651 PRUint32 n;
652 PRBool again = PR_TRUE;
654 do {
655 rv = mTransaction->WriteSegments(this, NS_HTTP_SEGMENT_SIZE, &n);
656 if (NS_FAILED(rv)) {
657 // if the transaction didn't want to take any more data, then
658 // wait for the transaction to call ResumeRecv.
659 if (rv == NS_BASE_STREAM_WOULD_BLOCK)
660 rv = NS_OK;
661 again = PR_FALSE;
663 else if (NS_FAILED(mSocketInCondition)) {
664 // continue waiting for the socket if necessary...
665 if (mSocketInCondition == NS_BASE_STREAM_WOULD_BLOCK)
666 rv = mSocketIn->AsyncWait(this, 0, 0, nsnull);
667 else
668 rv = mSocketInCondition;
669 again = PR_FALSE;
671 // read more from the socket until error...
672 } while (again);
674 return rv;
677 nsresult
678 nsHttpConnection::SetupSSLProxyConnect()
680 const char *val;
682 LOG(("nsHttpConnection::SetupSSLProxyConnect [this=%x]\n", this));
684 NS_ENSURE_TRUE(!mSSLProxyConnectStream, NS_ERROR_ALREADY_INITIALIZED);
686 nsCAutoString buf;
687 buf.Assign(mConnInfo->Host());
688 buf.Append(':');
689 buf.AppendInt(mConnInfo->Port());
691 // CONNECT host:port HTTP/1.1
692 nsHttpRequestHead request;
693 request.SetMethod(nsHttp::Connect);
694 request.SetVersion(gHttpHandler->HttpVersion());
695 request.SetRequestURI(buf);
696 request.SetHeader(nsHttp::User_Agent, gHttpHandler->UserAgent());
698 // send this header for backwards compatibility.
699 request.SetHeader(nsHttp::Proxy_Connection, NS_LITERAL_CSTRING("keep-alive"));
701 // NOTE: this cast is valid since this connection cannot be processing a
702 // transaction pipeline until after the first HTTP/1.1 response.
703 nsHttpTransaction *trans = static_cast<nsHttpTransaction *>(mTransaction);
705 val = trans->RequestHead()->PeekHeader(nsHttp::Host);
706 if (val) {
707 // all HTTP/1.1 requests must include a Host header (even though it
708 // may seem redundant in this case; see bug 82388).
709 request.SetHeader(nsHttp::Host, nsDependentCString(val));
712 val = trans->RequestHead()->PeekHeader(nsHttp::Proxy_Authorization);
713 if (val) {
714 // we don't know for sure if this authorization is intended for the
715 // SSL proxy, so we add it just in case.
716 request.SetHeader(nsHttp::Proxy_Authorization, nsDependentCString(val));
719 buf.Truncate();
720 request.Flatten(buf, PR_FALSE);
721 buf.AppendLiteral("\r\n");
723 return NS_NewCStringInputStream(getter_AddRefs(mSSLProxyConnectStream), buf);
726 //-----------------------------------------------------------------------------
727 // nsHttpConnection::nsISupports
728 //-----------------------------------------------------------------------------
730 NS_IMPL_THREADSAFE_ISUPPORTS4(nsHttpConnection,
731 nsIInputStreamCallback,
732 nsIOutputStreamCallback,
733 nsITransportEventSink,
734 nsIInterfaceRequestor)
736 //-----------------------------------------------------------------------------
737 // nsHttpConnection::nsIInputStreamCallback
738 //-----------------------------------------------------------------------------
740 // called on the socket transport thread
741 NS_IMETHODIMP
742 nsHttpConnection::OnInputStreamReady(nsIAsyncInputStream *in)
744 NS_ASSERTION(in == mSocketIn, "unexpected stream");
745 NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
747 // if the transaction was dropped...
748 if (!mTransaction) {
749 LOG((" no transaction; ignoring event\n"));
750 return NS_OK;
753 nsresult rv = OnSocketReadable();
754 if (NS_FAILED(rv))
755 CloseTransaction(mTransaction, rv);
757 return NS_OK;
760 //-----------------------------------------------------------------------------
761 // nsHttpConnection::nsIOutputStreamCallback
762 //-----------------------------------------------------------------------------
764 NS_IMETHODIMP
765 nsHttpConnection::OnOutputStreamReady(nsIAsyncOutputStream *out)
767 NS_ASSERTION(out == mSocketOut, "unexpected stream");
768 NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
770 // if the transaction was dropped...
771 if (!mTransaction) {
772 LOG((" no transaction; ignoring event\n"));
773 return NS_OK;
776 nsresult rv = OnSocketWritable();
777 if (NS_FAILED(rv))
778 CloseTransaction(mTransaction, rv);
780 return NS_OK;
783 //-----------------------------------------------------------------------------
784 // nsHttpConnection::nsITransportEventSink
785 //-----------------------------------------------------------------------------
787 NS_IMETHODIMP
788 nsHttpConnection::OnTransportStatus(nsITransport *trans,
789 nsresult status,
790 PRUint64 progress,
791 PRUint64 progressMax)
793 if (mTransaction)
794 mTransaction->OnTransportStatus(status, progress);
795 return NS_OK;
798 //-----------------------------------------------------------------------------
799 // nsHttpConnection::nsIInterfaceRequestor
800 //-----------------------------------------------------------------------------
802 // not called on the socket transport thread
803 NS_IMETHODIMP
804 nsHttpConnection::GetInterface(const nsIID &iid, void **result)
806 // NOTE: This function is only called on the UI thread via sync proxy from
807 // the socket transport thread. If that weren't the case, then we'd
808 // have to worry about the possibility of mTransaction going away
809 // part-way through this function call. See CloseTransaction.
810 NS_ASSERTION(PR_GetCurrentThread() != gSocketThread, "wrong thread");
812 if (mTransaction) {
813 nsCOMPtr<nsIInterfaceRequestor> callbacks;
814 mTransaction->GetSecurityCallbacks(getter_AddRefs(callbacks));
815 if (callbacks)
816 return callbacks->GetInterface(iid, result);
819 return NS_ERROR_NO_INTERFACE;