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/message_loop.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/strings/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/client_socket_handle.h"
37 #include "net/socket/socks5_client_socket.h"
38 #include "net/socket/socks_client_socket.h"
39 #include "net/socket/ssl_client_socket.h"
40 #include "net/socket/tcp_client_socket.h"
41 #include "net/socket_stream/socket_stream_metrics.h"
42 #include "net/ssl/ssl_cert_request_info.h"
43 #include "net/ssl/ssl_info.h"
44 #include "net/url_request/url_request.h"
45 #include "net/url_request/url_request_context.h"
47 static const int kMaxPendingSendAllowed = 32768; // 32 kilobytes.
48 static const int kReadBufferSize = 4096;
52 int SocketStream::Delegate::OnStartOpenConnection(
53 SocketStream* socket, const CompletionCallback& callback) {
57 void SocketStream::Delegate::OnAuthRequired(SocketStream* socket,
58 AuthChallengeInfo* auth_info) {
59 // By default, no credential is available and close the connection.
63 void SocketStream::Delegate::OnSSLCertificateError(
65 const SSLInfo& ssl_info,
67 socket->CancelWithSSLError(ssl_info);
70 bool SocketStream::Delegate::CanGetCookies(SocketStream* socket,
75 bool SocketStream::Delegate::CanSetCookie(SocketStream* request,
77 const std::string& cookie_line,
78 CookieOptions* options) {
82 SocketStream::ResponseHeaders::ResponseHeaders() : IOBuffer() {}
84 void SocketStream::ResponseHeaders::Realloc(size_t new_size) {
85 headers_.reset(static_cast<char*>(realloc(headers_.release(), new_size)));
88 SocketStream::ResponseHeaders::~ResponseHeaders() { data_ = NULL; }
90 SocketStream::SocketStream(const GURL& url, Delegate* delegate)
91 : delegate_(delegate),
93 max_pending_send_allowed_(kMaxPendingSendAllowed),
95 next_state_(STATE_NONE),
96 factory_(ClientSocketFactory::GetDefaultFactory()),
97 proxy_mode_(kDirectConnection),
100 connection_(new ClientSocketHandle),
101 privacy_mode_(kPrivacyModeDisabled),
102 // Unretained() is required; without it, Bind() creates a circular
103 // dependency and the SocketStream object will not be freed.
104 io_callback_(base::Bind(&SocketStream::OnIOCompleted,
105 base::Unretained(this))),
107 current_write_buf_(NULL),
108 waiting_for_write_completion_(false),
110 server_closed_(false),
111 metrics_(new SocketStreamMetrics(url)) {
112 DCHECK(base::MessageLoop::current())
113 << "The current base::MessageLoop must exist";
114 DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
115 << "The current base::MessageLoop must be TYPE_IO";
119 SocketStream::UserData* SocketStream::GetUserData(
120 const void* key) const {
121 UserDataMap::const_iterator found = user_data_.find(key);
122 if (found != user_data_.end())
123 return found->second.get();
127 void SocketStream::SetUserData(const void* key, UserData* data) {
128 user_data_[key] = linked_ptr<UserData>(data);
131 bool SocketStream::is_secure() const {
132 return url_.SchemeIs("wss");
135 void SocketStream::set_context(URLRequestContext* context) {
136 const URLRequestContext* prev_context = context_;
140 if (prev_context != context) {
141 if (prev_context && pac_request_) {
142 prev_context->proxy_service()->CancelPacRequest(pac_request_);
146 net_log_.EndEvent(NetLog::TYPE_REQUEST_ALIVE);
147 net_log_ = BoundNetLog();
150 net_log_ = BoundNetLog::Make(
152 NetLog::SOURCE_SOCKET_STREAM);
154 net_log_.BeginEvent(NetLog::TYPE_REQUEST_ALIVE);
159 void SocketStream::CheckPrivacyMode() {
160 if (context_ && context_->network_delegate()) {
161 bool enable = context_->network_delegate()->CanEnablePrivacyMode(url_,
163 privacy_mode_ = enable ? kPrivacyModeEnabled : kPrivacyModeDisabled;
164 // Disable Channel ID if privacy mode is enabled.
166 server_ssl_config_.channel_id_enabled = false;
170 void SocketStream::Connect() {
171 DCHECK(base::MessageLoop::current())
172 << "The current base::MessageLoop must exist";
173 DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
174 << "The current base::MessageLoop must be TYPE_IO";
176 context_->ssl_config_service()->GetSSLConfig(&server_ssl_config_);
177 proxy_ssl_config_ = server_ssl_config_;
181 DCHECK_EQ(next_state_, STATE_NONE);
183 AddRef(); // Released in Finish()
184 // Open a connection asynchronously, so that delegate won't be called
185 // back before returning Connect().
186 next_state_ = STATE_BEFORE_CONNECT;
188 NetLog::TYPE_SOCKET_STREAM_CONNECT,
189 NetLog::StringCallback("url", &url_.possibly_invalid_spec()));
190 base::MessageLoop::current()->PostTask(
191 FROM_HERE, base::Bind(&SocketStream::DoLoop, this, OK));
194 size_t SocketStream::GetTotalSizeOfPendingWriteBufs() const {
195 size_t total_size = 0;
196 for (PendingDataQueue::const_iterator iter = pending_write_bufs_.begin();
197 iter != pending_write_bufs_.end();
199 total_size += (*iter)->size();
203 bool SocketStream::SendData(const char* data, int len) {
204 DCHECK(base::MessageLoop::current())
205 << "The current base::MessageLoop must exist";
206 DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
207 << "The current base::MessageLoop must be TYPE_IO";
210 if (!connection_->socket() ||
211 !connection_->socket()->IsConnected() || next_state_ == STATE_NONE) {
215 int total_buffered_bytes = len;
216 if (current_write_buf_.get()) {
218 // - the purpose of this check is to limit the amount of buffer used by
220 // - the DrainableIOBuffer doesn't release consumed memory.
221 // we need to use not BytesRemaining() but size() here.
222 total_buffered_bytes += current_write_buf_->size();
224 total_buffered_bytes += GetTotalSizeOfPendingWriteBufs();
225 if (total_buffered_bytes > max_pending_send_allowed_)
228 // TODO(tyoshino): Split data into smaller chunks e.g. 8KiB to free consumed
229 // buffer progressively
230 pending_write_bufs_.push_back(make_scoped_refptr(
231 new IOBufferWithSize(len)));
232 memcpy(pending_write_bufs_.back()->data(), data, len);
234 // If current_write_buf_ is not NULL, it means that a) there's ongoing write
235 // operation or b) the connection is being closed. If a), the buffer we just
236 // pushed will be automatically handled when the completion callback runs
237 // the loop, and therefore we don't need to enqueue DoLoop(). If b), it's ok
238 // to do nothing. If current_write_buf_ is NULL, to make sure DoLoop() is
239 // ran soon, enequeue it.
240 if (!current_write_buf_.get()) {
241 // Send pending data asynchronously, so that delegate won't be called
242 // back before returning from SendData().
243 base::MessageLoop::current()->PostTask(
244 FROM_HERE, base::Bind(&SocketStream::DoLoop, this, OK));
250 void SocketStream::Close() {
251 DCHECK(base::MessageLoop::current())
252 << "The current base::MessageLoop must exist";
253 DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
254 << "The current base::MessageLoop must be TYPE_IO";
255 // If next_state_ is STATE_NONE, the socket was not opened, or already
256 // closed. So, return immediately.
257 // Otherwise, it might call Finish() more than once, so breaks balance
258 // of AddRef() and Release() in Connect() and Finish(), respectively.
259 if (next_state_ == STATE_NONE)
261 base::MessageLoop::current()->PostTask(
262 FROM_HERE, base::Bind(&SocketStream::DoClose, this));
265 void SocketStream::RestartWithAuth(const AuthCredentials& credentials) {
266 DCHECK(base::MessageLoop::current())
267 << "The current base::MessageLoop must exist";
268 DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
269 << "The current base::MessageLoop must be TYPE_IO";
270 DCHECK(proxy_auth_controller_.get());
271 if (!connection_->socket()) {
272 DVLOG(1) << "Socket is closed before restarting with auth.";
276 proxy_auth_controller_->ResetAuth(credentials);
278 base::MessageLoop::current()->PostTask(
279 FROM_HERE, base::Bind(&SocketStream::DoRestartWithAuth, this));
282 void SocketStream::DetachDelegate() {
286 // Prevent the rest of the function from executing if we are being called from
288 if (next_state_ == STATE_NONE)
290 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
291 // We don't need to send pending data when client detach the delegate.
292 pending_write_bufs_.clear();
296 const ProxyServer& SocketStream::proxy_server() const {
297 return proxy_info_.proxy_server();
300 void SocketStream::SetClientSocketFactory(
301 ClientSocketFactory* factory) {
306 void SocketStream::CancelWithError(int error) {
307 base::MessageLoop::current()->PostTask(
308 FROM_HERE, base::Bind(&SocketStream::DoLoop, this, error));
311 void SocketStream::CancelWithSSLError(const SSLInfo& ssl_info) {
312 CancelWithError(MapCertStatusToNetError(ssl_info.cert_status));
315 void SocketStream::ContinueDespiteError() {
316 base::MessageLoop::current()->PostTask(
317 FROM_HERE, base::Bind(&SocketStream::DoLoop, this, OK));
320 SocketStream::~SocketStream() {
323 DCHECK(!pac_request_);
326 SocketStream::RequestHeaders::~RequestHeaders() { data_ = NULL; }
328 void SocketStream::set_addresses(const AddressList& addresses) {
329 addresses_ = addresses;
332 void SocketStream::DoClose() {
334 // If next_state_ is STATE_TCP_CONNECT, it's waiting other socket
335 // establishing connection. If next_state_ is STATE_AUTH_REQUIRED, it's
336 // waiting for restarting. In these states, we'll close the SocketStream
338 if (next_state_ == STATE_TCP_CONNECT || next_state_ == STATE_AUTH_REQUIRED) {
342 // If next_state_ is STATE_READ_WRITE, we'll run DoLoop and close
344 // If it's writing now, we should defer the closing after the current
345 // writing is completed.
346 if (next_state_ == STATE_READ_WRITE && !current_write_buf_.get())
349 // In other next_state_, we'll wait for callback of other APIs, such as
353 void SocketStream::Finish(int result) {
354 DCHECK(base::MessageLoop::current())
355 << "The current base::MessageLoop must exist";
356 DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
357 << "The current base::MessageLoop must be TYPE_IO";
358 DCHECK_LE(result, OK);
360 result = ERR_CONNECTION_CLOSED;
361 DCHECK_EQ(next_state_, STATE_NONE);
362 DVLOG(1) << "Finish result=" << ErrorToString(result);
366 if (result != ERR_CONNECTION_CLOSED && delegate_)
367 delegate_->OnError(this, result);
368 if (result != ERR_PROTOCOL_SWITCHED && delegate_)
369 delegate_->OnClose(this);
375 int SocketStream::DidEstablishConnection() {
376 if (!connection_->socket() || !connection_->socket()->IsConnected()) {
377 next_state_ = STATE_CLOSE;
378 return ERR_CONNECTION_FAILED;
380 next_state_ = STATE_READ_WRITE;
381 metrics_->OnConnected();
383 net_log_.EndEvent(NetLog::TYPE_SOCKET_STREAM_CONNECT);
385 delegate_->OnConnected(this, max_pending_send_allowed_);
390 int SocketStream::DidReceiveData(int result) {
391 DCHECK(read_buf_.get());
392 DCHECK_GT(result, 0);
393 net_log_.AddEvent(NetLog::TYPE_SOCKET_STREAM_RECEIVED);
395 metrics_->OnRead(len);
397 // Notify recevied data to delegate.
398 delegate_->OnReceivedData(this, read_buf_->data(), len);
404 void SocketStream::DidSendData(int result) {
405 DCHECK_GT(result, 0);
406 DCHECK(current_write_buf_.get());
407 net_log_.AddEvent(NetLog::TYPE_SOCKET_STREAM_SENT);
409 int bytes_sent = result;
411 metrics_->OnWrite(bytes_sent);
413 current_write_buf_->DidConsume(result);
415 if (current_write_buf_->BytesRemaining())
418 size_t bytes_freed = current_write_buf_->size();
420 current_write_buf_ = NULL;
422 // We freed current_write_buf_ and this instance is now able to accept more
423 // data via SendData() (note that DidConsume() doesn't free consumed memory).
424 // We can tell that to delegate_ by calling OnSentData().
426 delegate_->OnSentData(this, bytes_freed);
429 void SocketStream::OnIOCompleted(int result) {
433 void SocketStream::OnReadCompleted(int result) {
435 // 0 indicates end-of-file, so socket was closed.
436 // Don't close the socket if it's still writing.
437 server_closed_ = true;
438 } else if (result > 0 && read_buf_.get()) {
439 result = DidReceiveData(result);
444 void SocketStream::OnWriteCompleted(int result) {
445 waiting_for_write_completion_ = false;
453 void SocketStream::DoLoop(int result) {
454 if (next_state_ == STATE_NONE)
457 // If context was not set, close immediately.
459 next_state_ = STATE_CLOSE;
462 State state = next_state_;
463 next_state_ = STATE_NONE;
465 case STATE_BEFORE_CONNECT:
466 DCHECK_EQ(OK, result);
467 result = DoBeforeConnect();
469 case STATE_BEFORE_CONNECT_COMPLETE:
470 result = DoBeforeConnectComplete(result);
472 case STATE_RESOLVE_PROXY:
473 DCHECK_EQ(OK, result);
474 result = DoResolveProxy();
476 case STATE_RESOLVE_PROXY_COMPLETE:
477 result = DoResolveProxyComplete(result);
479 case STATE_RESOLVE_HOST:
480 DCHECK_EQ(OK, result);
481 result = DoResolveHost();
483 case STATE_RESOLVE_HOST_COMPLETE:
484 result = DoResolveHostComplete(result);
486 case STATE_RESOLVE_PROTOCOL:
487 result = DoResolveProtocol(result);
489 case STATE_RESOLVE_PROTOCOL_COMPLETE:
490 result = DoResolveProtocolComplete(result);
492 case STATE_TCP_CONNECT:
493 result = DoTcpConnect(result);
495 case STATE_TCP_CONNECT_COMPLETE:
496 result = DoTcpConnectComplete(result);
498 case STATE_GENERATE_PROXY_AUTH_TOKEN:
499 result = DoGenerateProxyAuthToken();
501 case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
502 result = DoGenerateProxyAuthTokenComplete(result);
504 case STATE_WRITE_TUNNEL_HEADERS:
505 DCHECK_EQ(OK, result);
506 result = DoWriteTunnelHeaders();
508 case STATE_WRITE_TUNNEL_HEADERS_COMPLETE:
509 result = DoWriteTunnelHeadersComplete(result);
511 case STATE_READ_TUNNEL_HEADERS:
512 DCHECK_EQ(OK, result);
513 result = DoReadTunnelHeaders();
515 case STATE_READ_TUNNEL_HEADERS_COMPLETE:
516 result = DoReadTunnelHeadersComplete(result);
518 case STATE_SOCKS_CONNECT:
519 DCHECK_EQ(OK, result);
520 result = DoSOCKSConnect();
522 case STATE_SOCKS_CONNECT_COMPLETE:
523 result = DoSOCKSConnectComplete(result);
525 case STATE_SECURE_PROXY_CONNECT:
526 DCHECK_EQ(OK, result);
527 result = DoSecureProxyConnect();
529 case STATE_SECURE_PROXY_CONNECT_COMPLETE:
530 result = DoSecureProxyConnectComplete(result);
532 case STATE_SECURE_PROXY_HANDLE_CERT_ERROR:
533 result = DoSecureProxyHandleCertError(result);
535 case STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE:
536 result = DoSecureProxyHandleCertErrorComplete(result);
538 case STATE_SSL_CONNECT:
539 DCHECK_EQ(OK, result);
540 result = DoSSLConnect();
542 case STATE_SSL_CONNECT_COMPLETE:
543 result = DoSSLConnectComplete(result);
545 case STATE_SSL_HANDLE_CERT_ERROR:
546 result = DoSSLHandleCertError(result);
548 case STATE_SSL_HANDLE_CERT_ERROR_COMPLETE:
549 result = DoSSLHandleCertErrorComplete(result);
551 case STATE_READ_WRITE:
552 result = DoReadWrite(result);
554 case STATE_AUTH_REQUIRED:
555 // It might be called when DoClose is called while waiting in
556 // STATE_AUTH_REQUIRED.
560 DCHECK_LE(result, OK);
564 NOTREACHED() << "bad state " << state;
568 if (state == STATE_RESOLVE_PROTOCOL && result == ERR_PROTOCOL_SWITCHED)
570 // If the connection is not established yet and had actual errors,
571 // record the error. In next iteration, it will close the connection.
572 if (state != STATE_READ_WRITE && result < ERR_IO_PENDING) {
573 net_log_.EndEventWithNetErrorCode(
574 NetLog::TYPE_SOCKET_STREAM_CONNECT, result);
576 } while (result != ERR_IO_PENDING);
579 int SocketStream::DoBeforeConnect() {
580 next_state_ = STATE_BEFORE_CONNECT_COMPLETE;
581 if (!context_ || !context_->network_delegate())
584 int result = context_->network_delegate()->NotifyBeforeSocketStreamConnect(
586 if (result != OK && result != ERR_IO_PENDING)
587 next_state_ = STATE_CLOSE;
592 int SocketStream::DoBeforeConnectComplete(int result) {
593 DCHECK_NE(ERR_IO_PENDING, result);
596 next_state_ = STATE_RESOLVE_PROXY;
598 next_state_ = STATE_CLOSE;
603 int SocketStream::DoResolveProxy() {
605 DCHECK(!pac_request_);
606 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
608 if (!proxy_url_.is_valid()) {
609 next_state_ = STATE_CLOSE;
610 return ERR_INVALID_ARGUMENT;
613 // TODO(toyoshim): Check server advertisement of SPDY through the HTTP
614 // Alternate-Protocol header, then switch to SPDY if SPDY is available.
615 // Usually we already have a session to the SPDY server because JavaScript
616 // running WebSocket itself would be served by SPDY. But, in some situation
617 // (E.g. Used by Chrome Extensions or used for cross origin connection), this
618 // connection might be the first one. At that time, we should check
619 // Alternate-Protocol header here for ws:// or TLS NPN extension for wss:// .
621 return context_->proxy_service()->ResolveProxy(
622 proxy_url_, &proxy_info_, io_callback_, &pac_request_, net_log_);
625 int SocketStream::DoResolveProxyComplete(int result) {
628 DVLOG(1) << "Failed to resolve proxy: " << result;
630 delegate_->OnError(this, result);
631 proxy_info_.UseDirect();
633 if (proxy_info_.is_direct()) {
634 // If proxy was not found for original URL (i.e. websocket URL),
635 // try again with https URL, like Safari implementation.
636 // Note that we don't want to use http proxy, because we'll use tunnel
637 // proxy using CONNECT method, which is used by https proxy.
638 if (!proxy_url_.SchemeIs("https")) {
639 const std::string scheme = "https";
640 GURL::Replacements repl;
641 repl.SetSchemeStr(scheme);
642 proxy_url_ = url_.ReplaceComponents(repl);
643 DVLOG(1) << "Try https proxy: " << proxy_url_;
644 next_state_ = STATE_RESOLVE_PROXY;
649 if (proxy_info_.is_empty()) {
650 // No proxies/direct to choose from. This happens when we don't support any
651 // of the proxies in the returned list.
652 return ERR_NO_SUPPORTED_PROXIES;
655 next_state_ = STATE_RESOLVE_HOST;
659 int SocketStream::DoResolveHost() {
660 next_state_ = STATE_RESOLVE_HOST_COMPLETE;
662 DCHECK(!proxy_info_.is_empty());
663 if (proxy_info_.is_direct())
664 proxy_mode_ = kDirectConnection;
665 else if (proxy_info_.proxy_server().is_socks())
666 proxy_mode_ = kSOCKSProxy;
668 proxy_mode_ = kTunnelProxy;
670 // Determine the host and port to connect to.
671 HostPortPair host_port_pair;
672 if (proxy_mode_ != kDirectConnection) {
673 host_port_pair = proxy_info_.proxy_server().host_port_pair();
675 host_port_pair = HostPortPair::FromURL(url_);
678 HostResolver::RequestInfo resolve_info(host_port_pair);
680 DCHECK(context_->host_resolver());
681 resolver_.reset(new SingleRequestHostResolver(context_->host_resolver()));
682 return resolver_->Resolve(resolve_info,
685 base::Bind(&SocketStream::OnIOCompleted, this),
689 int SocketStream::DoResolveHostComplete(int result) {
691 next_state_ = STATE_RESOLVE_PROTOCOL;
693 next_state_ = STATE_CLOSE;
694 // TODO(ukai): if error occured, reconsider proxy after error.
698 int SocketStream::DoResolveProtocol(int result) {
699 DCHECK_EQ(OK, result);
702 next_state_ = STATE_CLOSE;
706 next_state_ = STATE_RESOLVE_PROTOCOL_COMPLETE;
707 result = delegate_->OnStartOpenConnection(this, io_callback_);
708 if (result == ERR_IO_PENDING)
709 metrics_->OnWaitConnection();
710 else if (result != OK && result != ERR_PROTOCOL_SWITCHED)
711 next_state_ = STATE_CLOSE;
715 int SocketStream::DoResolveProtocolComplete(int result) {
716 DCHECK_NE(ERR_IO_PENDING, result);
718 if (result == ERR_PROTOCOL_SWITCHED) {
719 next_state_ = STATE_CLOSE;
720 metrics_->OnCountWireProtocolType(
721 SocketStreamMetrics::WIRE_PROTOCOL_SPDY);
722 } else if (result == OK) {
723 next_state_ = STATE_TCP_CONNECT;
724 metrics_->OnCountWireProtocolType(
725 SocketStreamMetrics::WIRE_PROTOCOL_WEBSOCKET);
727 next_state_ = STATE_CLOSE;
732 int SocketStream::DoTcpConnect(int result) {
734 next_state_ = STATE_CLOSE;
737 next_state_ = STATE_TCP_CONNECT_COMPLETE;
739 connection_->SetSocket(
740 factory_->CreateTransportClientSocket(addresses_,
743 metrics_->OnStartConnection();
744 return connection_->socket()->Connect(io_callback_);
747 int SocketStream::DoTcpConnectComplete(int result) {
748 // TODO(ukai): if error occured, reconsider proxy after error.
750 next_state_ = STATE_CLOSE;
754 if (proxy_mode_ == kTunnelProxy) {
755 if (proxy_info_.is_https())
756 next_state_ = STATE_SECURE_PROXY_CONNECT;
758 next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
759 } else if (proxy_mode_ == kSOCKSProxy) {
760 next_state_ = STATE_SOCKS_CONNECT;
761 } else if (is_secure()) {
762 next_state_ = STATE_SSL_CONNECT;
764 result = DidEstablishConnection();
769 int SocketStream::DoGenerateProxyAuthToken() {
770 next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE;
771 if (!proxy_auth_controller_.get()) {
773 DCHECK(context_->http_transaction_factory());
774 DCHECK(context_->http_transaction_factory()->GetSession());
775 HttpNetworkSession* session =
776 context_->http_transaction_factory()->GetSession();
777 const char* scheme = proxy_info_.is_https() ? "https://" : "http://";
778 GURL auth_url(scheme +
779 proxy_info_.proxy_server().host_port_pair().ToString());
780 proxy_auth_controller_ =
781 new HttpAuthController(HttpAuth::AUTH_PROXY,
783 session->http_auth_cache(),
784 session->http_auth_handler_factory());
786 HttpRequestInfo request_info;
787 request_info.url = url_;
788 request_info.method = "CONNECT";
789 return proxy_auth_controller_->MaybeGenerateAuthToken(
790 &request_info, io_callback_, net_log_);
793 int SocketStream::DoGenerateProxyAuthTokenComplete(int result) {
795 next_state_ = STATE_CLOSE;
799 next_state_ = STATE_WRITE_TUNNEL_HEADERS;
803 int SocketStream::DoWriteTunnelHeaders() {
804 DCHECK_EQ(kTunnelProxy, proxy_mode_);
806 next_state_ = STATE_WRITE_TUNNEL_HEADERS_COMPLETE;
808 if (!tunnel_request_headers_.get()) {
809 metrics_->OnCountConnectionType(SocketStreamMetrics::TUNNEL_CONNECTION);
810 tunnel_request_headers_ = new RequestHeaders();
811 tunnel_request_headers_bytes_sent_ = 0;
813 if (tunnel_request_headers_->headers_.empty()) {
814 HttpRequestHeaders request_headers;
815 request_headers.SetHeader("Host", GetHostAndOptionalPort(url_));
816 request_headers.SetHeader("Proxy-Connection", "keep-alive");
817 if (proxy_auth_controller_.get() && proxy_auth_controller_->HaveAuth())
818 proxy_auth_controller_->AddAuthorizationHeader(&request_headers);
819 tunnel_request_headers_->headers_ = base::StringPrintf(
820 "CONNECT %s HTTP/1.1\r\n"
822 GetHostAndPort(url_).c_str(),
823 request_headers.ToString().c_str());
825 tunnel_request_headers_->SetDataOffset(tunnel_request_headers_bytes_sent_);
826 int buf_len = static_cast<int>(tunnel_request_headers_->headers_.size() -
827 tunnel_request_headers_bytes_sent_);
828 DCHECK_GT(buf_len, 0);
829 return connection_->socket()->Write(
830 tunnel_request_headers_.get(), buf_len, io_callback_);
833 int SocketStream::DoWriteTunnelHeadersComplete(int result) {
834 DCHECK_EQ(kTunnelProxy, proxy_mode_);
837 next_state_ = STATE_CLOSE;
841 tunnel_request_headers_bytes_sent_ += result;
842 if (tunnel_request_headers_bytes_sent_ <
843 tunnel_request_headers_->headers_.size()) {
844 next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
846 // Handling a cert error or a client cert request requires reconnection.
847 // DoWriteTunnelHeaders() will be called again.
848 // Thus |tunnel_request_headers_bytes_sent_| should be reset to 0 for
849 // sending |tunnel_request_headers_| correctly.
850 tunnel_request_headers_bytes_sent_ = 0;
851 next_state_ = STATE_READ_TUNNEL_HEADERS;
856 int SocketStream::DoReadTunnelHeaders() {
857 DCHECK_EQ(kTunnelProxy, proxy_mode_);
859 next_state_ = STATE_READ_TUNNEL_HEADERS_COMPLETE;
861 if (!tunnel_response_headers_.get()) {
862 tunnel_response_headers_ = new ResponseHeaders();
863 tunnel_response_headers_capacity_ = kMaxTunnelResponseHeadersSize;
864 tunnel_response_headers_->Realloc(tunnel_response_headers_capacity_);
865 tunnel_response_headers_len_ = 0;
868 int buf_len = tunnel_response_headers_capacity_ -
869 tunnel_response_headers_len_;
870 tunnel_response_headers_->SetDataOffset(tunnel_response_headers_len_);
871 CHECK(tunnel_response_headers_->data());
873 return connection_->socket()->Read(
874 tunnel_response_headers_.get(), buf_len, io_callback_);
877 int SocketStream::DoReadTunnelHeadersComplete(int result) {
878 DCHECK_EQ(kTunnelProxy, proxy_mode_);
881 next_state_ = STATE_CLOSE;
886 // 0 indicates end-of-file, so socket was closed.
887 next_state_ = STATE_CLOSE;
888 return ERR_CONNECTION_CLOSED;
891 tunnel_response_headers_len_ += result;
892 DCHECK(tunnel_response_headers_len_ <= tunnel_response_headers_capacity_);
894 int eoh = HttpUtil::LocateEndOfHeaders(
895 tunnel_response_headers_->headers(), tunnel_response_headers_len_, 0);
897 if (tunnel_response_headers_len_ >= kMaxTunnelResponseHeadersSize) {
898 next_state_ = STATE_CLOSE;
899 return ERR_RESPONSE_HEADERS_TOO_BIG;
902 next_state_ = STATE_READ_TUNNEL_HEADERS;
905 // DidReadResponseHeaders
906 scoped_refptr<HttpResponseHeaders> headers;
907 headers = new HttpResponseHeaders(
908 HttpUtil::AssembleRawHeaders(tunnel_response_headers_->headers(), eoh));
909 if (headers->GetParsedHttpVersion() < HttpVersion(1, 0)) {
910 // Require the "HTTP/1.x" status line.
911 next_state_ = STATE_CLOSE;
912 return ERR_TUNNEL_CONNECTION_FAILED;
914 switch (headers->response_code()) {
917 DCHECK_EQ(eoh, tunnel_response_headers_len_);
918 next_state_ = STATE_SSL_CONNECT;
920 result = DidEstablishConnection();
922 next_state_ = STATE_CLOSE;
925 if ((eoh < tunnel_response_headers_len_) && delegate_)
926 delegate_->OnReceivedData(
927 this, tunnel_response_headers_->headers() + eoh,
928 tunnel_response_headers_len_ - eoh);
931 case 407: // Proxy Authentication Required.
932 if (proxy_mode_ != kTunnelProxy)
933 return ERR_UNEXPECTED_PROXY_AUTH;
935 result = proxy_auth_controller_->HandleAuthChallenge(
936 headers, false, true, net_log_);
939 DCHECK(!proxy_info_.is_empty());
940 next_state_ = STATE_AUTH_REQUIRED;
941 if (proxy_auth_controller_->HaveAuth()) {
942 base::MessageLoop::current()->PostTask(
943 FROM_HERE, base::Bind(&SocketStream::DoRestartWithAuth, this));
944 return ERR_IO_PENDING;
947 // Wait until RestartWithAuth or Close is called.
948 base::MessageLoop::current()->PostTask(
949 FROM_HERE, base::Bind(&SocketStream::DoAuthRequired, this));
950 return ERR_IO_PENDING;
956 next_state_ = STATE_CLOSE;
957 return ERR_TUNNEL_CONNECTION_FAILED;
960 int SocketStream::DoSOCKSConnect() {
961 DCHECK_EQ(kSOCKSProxy, proxy_mode_);
963 next_state_ = STATE_SOCKS_CONNECT_COMPLETE;
965 HostResolver::RequestInfo req_info(HostPortPair::FromURL(url_));
967 DCHECK(!proxy_info_.is_empty());
968 scoped_ptr<StreamSocket> s;
969 if (proxy_info_.proxy_server().scheme() == ProxyServer::SCHEME_SOCKS5) {
970 s.reset(new SOCKS5ClientSocket(connection_.Pass(), req_info));
972 s.reset(new SOCKSClientSocket(connection_.Pass(),
975 context_->host_resolver()));
977 connection_.reset(new ClientSocketHandle);
978 connection_->SetSocket(s.Pass());
979 metrics_->OnCountConnectionType(SocketStreamMetrics::SOCKS_CONNECTION);
980 return connection_->socket()->Connect(io_callback_);
983 int SocketStream::DoSOCKSConnectComplete(int result) {
984 DCHECK_EQ(kSOCKSProxy, proxy_mode_);
988 next_state_ = STATE_SSL_CONNECT;
990 result = DidEstablishConnection();
992 next_state_ = STATE_CLOSE;
997 int SocketStream::DoSecureProxyConnect() {
999 SSLClientSocketContext ssl_context;
1000 ssl_context.cert_verifier = context_->cert_verifier();
1001 ssl_context.transport_security_state = context_->transport_security_state();
1002 ssl_context.server_bound_cert_service = context_->server_bound_cert_service();
1003 scoped_ptr<StreamSocket> socket(factory_->CreateSSLClientSocket(
1005 proxy_info_.proxy_server().host_port_pair(),
1008 connection_.reset(new ClientSocketHandle);
1009 connection_->SetSocket(socket.Pass());
1010 next_state_ = STATE_SECURE_PROXY_CONNECT_COMPLETE;
1011 metrics_->OnCountConnectionType(SocketStreamMetrics::SECURE_PROXY_CONNECTION);
1012 return connection_->socket()->Connect(io_callback_);
1015 int SocketStream::DoSecureProxyConnectComplete(int result) {
1016 DCHECK_EQ(STATE_NONE, next_state_);
1017 // Reconnect with client authentication.
1018 if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED)
1019 return HandleCertificateRequest(result, &proxy_ssl_config_);
1021 if (IsCertificateError(result))
1022 next_state_ = STATE_SECURE_PROXY_HANDLE_CERT_ERROR;
1023 else if (result == OK)
1024 next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
1026 next_state_ = STATE_CLOSE;
1030 int SocketStream::DoSecureProxyHandleCertError(int result) {
1031 DCHECK_EQ(STATE_NONE, next_state_);
1032 DCHECK(IsCertificateError(result));
1033 result = HandleCertificateError(result);
1034 if (result == ERR_IO_PENDING)
1035 next_state_ = STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE;
1037 next_state_ = STATE_CLOSE;
1041 int SocketStream::DoSecureProxyHandleCertErrorComplete(int result) {
1042 DCHECK_EQ(STATE_NONE, next_state_);
1044 if (!connection_->socket()->IsConnectedAndIdle())
1045 return AllowCertErrorForReconnection(&proxy_ssl_config_);
1046 next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
1048 next_state_ = STATE_CLOSE;
1053 int SocketStream::DoSSLConnect() {
1055 SSLClientSocketContext ssl_context;
1056 ssl_context.cert_verifier = context_->cert_verifier();
1057 ssl_context.transport_security_state = context_->transport_security_state();
1058 ssl_context.server_bound_cert_service = context_->server_bound_cert_service();
1059 scoped_ptr<StreamSocket> socket(
1060 factory_->CreateSSLClientSocket(connection_.Pass(),
1061 HostPortPair::FromURL(url_),
1064 connection_.reset(new ClientSocketHandle);
1065 connection_->SetSocket(socket.Pass());
1066 next_state_ = STATE_SSL_CONNECT_COMPLETE;
1067 metrics_->OnCountConnectionType(SocketStreamMetrics::SSL_CONNECTION);
1068 return connection_->socket()->Connect(io_callback_);
1071 int SocketStream::DoSSLConnectComplete(int result) {
1072 DCHECK_EQ(STATE_NONE, next_state_);
1073 // Reconnect with client authentication.
1074 if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED)
1075 return HandleCertificateRequest(result, &server_ssl_config_);
1077 if (IsCertificateError(result))
1078 next_state_ = STATE_SSL_HANDLE_CERT_ERROR;
1079 else if (result == OK)
1080 result = DidEstablishConnection();
1082 next_state_ = STATE_CLOSE;
1086 int SocketStream::DoSSLHandleCertError(int result) {
1087 DCHECK_EQ(STATE_NONE, next_state_);
1088 DCHECK(IsCertificateError(result));
1089 result = HandleCertificateError(result);
1090 if (result == OK || result == ERR_IO_PENDING)
1091 next_state_ = STATE_SSL_HANDLE_CERT_ERROR_COMPLETE;
1093 next_state_ = STATE_CLOSE;
1097 int SocketStream::DoSSLHandleCertErrorComplete(int result) {
1098 DCHECK_EQ(STATE_NONE, next_state_);
1099 // TODO(toyoshim): Upgrade to SPDY through TLS NPN extension if possible.
1100 // If we use HTTPS and this is the first connection to the SPDY server,
1101 // we should take care of TLS NPN extension here.
1104 if (!connection_->socket()->IsConnectedAndIdle())
1105 return AllowCertErrorForReconnection(&server_ssl_config_);
1106 result = DidEstablishConnection();
1108 next_state_ = STATE_CLOSE;
1113 int SocketStream::DoReadWrite(int result) {
1115 next_state_ = STATE_CLOSE;
1118 if (!connection_->socket() || !connection_->socket()->IsConnected()) {
1119 next_state_ = STATE_CLOSE;
1120 return ERR_CONNECTION_CLOSED;
1123 // If client has requested close(), and there's nothing to write, then
1124 // let's close the socket.
1125 // We don't care about receiving data after the socket is closed.
1126 if (closing_ && !current_write_buf_.get() && pending_write_bufs_.empty()) {
1127 connection_->socket()->Disconnect();
1128 next_state_ = STATE_CLOSE;
1132 next_state_ = STATE_READ_WRITE;
1134 // If server already closed the socket, we don't try to read.
1135 if (!server_closed_) {
1136 if (!read_buf_.get()) {
1137 // No read pending and server didn't close the socket.
1138 read_buf_ = new IOBuffer(kReadBufferSize);
1139 result = connection_->socket()->Read(
1142 base::Bind(&SocketStream::OnReadCompleted, base::Unretained(this)));
1144 return DidReceiveData(result);
1145 } else if (result == 0) {
1146 // 0 indicates end-of-file, so socket was closed.
1147 next_state_ = STATE_CLOSE;
1148 server_closed_ = true;
1149 return ERR_CONNECTION_CLOSED;
1151 // If read is pending, try write as well.
1152 // Otherwise, return the result and do next loop (to close the
1154 if (result != ERR_IO_PENDING) {
1155 next_state_ = STATE_CLOSE;
1156 server_closed_ = true;
1161 DCHECK(read_buf_.get());
1164 if (waiting_for_write_completion_)
1165 return ERR_IO_PENDING;
1167 if (!current_write_buf_.get()) {
1168 if (pending_write_bufs_.empty()) {
1169 // Nothing buffered for send.
1170 return ERR_IO_PENDING;
1173 current_write_buf_ = new DrainableIOBuffer(
1174 pending_write_bufs_.front().get(), pending_write_bufs_.front()->size());
1175 pending_write_bufs_.pop_front();
1178 result = connection_->socket()->Write(
1179 current_write_buf_.get(),
1180 current_write_buf_->BytesRemaining(),
1181 base::Bind(&SocketStream::OnWriteCompleted, base::Unretained(this)));
1183 if (result == ERR_IO_PENDING) {
1184 waiting_for_write_completion_ = true;
1185 } else if (result < 0) {
1186 // Shortcut. Enter STATE_CLOSE now by changing next_state_ here than by
1187 // calling DoReadWrite() again with the error code.
1188 next_state_ = STATE_CLOSE;
1189 } else if (result > 0) {
1190 // Write is not pending. Return OK and do next loop.
1191 DidSendData(result);
1198 GURL SocketStream::ProxyAuthOrigin() const {
1199 DCHECK(!proxy_info_.is_empty());
1200 return GURL("http://" +
1201 proxy_info_.proxy_server().host_port_pair().ToString());
1204 int SocketStream::HandleCertificateRequest(int result, SSLConfig* ssl_config) {
1205 if (ssl_config->send_client_cert) {
1206 // We already have performed SSL client authentication once and failed.
1210 DCHECK(connection_->socket());
1211 scoped_refptr<SSLCertRequestInfo> cert_request_info = new SSLCertRequestInfo;
1212 SSLClientSocket* ssl_socket =
1213 static_cast<SSLClientSocket*>(connection_->socket());
1214 ssl_socket->GetSSLCertRequestInfo(cert_request_info.get());
1216 HttpTransactionFactory* factory = context_->http_transaction_factory();
1219 scoped_refptr<HttpNetworkSession> session = factory->GetSession();
1223 // If the user selected one of the certificates in client_certs or declined
1224 // to provide one for this server before, use the past decision
1226 scoped_refptr<X509Certificate> client_cert;
1227 if (!session->ssl_client_auth_cache()->Lookup(
1228 cert_request_info->host_and_port, &client_cert)) {
1232 // Note: |client_cert| may be NULL, indicating that the caller
1233 // wishes to proceed anonymously (eg: continue the handshake
1234 // without sending a client cert)
1236 // Check that the certificate selected is still a certificate the server
1237 // is likely to accept, based on the criteria supplied in the
1238 // CertificateRequest message.
1239 const std::vector<std::string>& cert_authorities =
1240 cert_request_info->cert_authorities;
1241 if (client_cert.get() && !cert_authorities.empty() &&
1242 !client_cert->IsIssuedByEncoded(cert_authorities)) {
1246 ssl_config->send_client_cert = true;
1247 ssl_config->client_cert = client_cert;
1248 next_state_ = STATE_TCP_CONNECT;
1252 int SocketStream::AllowCertErrorForReconnection(SSLConfig* ssl_config) {
1254 // The SSL handshake didn't finish, or the server closed the SSL connection.
1255 // So, we should restart establishing connection with the certificate in
1256 // allowed bad certificates in |ssl_config|.
1257 // See also net/http/http_network_transaction.cc HandleCertificateError() and
1258 // RestartIgnoringLastError().
1259 SSLClientSocket* ssl_socket =
1260 static_cast<SSLClientSocket*>(connection_->socket());
1262 ssl_socket->GetSSLInfo(&ssl_info);
1263 if (ssl_info.cert.get() == NULL ||
1264 ssl_config->IsAllowedBadCert(ssl_info.cert.get(), NULL)) {
1265 // If we already have the certificate in the set of allowed bad
1266 // certificates, we did try it and failed again, so we should not
1267 // retry again: the connection should fail at last.
1268 next_state_ = STATE_CLOSE;
1269 return ERR_UNEXPECTED;
1271 // Add the bad certificate to the set of allowed certificates in the
1272 // SSL config object.
1273 SSLConfig::CertAndStatus bad_cert;
1274 if (!X509Certificate::GetDEREncoded(ssl_info.cert->os_cert_handle(),
1275 &bad_cert.der_cert)) {
1276 next_state_ = STATE_CLOSE;
1277 return ERR_UNEXPECTED;
1279 bad_cert.cert_status = ssl_info.cert_status;
1280 ssl_config->allowed_bad_certs.push_back(bad_cert);
1281 // Restart connection ignoring the bad certificate.
1282 connection_->socket()->Disconnect();
1283 connection_->SetSocket(scoped_ptr<StreamSocket>());
1284 next_state_ = STATE_TCP_CONNECT;
1288 void SocketStream::DoAuthRequired() {
1289 if (delegate_ && proxy_auth_controller_.get())
1290 delegate_->OnAuthRequired(this, proxy_auth_controller_->auth_info().get());
1292 DoLoop(ERR_UNEXPECTED);
1295 void SocketStream::DoRestartWithAuth() {
1296 DCHECK_EQ(next_state_, STATE_AUTH_REQUIRED);
1297 tunnel_request_headers_ = NULL;
1298 tunnel_request_headers_bytes_sent_ = 0;
1299 tunnel_response_headers_ = NULL;
1300 tunnel_response_headers_capacity_ = 0;
1301 tunnel_response_headers_len_ = 0;
1303 next_state_ = STATE_TCP_CONNECT;
1307 int SocketStream::HandleCertificateError(int result) {
1308 DCHECK(IsCertificateError(result));
1309 SSLClientSocket* ssl_socket =
1310 static_cast<SSLClientSocket*>(connection_->socket());
1316 if (SSLClientSocket::IgnoreCertError(result, LOAD_IGNORE_ALL_CERT_ERRORS)) {
1317 const HttpNetworkSession::Params* session_params =
1318 context_->GetNetworkSessionParams();
1319 if (session_params && session_params->ignore_certificate_errors)
1327 ssl_socket->GetSSLInfo(&ssl_info);
1329 TransportSecurityState::DomainState domain_state;
1330 const bool fatal = context_->transport_security_state() &&
1331 context_->transport_security_state()->GetDomainState(url_.host(),
1332 SSLConfigService::IsSNIAvailable(context_->ssl_config_service()),
1334 domain_state.ShouldSSLErrorsBeFatal();
1336 delegate_->OnSSLCertificateError(this, ssl_info, fatal);
1337 return ERR_IO_PENDING;