1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // TODO(ukai): code is similar with http_network_transaction.cc. We should
6 // think about ways to share code, if possible.
8 #include "net/socket_stream/socket_stream.h"
14 #include "base/bind.h"
15 #include "base/bind_helpers.h"
16 #include "base/compiler_specific.h"
17 #include "base/logging.h"
18 #include "base/message_loop.h"
19 #include "base/string_util.h"
20 #include "base/stringprintf.h"
21 #include "base/utf_string_conversions.h"
22 #include "net/base/auth.h"
23 #include "net/base/io_buffer.h"
24 #include "net/base/net_errors.h"
25 #include "net/base/net_util.h"
26 #include "net/dns/host_resolver.h"
27 #include "net/http/http_auth_controller.h"
28 #include "net/http/http_network_session.h"
29 #include "net/http/http_request_headers.h"
30 #include "net/http/http_request_info.h"
31 #include "net/http/http_response_headers.h"
32 #include "net/http/http_stream_factory.h"
33 #include "net/http/http_transaction_factory.h"
34 #include "net/http/http_util.h"
35 #include "net/socket/client_socket_factory.h"
36 #include "net/socket/socks5_client_socket.h"
37 #include "net/socket/socks_client_socket.h"
38 #include "net/socket/ssl_client_socket.h"
39 #include "net/socket/tcp_client_socket.h"
40 #include "net/socket_stream/socket_stream_metrics.h"
41 #include "net/ssl/ssl_cert_request_info.h"
42 #include "net/ssl/ssl_info.h"
43 #include "net/url_request/url_request.h"
44 #include "net/url_request/url_request_context.h"
46 static const int kMaxPendingSendAllowed
= 32768; // 32 kilobytes.
47 static const int kReadBufferSize
= 4096;
51 int SocketStream::Delegate::OnStartOpenConnection(
52 SocketStream
* socket
, const CompletionCallback
& callback
) {
56 void SocketStream::Delegate::OnAuthRequired(SocketStream
* socket
,
57 AuthChallengeInfo
* auth_info
) {
58 // By default, no credential is available and close the connection.
62 void SocketStream::Delegate::OnSSLCertificateError(
64 const SSLInfo
& ssl_info
,
66 socket
->CancelWithSSLError(ssl_info
);
69 bool SocketStream::Delegate::CanGetCookies(SocketStream
* socket
,
74 bool SocketStream::Delegate::CanSetCookie(SocketStream
* request
,
76 const std::string
& cookie_line
,
77 CookieOptions
* options
) {
81 SocketStream::ResponseHeaders::ResponseHeaders() : IOBuffer() {}
83 void SocketStream::ResponseHeaders::Realloc(size_t new_size
) {
84 headers_
.reset(static_cast<char*>(realloc(headers_
.release(), new_size
)));
87 SocketStream::ResponseHeaders::~ResponseHeaders() { data_
= NULL
; }
89 SocketStream::SocketStream(const GURL
& url
, Delegate
* delegate
)
90 : delegate_(delegate
),
92 max_pending_send_allowed_(kMaxPendingSendAllowed
),
94 next_state_(STATE_NONE
),
97 server_bound_cert_service_(NULL
),
98 factory_(ClientSocketFactory::GetDefaultFactory()),
99 proxy_mode_(kDirectConnection
),
102 // Unretained() is required; without it, Bind() creates a circular
103 // dependency and the SocketStream object will not be freed.
104 ALLOW_THIS_IN_INITIALIZER_LIST(
105 io_callback_(base::Bind(&SocketStream::OnIOCompleted
,
106 base::Unretained(this)))),
108 current_write_buf_(NULL
),
109 waiting_for_write_completion_(false),
111 server_closed_(false),
112 metrics_(new SocketStreamMetrics(url
)) {
113 DCHECK(MessageLoop::current()) <<
114 "The current MessageLoop must exist";
115 DCHECK_EQ(MessageLoop::TYPE_IO
, MessageLoop::current()->type()) <<
116 "The current MessageLoop must be TYPE_IO";
120 SocketStream::UserData
* SocketStream::GetUserData(
121 const void* key
) const {
122 UserDataMap::const_iterator found
= user_data_
.find(key
);
123 if (found
!= user_data_
.end())
124 return found
->second
.get();
128 void SocketStream::SetUserData(const void* key
, UserData
* data
) {
129 user_data_
[key
] = linked_ptr
<UserData
>(data
);
132 bool SocketStream::is_secure() const {
133 return url_
.SchemeIs("wss");
136 void SocketStream::set_context(const URLRequestContext
* context
) {
137 const URLRequestContext
* prev_context
= context_
;
141 if (prev_context
!= context
) {
142 if (prev_context
&& pac_request_
) {
143 prev_context
->proxy_service()->CancelPacRequest(pac_request_
);
147 net_log_
.EndEvent(NetLog::TYPE_REQUEST_ALIVE
);
148 net_log_
= BoundNetLog();
151 net_log_
= BoundNetLog::Make(
153 NetLog::SOURCE_SOCKET_STREAM
);
155 net_log_
.BeginEvent(NetLog::TYPE_REQUEST_ALIVE
);
160 host_resolver_
= context_
->host_resolver();
161 cert_verifier_
= context_
->cert_verifier();
162 server_bound_cert_service_
= context_
->server_bound_cert_service();
166 void SocketStream::Connect() {
167 DCHECK(MessageLoop::current()) <<
168 "The current MessageLoop must exist";
169 DCHECK_EQ(MessageLoop::TYPE_IO
, MessageLoop::current()->type()) <<
170 "The current MessageLoop must be TYPE_IO";
172 ssl_config_service()->GetSSLConfig(&server_ssl_config_
);
173 proxy_ssl_config_
= server_ssl_config_
;
175 DCHECK_EQ(next_state_
, STATE_NONE
);
177 AddRef(); // Released in Finish()
178 // Open a connection asynchronously, so that delegate won't be called
179 // back before returning Connect().
180 next_state_
= STATE_BEFORE_CONNECT
;
182 NetLog::TYPE_SOCKET_STREAM_CONNECT
,
183 NetLog::StringCallback("url", &url_
.possibly_invalid_spec()));
184 MessageLoop::current()->PostTask(
186 base::Bind(&SocketStream::DoLoop
, this, OK
));
189 size_t SocketStream::GetTotalSizeOfPendingWriteBufs() const {
190 size_t total_size
= 0;
191 for (PendingDataQueue::const_iterator iter
= pending_write_bufs_
.begin();
192 iter
!= pending_write_bufs_
.end();
194 total_size
+= (*iter
)->size();
198 bool SocketStream::SendData(const char* data
, int len
) {
199 DCHECK(MessageLoop::current()) <<
200 "The current MessageLoop must exist";
201 DCHECK_EQ(MessageLoop::TYPE_IO
, MessageLoop::current()->type()) <<
202 "The current MessageLoop must be TYPE_IO";
205 if (!socket_
.get() || !socket_
->IsConnected() || next_state_
== STATE_NONE
)
208 int total_buffered_bytes
= len
;
209 if (current_write_buf_
) {
211 // - the purpose of this check is to limit the amount of buffer used by
213 // - the DrainableIOBuffer doesn't release consumed memory.
214 // we need to use not BytesRemaining() but size() here.
215 total_buffered_bytes
+= current_write_buf_
->size();
217 total_buffered_bytes
+= GetTotalSizeOfPendingWriteBufs();
218 if (total_buffered_bytes
> max_pending_send_allowed_
)
221 // TODO(tyoshino): Split data into smaller chunks e.g. 8KiB to free consumed
222 // buffer progressively
223 pending_write_bufs_
.push_back(make_scoped_refptr(
224 new IOBufferWithSize(len
)));
225 memcpy(pending_write_bufs_
.back()->data(), data
, len
);
227 // If current_write_buf_ is not NULL, it means that a) there's ongoing write
228 // operation or b) the connection is being closed. If a), the buffer we just
229 // pushed will be automatically handled when the completion callback runs
230 // the loop, and therefore we don't need to enqueue DoLoop(). If b), it's ok
231 // to do nothing. If current_write_buf_ is NULL, to make sure DoLoop() is
232 // ran soon, enequeue it.
233 if (!current_write_buf_
) {
234 // Send pending data asynchronously, so that delegate won't be called
235 // back before returning from SendData().
236 MessageLoop::current()->PostTask(
238 base::Bind(&SocketStream::DoLoop
, this, OK
));
244 void SocketStream::Close() {
245 DCHECK(MessageLoop::current()) <<
246 "The current MessageLoop must exist";
247 DCHECK_EQ(MessageLoop::TYPE_IO
, MessageLoop::current()->type()) <<
248 "The current MessageLoop must be TYPE_IO";
249 // If next_state_ is STATE_NONE, the socket was not opened, or already
250 // closed. So, return immediately.
251 // Otherwise, it might call Finish() more than once, so breaks balance
252 // of AddRef() and Release() in Connect() and Finish(), respectively.
253 if (next_state_
== STATE_NONE
)
255 MessageLoop::current()->PostTask(
257 base::Bind(&SocketStream::DoClose
, this));
260 void SocketStream::RestartWithAuth(const AuthCredentials
& credentials
) {
261 DCHECK(MessageLoop::current()) <<
262 "The current MessageLoop must exist";
263 DCHECK_EQ(MessageLoop::TYPE_IO
, MessageLoop::current()->type()) <<
264 "The current MessageLoop must be TYPE_IO";
265 DCHECK(proxy_auth_controller_
.get());
266 if (!socket_
.get()) {
267 LOG(ERROR
) << "Socket is closed before restarting with auth.";
271 proxy_auth_controller_
->ResetAuth(credentials
);
273 MessageLoop::current()->PostTask(
275 base::Bind(&SocketStream::DoRestartWithAuth
, this));
278 void SocketStream::DetachDelegate() {
282 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
283 // We don't need to send pending data when client detach the delegate.
284 pending_write_bufs_
.clear();
288 const ProxyServer
& SocketStream::proxy_server() const {
289 return proxy_info_
.proxy_server();
292 void SocketStream::SetClientSocketFactory(
293 ClientSocketFactory
* factory
) {
298 void SocketStream::CancelWithError(int error
) {
299 MessageLoop::current()->PostTask(
301 base::Bind(&SocketStream::DoLoop
, this, error
));
304 void SocketStream::CancelWithSSLError(const SSLInfo
& ssl_info
) {
305 CancelWithError(MapCertStatusToNetError(ssl_info
.cert_status
));
308 void SocketStream::ContinueDespiteError() {
309 MessageLoop::current()->PostTask(
311 base::Bind(&SocketStream::DoLoop
, this, OK
));
314 SocketStream::~SocketStream() {
317 DCHECK(!pac_request_
);
320 SocketStream::RequestHeaders::~RequestHeaders() { data_
= NULL
; }
322 void SocketStream::set_addresses(const AddressList
& addresses
) {
323 addresses_
= addresses
;
326 void SocketStream::DoClose() {
328 // If next_state_ is STATE_TCP_CONNECT, it's waiting other socket
329 // establishing connection. If next_state_ is STATE_AUTH_REQUIRED, it's
330 // waiting for restarting. In these states, we'll close the SocketStream
332 if (next_state_
== STATE_TCP_CONNECT
|| next_state_
== STATE_AUTH_REQUIRED
) {
336 // If next_state_ is STATE_READ_WRITE, we'll run DoLoop and close
338 // If it's writing now, we should defer the closing after the current
339 // writing is completed.
340 if (next_state_
== STATE_READ_WRITE
&& !current_write_buf_
)
343 // In other next_state_, we'll wait for callback of other APIs, such as
347 void SocketStream::Finish(int result
) {
348 DCHECK(MessageLoop::current()) <<
349 "The current MessageLoop must exist";
350 DCHECK_EQ(MessageLoop::TYPE_IO
, MessageLoop::current()->type()) <<
351 "The current MessageLoop must be TYPE_IO";
352 DCHECK_LE(result
, OK
);
354 result
= ERR_CONNECTION_CLOSED
;
355 DCHECK_EQ(next_state_
, STATE_NONE
);
356 DVLOG(1) << "Finish result=" << ErrorToString(result
);
359 Delegate
* delegate
= delegate_
;
362 delegate
->OnError(this, result
);
363 if (result
!= ERR_PROTOCOL_SWITCHED
)
364 delegate
->OnClose(this);
369 int SocketStream::DidEstablishConnection() {
370 if (!socket_
.get() || !socket_
->IsConnected()) {
371 next_state_
= STATE_CLOSE
;
372 return ERR_CONNECTION_FAILED
;
374 next_state_
= STATE_READ_WRITE
;
375 metrics_
->OnConnected();
377 net_log_
.EndEvent(NetLog::TYPE_SOCKET_STREAM_CONNECT
);
379 delegate_
->OnConnected(this, max_pending_send_allowed_
);
384 int SocketStream::DidReceiveData(int result
) {
386 DCHECK_GT(result
, 0);
387 net_log_
.AddEvent(NetLog::TYPE_SOCKET_STREAM_RECEIVED
);
389 metrics_
->OnRead(len
);
391 // Notify recevied data to delegate.
392 delegate_
->OnReceivedData(this, read_buf_
->data(), len
);
398 void SocketStream::DidSendData(int result
) {
399 DCHECK_GT(result
, 0);
400 DCHECK(current_write_buf_
);
401 net_log_
.AddEvent(NetLog::TYPE_SOCKET_STREAM_SENT
);
403 int bytes_sent
= result
;
405 metrics_
->OnWrite(bytes_sent
);
407 current_write_buf_
->DidConsume(result
);
409 if (current_write_buf_
->BytesRemaining())
412 size_t bytes_freed
= current_write_buf_
->size();
414 current_write_buf_
= NULL
;
416 // We freed current_write_buf_ and this instance is now able to accept more
417 // data via SendData() (note that DidConsume() doesn't free consumed memory).
418 // We can tell that to delegate_ by calling OnSentData().
420 delegate_
->OnSentData(this, bytes_freed
);
423 void SocketStream::OnIOCompleted(int result
) {
427 void SocketStream::OnReadCompleted(int result
) {
429 // 0 indicates end-of-file, so socket was closed.
430 // Don't close the socket if it's still writing.
431 server_closed_
= true;
432 } else if (result
> 0 && read_buf_
) {
433 result
= DidReceiveData(result
);
438 void SocketStream::OnWriteCompleted(int result
) {
439 waiting_for_write_completion_
= false;
447 void SocketStream::DoLoop(int result
) {
448 // If context was not set, close immediately.
450 next_state_
= STATE_CLOSE
;
452 if (next_state_
== STATE_NONE
)
456 State state
= next_state_
;
457 next_state_
= STATE_NONE
;
459 case STATE_BEFORE_CONNECT
:
460 DCHECK_EQ(OK
, result
);
461 result
= DoBeforeConnect();
463 case STATE_BEFORE_CONNECT_COMPLETE
:
464 result
= DoBeforeConnectComplete(result
);
466 case STATE_RESOLVE_PROXY
:
467 DCHECK_EQ(OK
, result
);
468 result
= DoResolveProxy();
470 case STATE_RESOLVE_PROXY_COMPLETE
:
471 result
= DoResolveProxyComplete(result
);
473 case STATE_RESOLVE_HOST
:
474 DCHECK_EQ(OK
, result
);
475 result
= DoResolveHost();
477 case STATE_RESOLVE_HOST_COMPLETE
:
478 result
= DoResolveHostComplete(result
);
480 case STATE_RESOLVE_PROTOCOL
:
481 result
= DoResolveProtocol(result
);
483 case STATE_RESOLVE_PROTOCOL_COMPLETE
:
484 result
= DoResolveProtocolComplete(result
);
486 case STATE_TCP_CONNECT
:
487 result
= DoTcpConnect(result
);
489 case STATE_TCP_CONNECT_COMPLETE
:
490 result
= DoTcpConnectComplete(result
);
492 case STATE_GENERATE_PROXY_AUTH_TOKEN
:
493 result
= DoGenerateProxyAuthToken();
495 case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
:
496 result
= DoGenerateProxyAuthTokenComplete(result
);
498 case STATE_WRITE_TUNNEL_HEADERS
:
499 DCHECK_EQ(OK
, result
);
500 result
= DoWriteTunnelHeaders();
502 case STATE_WRITE_TUNNEL_HEADERS_COMPLETE
:
503 result
= DoWriteTunnelHeadersComplete(result
);
505 case STATE_READ_TUNNEL_HEADERS
:
506 DCHECK_EQ(OK
, result
);
507 result
= DoReadTunnelHeaders();
509 case STATE_READ_TUNNEL_HEADERS_COMPLETE
:
510 result
= DoReadTunnelHeadersComplete(result
);
512 case STATE_SOCKS_CONNECT
:
513 DCHECK_EQ(OK
, result
);
514 result
= DoSOCKSConnect();
516 case STATE_SOCKS_CONNECT_COMPLETE
:
517 result
= DoSOCKSConnectComplete(result
);
519 case STATE_SECURE_PROXY_CONNECT
:
520 DCHECK_EQ(OK
, result
);
521 result
= DoSecureProxyConnect();
523 case STATE_SECURE_PROXY_CONNECT_COMPLETE
:
524 result
= DoSecureProxyConnectComplete(result
);
526 case STATE_SECURE_PROXY_HANDLE_CERT_ERROR
:
527 result
= DoSecureProxyHandleCertError(result
);
529 case STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE
:
530 result
= DoSecureProxyHandleCertErrorComplete(result
);
532 case STATE_SSL_CONNECT
:
533 DCHECK_EQ(OK
, result
);
534 result
= DoSSLConnect();
536 case STATE_SSL_CONNECT_COMPLETE
:
537 result
= DoSSLConnectComplete(result
);
539 case STATE_SSL_HANDLE_CERT_ERROR
:
540 result
= DoSSLHandleCertError(result
);
542 case STATE_SSL_HANDLE_CERT_ERROR_COMPLETE
:
543 result
= DoSSLHandleCertErrorComplete(result
);
545 case STATE_READ_WRITE
:
546 result
= DoReadWrite(result
);
548 case STATE_AUTH_REQUIRED
:
549 // It might be called when DoClose is called while waiting in
550 // STATE_AUTH_REQUIRED.
554 DCHECK_LE(result
, OK
);
558 NOTREACHED() << "bad state " << state
;
562 if (state
== STATE_RESOLVE_PROTOCOL
&& result
== ERR_PROTOCOL_SWITCHED
)
564 // If the connection is not established yet and had actual errors,
565 // record the error. In next iteration, it will close the connection.
566 if (state
!= STATE_READ_WRITE
&& result
< ERR_IO_PENDING
) {
567 net_log_
.EndEventWithNetErrorCode(
568 NetLog::TYPE_SOCKET_STREAM_CONNECT
, result
);
570 } while (result
!= ERR_IO_PENDING
);
573 int SocketStream::DoBeforeConnect() {
574 next_state_
= STATE_BEFORE_CONNECT_COMPLETE
;
575 if (!context_
|| !context_
->network_delegate())
578 int result
= context_
->network_delegate()->NotifyBeforeSocketStreamConnect(
580 if (result
!= OK
&& result
!= ERR_IO_PENDING
)
581 next_state_
= STATE_CLOSE
;
586 int SocketStream::DoBeforeConnectComplete(int result
) {
587 DCHECK_NE(ERR_IO_PENDING
, result
);
590 next_state_
= STATE_RESOLVE_PROXY
;
592 next_state_
= STATE_CLOSE
;
597 int SocketStream::DoResolveProxy() {
598 DCHECK(!pac_request_
);
599 next_state_
= STATE_RESOLVE_PROXY_COMPLETE
;
601 if (!proxy_url_
.is_valid()) {
602 next_state_
= STATE_CLOSE
;
603 return ERR_INVALID_ARGUMENT
;
606 // TODO(toyoshim): Check server advertisement of SPDY through the HTTP
607 // Alternate-Protocol header, then switch to SPDY if SPDY is available.
608 // Usually we already have a session to the SPDY server because JavaScript
609 // running WebSocket itself would be served by SPDY. But, in some situation
610 // (E.g. Used by Chrome Extensions or used for cross origin connection), this
611 // connection might be the first one. At that time, we should check
612 // Alternate-Protocol header here for ws:// or TLS NPN extension for wss:// .
614 return proxy_service()->ResolveProxy(
615 proxy_url_
, &proxy_info_
, io_callback_
, &pac_request_
, net_log_
);
618 int SocketStream::DoResolveProxyComplete(int result
) {
621 LOG(ERROR
) << "Failed to resolve proxy: " << result
;
623 delegate_
->OnError(this, result
);
624 proxy_info_
.UseDirect();
626 if (proxy_info_
.is_direct()) {
627 // If proxy was not found for original URL (i.e. websocket URL),
628 // try again with https URL, like Safari implementation.
629 // Note that we don't want to use http proxy, because we'll use tunnel
630 // proxy using CONNECT method, which is used by https proxy.
631 if (!proxy_url_
.SchemeIs("https")) {
632 const std::string scheme
= "https";
633 GURL::Replacements repl
;
634 repl
.SetSchemeStr(scheme
);
635 proxy_url_
= url_
.ReplaceComponents(repl
);
636 DVLOG(1) << "Try https proxy: " << proxy_url_
;
637 next_state_
= STATE_RESOLVE_PROXY
;
642 if (proxy_info_
.is_empty()) {
643 // No proxies/direct to choose from. This happens when we don't support any
644 // of the proxies in the returned list.
645 return ERR_NO_SUPPORTED_PROXIES
;
648 next_state_
= STATE_RESOLVE_HOST
;
652 int SocketStream::DoResolveHost() {
653 next_state_
= STATE_RESOLVE_HOST_COMPLETE
;
655 DCHECK(!proxy_info_
.is_empty());
656 if (proxy_info_
.is_direct())
657 proxy_mode_
= kDirectConnection
;
658 else if (proxy_info_
.proxy_server().is_socks())
659 proxy_mode_
= kSOCKSProxy
;
661 proxy_mode_
= kTunnelProxy
;
663 // Determine the host and port to connect to.
664 HostPortPair host_port_pair
;
665 if (proxy_mode_
!= kDirectConnection
) {
666 host_port_pair
= proxy_info_
.proxy_server().host_port_pair();
668 host_port_pair
= HostPortPair::FromURL(url_
);
671 HostResolver::RequestInfo
resolve_info(host_port_pair
);
673 DCHECK(host_resolver_
);
674 resolver_
.reset(new SingleRequestHostResolver(host_resolver_
));
675 return resolver_
->Resolve(
676 resolve_info
, &addresses_
, base::Bind(&SocketStream::OnIOCompleted
, this),
680 int SocketStream::DoResolveHostComplete(int result
) {
681 if (result
== OK
&& delegate_
)
682 next_state_
= STATE_RESOLVE_PROTOCOL
;
684 next_state_
= STATE_CLOSE
;
685 // TODO(ukai): if error occured, reconsider proxy after error.
689 int SocketStream::DoResolveProtocol(int result
) {
690 DCHECK_EQ(OK
, result
);
691 next_state_
= STATE_RESOLVE_PROTOCOL_COMPLETE
;
692 result
= delegate_
->OnStartOpenConnection(this, io_callback_
);
693 if (result
== ERR_IO_PENDING
)
694 metrics_
->OnWaitConnection();
695 else if (result
!= OK
&& result
!= ERR_PROTOCOL_SWITCHED
)
696 next_state_
= STATE_CLOSE
;
700 int SocketStream::DoResolveProtocolComplete(int result
) {
701 DCHECK_NE(ERR_IO_PENDING
, result
);
703 if (result
== ERR_PROTOCOL_SWITCHED
) {
704 next_state_
= STATE_CLOSE
;
705 metrics_
->OnCountWireProtocolType(
706 SocketStreamMetrics::WIRE_PROTOCOL_SPDY
);
707 } else if (result
== OK
) {
708 next_state_
= STATE_TCP_CONNECT
;
709 metrics_
->OnCountWireProtocolType(
710 SocketStreamMetrics::WIRE_PROTOCOL_WEBSOCKET
);
712 next_state_
= STATE_CLOSE
;
717 int SocketStream::DoTcpConnect(int result
) {
719 next_state_
= STATE_CLOSE
;
722 next_state_
= STATE_TCP_CONNECT_COMPLETE
;
724 socket_
.reset(factory_
->CreateTransportClientSocket(addresses_
,
727 metrics_
->OnStartConnection();
728 return socket_
->Connect(io_callback_
);
731 int SocketStream::DoTcpConnectComplete(int result
) {
732 // TODO(ukai): if error occured, reconsider proxy after error.
734 next_state_
= STATE_CLOSE
;
738 if (proxy_mode_
== kTunnelProxy
) {
739 if (proxy_info_
.is_https())
740 next_state_
= STATE_SECURE_PROXY_CONNECT
;
742 next_state_
= STATE_GENERATE_PROXY_AUTH_TOKEN
;
743 } else if (proxy_mode_
== kSOCKSProxy
) {
744 next_state_
= STATE_SOCKS_CONNECT
;
745 } else if (is_secure()) {
746 next_state_
= STATE_SSL_CONNECT
;
748 result
= DidEstablishConnection();
753 int SocketStream::DoGenerateProxyAuthToken() {
754 next_state_
= STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
;
755 if (!proxy_auth_controller_
.get()) {
757 DCHECK(context_
->http_transaction_factory());
758 DCHECK(context_
->http_transaction_factory()->GetSession());
759 HttpNetworkSession
* session
=
760 context_
->http_transaction_factory()->GetSession();
761 const char* scheme
= proxy_info_
.is_https() ? "https://" : "http://";
762 GURL
auth_url(scheme
+
763 proxy_info_
.proxy_server().host_port_pair().ToString());
764 proxy_auth_controller_
=
765 new HttpAuthController(HttpAuth::AUTH_PROXY
,
767 session
->http_auth_cache(),
768 session
->http_auth_handler_factory());
770 HttpRequestInfo request_info
;
771 request_info
.url
= url_
;
772 request_info
.method
= "CONNECT";
773 return proxy_auth_controller_
->MaybeGenerateAuthToken(
774 &request_info
, io_callback_
, net_log_
);
777 int SocketStream::DoGenerateProxyAuthTokenComplete(int result
) {
779 next_state_
= STATE_CLOSE
;
783 next_state_
= STATE_WRITE_TUNNEL_HEADERS
;
787 int SocketStream::DoWriteTunnelHeaders() {
788 DCHECK_EQ(kTunnelProxy
, proxy_mode_
);
790 next_state_
= STATE_WRITE_TUNNEL_HEADERS_COMPLETE
;
792 if (!tunnel_request_headers_
.get()) {
793 metrics_
->OnCountConnectionType(SocketStreamMetrics::TUNNEL_CONNECTION
);
794 tunnel_request_headers_
= new RequestHeaders();
795 tunnel_request_headers_bytes_sent_
= 0;
797 if (tunnel_request_headers_
->headers_
.empty()) {
798 HttpRequestHeaders request_headers
;
799 request_headers
.SetHeader("Host", GetHostAndOptionalPort(url_
));
800 request_headers
.SetHeader("Proxy-Connection", "keep-alive");
801 if (proxy_auth_controller_
.get() && proxy_auth_controller_
->HaveAuth())
802 proxy_auth_controller_
->AddAuthorizationHeader(&request_headers
);
803 tunnel_request_headers_
->headers_
= base::StringPrintf(
804 "CONNECT %s HTTP/1.1\r\n"
806 GetHostAndPort(url_
).c_str(),
807 request_headers
.ToString().c_str());
809 tunnel_request_headers_
->SetDataOffset(tunnel_request_headers_bytes_sent_
);
810 int buf_len
= static_cast<int>(tunnel_request_headers_
->headers_
.size() -
811 tunnel_request_headers_bytes_sent_
);
812 DCHECK_GT(buf_len
, 0);
813 return socket_
->Write(tunnel_request_headers_
, buf_len
, io_callback_
);
816 int SocketStream::DoWriteTunnelHeadersComplete(int result
) {
817 DCHECK_EQ(kTunnelProxy
, proxy_mode_
);
820 next_state_
= STATE_CLOSE
;
824 tunnel_request_headers_bytes_sent_
+= result
;
825 if (tunnel_request_headers_bytes_sent_
<
826 tunnel_request_headers_
->headers_
.size()) {
827 next_state_
= STATE_GENERATE_PROXY_AUTH_TOKEN
;
829 // Handling a cert error or a client cert request requires reconnection.
830 // DoWriteTunnelHeaders() will be called again.
831 // Thus |tunnel_request_headers_bytes_sent_| should be reset to 0 for
832 // sending |tunnel_request_headers_| correctly.
833 tunnel_request_headers_bytes_sent_
= 0;
834 next_state_
= STATE_READ_TUNNEL_HEADERS
;
839 int SocketStream::DoReadTunnelHeaders() {
840 DCHECK_EQ(kTunnelProxy
, proxy_mode_
);
842 next_state_
= STATE_READ_TUNNEL_HEADERS_COMPLETE
;
844 if (!tunnel_response_headers_
.get()) {
845 tunnel_response_headers_
= new ResponseHeaders();
846 tunnel_response_headers_capacity_
= kMaxTunnelResponseHeadersSize
;
847 tunnel_response_headers_
->Realloc(tunnel_response_headers_capacity_
);
848 tunnel_response_headers_len_
= 0;
851 int buf_len
= tunnel_response_headers_capacity_
-
852 tunnel_response_headers_len_
;
853 tunnel_response_headers_
->SetDataOffset(tunnel_response_headers_len_
);
854 CHECK(tunnel_response_headers_
->data());
856 return socket_
->Read(tunnel_response_headers_
, buf_len
, io_callback_
);
859 int SocketStream::DoReadTunnelHeadersComplete(int result
) {
860 DCHECK_EQ(kTunnelProxy
, proxy_mode_
);
863 next_state_
= STATE_CLOSE
;
868 // 0 indicates end-of-file, so socket was closed.
869 next_state_
= STATE_CLOSE
;
870 return ERR_CONNECTION_CLOSED
;
873 tunnel_response_headers_len_
+= result
;
874 DCHECK(tunnel_response_headers_len_
<= tunnel_response_headers_capacity_
);
876 int eoh
= HttpUtil::LocateEndOfHeaders(
877 tunnel_response_headers_
->headers(), tunnel_response_headers_len_
, 0);
879 if (tunnel_response_headers_len_
>= kMaxTunnelResponseHeadersSize
) {
880 next_state_
= STATE_CLOSE
;
881 return ERR_RESPONSE_HEADERS_TOO_BIG
;
884 next_state_
= STATE_READ_TUNNEL_HEADERS
;
887 // DidReadResponseHeaders
888 scoped_refptr
<HttpResponseHeaders
> headers
;
889 headers
= new HttpResponseHeaders(
890 HttpUtil::AssembleRawHeaders(tunnel_response_headers_
->headers(), eoh
));
891 if (headers
->GetParsedHttpVersion() < HttpVersion(1, 0)) {
892 // Require the "HTTP/1.x" status line.
893 next_state_
= STATE_CLOSE
;
894 return ERR_TUNNEL_CONNECTION_FAILED
;
896 switch (headers
->response_code()) {
899 DCHECK_EQ(eoh
, tunnel_response_headers_len_
);
900 next_state_
= STATE_SSL_CONNECT
;
902 result
= DidEstablishConnection();
904 next_state_
= STATE_CLOSE
;
907 if ((eoh
< tunnel_response_headers_len_
) && delegate_
)
908 delegate_
->OnReceivedData(
909 this, tunnel_response_headers_
->headers() + eoh
,
910 tunnel_response_headers_len_
- eoh
);
913 case 407: // Proxy Authentication Required.
914 if (proxy_mode_
!= kTunnelProxy
)
915 return ERR_UNEXPECTED_PROXY_AUTH
;
917 result
= proxy_auth_controller_
->HandleAuthChallenge(
918 headers
, false, true, net_log_
);
921 DCHECK(!proxy_info_
.is_empty());
922 next_state_
= STATE_AUTH_REQUIRED
;
923 if (proxy_auth_controller_
->HaveAuth()) {
924 MessageLoop::current()->PostTask(
926 base::Bind(&SocketStream::DoRestartWithAuth
, this));
927 return ERR_IO_PENDING
;
930 // Wait until RestartWithAuth or Close is called.
931 MessageLoop::current()->PostTask(
933 base::Bind(&SocketStream::DoAuthRequired
, this));
934 return ERR_IO_PENDING
;
940 next_state_
= STATE_CLOSE
;
941 return ERR_TUNNEL_CONNECTION_FAILED
;
944 int SocketStream::DoSOCKSConnect() {
945 DCHECK_EQ(kSOCKSProxy
, proxy_mode_
);
947 next_state_
= STATE_SOCKS_CONNECT_COMPLETE
;
949 StreamSocket
* s
= socket_
.release();
950 HostResolver::RequestInfo
req_info(HostPortPair::FromURL(url_
));
952 DCHECK(!proxy_info_
.is_empty());
953 if (proxy_info_
.proxy_server().scheme() == ProxyServer::SCHEME_SOCKS5
)
954 s
= new SOCKS5ClientSocket(s
, req_info
);
956 s
= new SOCKSClientSocket(s
, req_info
, host_resolver_
);
958 metrics_
->OnCountConnectionType(SocketStreamMetrics::SOCKS_CONNECTION
);
959 return socket_
->Connect(io_callback_
);
962 int SocketStream::DoSOCKSConnectComplete(int result
) {
963 DCHECK_EQ(kSOCKSProxy
, proxy_mode_
);
967 next_state_
= STATE_SSL_CONNECT
;
969 result
= DidEstablishConnection();
971 next_state_
= STATE_CLOSE
;
976 int SocketStream::DoSecureProxyConnect() {
978 SSLClientSocketContext ssl_context
;
979 ssl_context
.cert_verifier
= cert_verifier_
;
980 ssl_context
.server_bound_cert_service
= server_bound_cert_service_
;
981 socket_
.reset(factory_
->CreateSSLClientSocket(
983 proxy_info_
.proxy_server().host_port_pair(),
986 next_state_
= STATE_SECURE_PROXY_CONNECT_COMPLETE
;
987 metrics_
->OnCountConnectionType(SocketStreamMetrics::SECURE_PROXY_CONNECTION
);
988 return socket_
->Connect(io_callback_
);
991 int SocketStream::DoSecureProxyConnectComplete(int result
) {
992 DCHECK_EQ(STATE_NONE
, next_state_
);
993 // Reconnect with client authentication.
994 if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
)
995 return HandleCertificateRequest(result
, &proxy_ssl_config_
);
997 if (IsCertificateError(result
))
998 next_state_
= STATE_SECURE_PROXY_HANDLE_CERT_ERROR
;
999 else if (result
== OK
)
1000 next_state_
= STATE_GENERATE_PROXY_AUTH_TOKEN
;
1002 next_state_
= STATE_CLOSE
;
1006 int SocketStream::DoSecureProxyHandleCertError(int result
) {
1007 DCHECK_EQ(STATE_NONE
, next_state_
);
1008 DCHECK(IsCertificateError(result
));
1009 result
= HandleCertificateError(result
);
1010 if (result
== ERR_IO_PENDING
)
1011 next_state_
= STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE
;
1013 next_state_
= STATE_CLOSE
;
1017 int SocketStream::DoSecureProxyHandleCertErrorComplete(int result
) {
1018 DCHECK_EQ(STATE_NONE
, next_state_
);
1020 if (!socket_
->IsConnectedAndIdle())
1021 return AllowCertErrorForReconnection(&proxy_ssl_config_
);
1022 next_state_
= STATE_GENERATE_PROXY_AUTH_TOKEN
;
1024 next_state_
= STATE_CLOSE
;
1029 int SocketStream::DoSSLConnect() {
1031 SSLClientSocketContext ssl_context
;
1032 ssl_context
.cert_verifier
= cert_verifier_
;
1033 ssl_context
.server_bound_cert_service
= server_bound_cert_service_
;
1034 socket_
.reset(factory_
->CreateSSLClientSocket(socket_
.release(),
1035 HostPortPair::FromURL(url_
),
1038 next_state_
= STATE_SSL_CONNECT_COMPLETE
;
1039 metrics_
->OnCountConnectionType(SocketStreamMetrics::SSL_CONNECTION
);
1040 return socket_
->Connect(io_callback_
);
1043 int SocketStream::DoSSLConnectComplete(int result
) {
1044 DCHECK_EQ(STATE_NONE
, next_state_
);
1045 // Reconnect with client authentication.
1046 if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
)
1047 return HandleCertificateRequest(result
, &server_ssl_config_
);
1049 if (IsCertificateError(result
))
1050 next_state_
= STATE_SSL_HANDLE_CERT_ERROR
;
1051 else if (result
== OK
)
1052 result
= DidEstablishConnection();
1054 next_state_
= STATE_CLOSE
;
1058 int SocketStream::DoSSLHandleCertError(int result
) {
1059 DCHECK_EQ(STATE_NONE
, next_state_
);
1060 DCHECK(IsCertificateError(result
));
1061 result
= HandleCertificateError(result
);
1062 if (result
== OK
|| result
== ERR_IO_PENDING
)
1063 next_state_
= STATE_SSL_HANDLE_CERT_ERROR_COMPLETE
;
1065 next_state_
= STATE_CLOSE
;
1069 int SocketStream::DoSSLHandleCertErrorComplete(int result
) {
1070 DCHECK_EQ(STATE_NONE
, next_state_
);
1071 // TODO(toyoshim): Upgrade to SPDY through TLS NPN extension if possible.
1072 // If we use HTTPS and this is the first connection to the SPDY server,
1073 // we should take care of TLS NPN extension here.
1076 if (!socket_
->IsConnectedAndIdle())
1077 return AllowCertErrorForReconnection(&server_ssl_config_
);
1078 result
= DidEstablishConnection();
1080 next_state_
= STATE_CLOSE
;
1085 int SocketStream::DoReadWrite(int result
) {
1087 next_state_
= STATE_CLOSE
;
1090 if (!socket_
.get() || !socket_
->IsConnected()) {
1091 next_state_
= STATE_CLOSE
;
1092 return ERR_CONNECTION_CLOSED
;
1095 // If client has requested close(), and there's nothing to write, then
1096 // let's close the socket.
1097 // We don't care about receiving data after the socket is closed.
1098 if (closing_
&& !current_write_buf_
&& pending_write_bufs_
.empty()) {
1099 socket_
->Disconnect();
1100 next_state_
= STATE_CLOSE
;
1104 next_state_
= STATE_READ_WRITE
;
1106 // If server already closed the socket, we don't try to read.
1107 if (!server_closed_
) {
1109 // No read pending and server didn't close the socket.
1110 read_buf_
= new IOBuffer(kReadBufferSize
);
1111 result
= socket_
->Read(read_buf_
, kReadBufferSize
,
1112 base::Bind(&SocketStream::OnReadCompleted
,
1113 base::Unretained(this)));
1115 return DidReceiveData(result
);
1116 } else if (result
== 0) {
1117 // 0 indicates end-of-file, so socket was closed.
1118 next_state_
= STATE_CLOSE
;
1119 server_closed_
= true;
1120 return ERR_CONNECTION_CLOSED
;
1122 // If read is pending, try write as well.
1123 // Otherwise, return the result and do next loop (to close the
1125 if (result
!= ERR_IO_PENDING
) {
1126 next_state_
= STATE_CLOSE
;
1127 server_closed_
= true;
1135 if (waiting_for_write_completion_
)
1136 return ERR_IO_PENDING
;
1138 if (!current_write_buf_
) {
1139 if (pending_write_bufs_
.empty()) {
1140 // Nothing buffered for send.
1141 return ERR_IO_PENDING
;
1144 current_write_buf_
=
1145 new DrainableIOBuffer(pending_write_bufs_
.front(),
1146 pending_write_bufs_
.front()->size());
1147 pending_write_bufs_
.pop_front();
1150 result
= socket_
->Write(current_write_buf_
,
1151 current_write_buf_
->BytesRemaining(),
1152 base::Bind(&SocketStream::OnWriteCompleted
,
1153 base::Unretained(this)));
1155 if (result
== ERR_IO_PENDING
) {
1156 waiting_for_write_completion_
= true;
1157 } else if (result
< 0) {
1158 // Shortcut. Enter STATE_CLOSE now by changing next_state_ here than by
1159 // calling DoReadWrite() again with the error code.
1160 next_state_
= STATE_CLOSE
;
1161 } else if (result
> 0) {
1162 // Write is not pending. Return OK and do next loop.
1163 DidSendData(result
);
1170 GURL
SocketStream::ProxyAuthOrigin() const {
1171 DCHECK(!proxy_info_
.is_empty());
1172 return GURL("http://" +
1173 proxy_info_
.proxy_server().host_port_pair().ToString());
1176 int SocketStream::HandleCertificateRequest(int result
, SSLConfig
* ssl_config
) {
1177 if (ssl_config
->send_client_cert
) {
1178 // We already have performed SSL client authentication once and failed.
1182 DCHECK(socket_
.get());
1183 scoped_refptr
<SSLCertRequestInfo
> cert_request_info
= new SSLCertRequestInfo
;
1184 SSLClientSocket
* ssl_socket
=
1185 static_cast<SSLClientSocket
*>(socket_
.get());
1186 ssl_socket
->GetSSLCertRequestInfo(cert_request_info
);
1188 HttpTransactionFactory
* factory
= context_
->http_transaction_factory();
1191 scoped_refptr
<HttpNetworkSession
> session
= factory
->GetSession();
1195 // If the user selected one of the certificates in client_certs or declined
1196 // to provide one for this server before, use the past decision
1198 scoped_refptr
<X509Certificate
> client_cert
;
1199 if (!session
->ssl_client_auth_cache()->Lookup(
1200 cert_request_info
->host_and_port
, &client_cert
)) {
1204 // Note: |client_cert| may be NULL, indicating that the caller
1205 // wishes to proceed anonymously (eg: continue the handshake
1206 // without sending a client cert)
1208 // Check that the certificate selected is still a certificate the server
1209 // is likely to accept, based on the criteria supplied in the
1210 // CertificateRequest message.
1211 const std::vector
<std::string
>& cert_authorities
=
1212 cert_request_info
->cert_authorities
;
1213 if (client_cert
&& !cert_authorities
.empty() &&
1214 !client_cert
->IsIssuedByEncoded(cert_authorities
)) {
1218 ssl_config
->send_client_cert
= true;
1219 ssl_config
->client_cert
= client_cert
;
1220 next_state_
= STATE_TCP_CONNECT
;
1224 int SocketStream::AllowCertErrorForReconnection(SSLConfig
* ssl_config
) {
1226 // The SSL handshake didn't finish, or the server closed the SSL connection.
1227 // So, we should restart establishing connection with the certificate in
1228 // allowed bad certificates in |ssl_config|.
1229 // See also net/http/http_network_transaction.cc HandleCertificateError() and
1230 // RestartIgnoringLastError().
1231 SSLClientSocket
* ssl_socket
= static_cast<SSLClientSocket
*>(socket_
.get());
1233 ssl_socket
->GetSSLInfo(&ssl_info
);
1234 if (ssl_info
.cert
== NULL
||
1235 ssl_config
->IsAllowedBadCert(ssl_info
.cert
, NULL
)) {
1236 // If we already have the certificate in the set of allowed bad
1237 // certificates, we did try it and failed again, so we should not
1238 // retry again: the connection should fail at last.
1239 next_state_
= STATE_CLOSE
;
1240 return ERR_UNEXPECTED
;
1242 // Add the bad certificate to the set of allowed certificates in the
1243 // SSL config object.
1244 SSLConfig::CertAndStatus bad_cert
;
1245 if (!X509Certificate::GetDEREncoded(ssl_info
.cert
->os_cert_handle(),
1246 &bad_cert
.der_cert
)) {
1247 next_state_
= STATE_CLOSE
;
1248 return ERR_UNEXPECTED
;
1250 bad_cert
.cert_status
= ssl_info
.cert_status
;
1251 ssl_config
->allowed_bad_certs
.push_back(bad_cert
);
1252 // Restart connection ignoring the bad certificate.
1253 socket_
->Disconnect();
1255 next_state_
= STATE_TCP_CONNECT
;
1259 void SocketStream::DoAuthRequired() {
1260 if (delegate_
&& proxy_auth_controller_
.get())
1261 delegate_
->OnAuthRequired(this, proxy_auth_controller_
->auth_info().get());
1263 DoLoop(ERR_UNEXPECTED
);
1266 void SocketStream::DoRestartWithAuth() {
1267 DCHECK_EQ(next_state_
, STATE_AUTH_REQUIRED
);
1268 tunnel_request_headers_
= NULL
;
1269 tunnel_request_headers_bytes_sent_
= 0;
1270 tunnel_response_headers_
= NULL
;
1271 tunnel_response_headers_capacity_
= 0;
1272 tunnel_response_headers_len_
= 0;
1274 next_state_
= STATE_TCP_CONNECT
;
1278 int SocketStream::HandleCertificateError(int result
) {
1279 DCHECK(IsCertificateError(result
));
1280 SSLClientSocket
* ssl_socket
= static_cast<SSLClientSocket
*>(socket_
.get());
1283 if (SSLClientSocket::IgnoreCertError(result
, LOAD_IGNORE_ALL_CERT_ERRORS
)) {
1284 const HttpNetworkSession::Params
* session_params
=
1285 context_
->GetNetworkSessionParams();
1286 if (session_params
&& session_params
->ignore_certificate_errors
)
1294 ssl_socket
->GetSSLInfo(&ssl_info
);
1296 TransportSecurityState::DomainState domain_state
;
1298 const bool fatal
= context_
->transport_security_state() &&
1299 context_
->transport_security_state()->GetDomainState(url_
.host(),
1300 SSLConfigService::IsSNIAvailable(context_
->ssl_config_service()),
1302 domain_state
.ShouldSSLErrorsBeFatal();
1304 delegate_
->OnSSLCertificateError(this, ssl_info
, fatal
);
1305 return ERR_IO_PENDING
;
1308 SSLConfigService
* SocketStream::ssl_config_service() const {
1309 return context_
->ssl_config_service();
1312 ProxyService
* SocketStream::proxy_service() const {
1313 return context_
->proxy_service();