Home | History | Annotate | Download | only in socket_stream
      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.
      4 //
      5 // TODO(ukai): code is similar with http_network_transaction.cc.  We should
      6 //   think about ways to share code, if possible.
      7 
      8 #include "net/socket_stream/socket_stream.h"
      9 
     10 #include <set>
     11 #include <string>
     12 #include <vector>
     13 
     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"
     46 
     47 static const int kMaxPendingSendAllowed = 32768;  // 32 kilobytes.
     48 static const int kReadBufferSize = 4096;
     49 
     50 namespace net {
     51 
     52 int SocketStream::Delegate::OnStartOpenConnection(
     53     SocketStream* socket, const CompletionCallback& callback) {
     54   return OK;
     55 }
     56 
     57 void SocketStream::Delegate::OnAuthRequired(SocketStream* socket,
     58                                             AuthChallengeInfo* auth_info) {
     59   // By default, no credential is available and close the connection.
     60   socket->Close();
     61 }
     62 
     63 void SocketStream::Delegate::OnSSLCertificateError(
     64     SocketStream* socket,
     65     const SSLInfo& ssl_info,
     66     bool fatal) {
     67   socket->CancelWithSSLError(ssl_info);
     68 }
     69 
     70 bool SocketStream::Delegate::CanGetCookies(SocketStream* socket,
     71                                            const GURL& url) {
     72   return true;
     73 }
     74 
     75 bool SocketStream::Delegate::CanSetCookie(SocketStream* request,
     76                                           const GURL& url,
     77                                           const std::string& cookie_line,
     78                                           CookieOptions* options) {
     79   return true;
     80 }
     81 
     82 SocketStream::ResponseHeaders::ResponseHeaders() : IOBuffer() {}
     83 
     84 void SocketStream::ResponseHeaders::Realloc(size_t new_size) {
     85   headers_.reset(static_cast<char*>(realloc(headers_.release(), new_size)));
     86 }
     87 
     88 SocketStream::ResponseHeaders::~ResponseHeaders() { data_ = NULL; }
     89 
     90 SocketStream::SocketStream(const GURL& url, Delegate* delegate)
     91     : delegate_(delegate),
     92       url_(url),
     93       max_pending_send_allowed_(kMaxPendingSendAllowed),
     94       context_(NULL),
     95       next_state_(STATE_NONE),
     96       factory_(ClientSocketFactory::GetDefaultFactory()),
     97       proxy_mode_(kDirectConnection),
     98       proxy_url_(url),
     99       pac_request_(NULL),
    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))),
    106       read_buf_(NULL),
    107       current_write_buf_(NULL),
    108       waiting_for_write_completion_(false),
    109       closing_(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";
    116   DCHECK(delegate_);
    117 }
    118 
    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();
    124   return NULL;
    125 }
    126 
    127 void SocketStream::SetUserData(const void* key, UserData* data) {
    128   user_data_[key] = linked_ptr<UserData>(data);
    129 }
    130 
    131 bool SocketStream::is_secure() const {
    132   return url_.SchemeIs("wss");
    133 }
    134 
    135 void SocketStream::set_context(URLRequestContext* context) {
    136   const URLRequestContext* prev_context = context_;
    137 
    138   context_ = context;
    139 
    140   if (prev_context != context) {
    141     if (prev_context && pac_request_) {
    142       prev_context->proxy_service()->CancelPacRequest(pac_request_);
    143       pac_request_ = NULL;
    144     }
    145 
    146     net_log_.EndEvent(NetLog::TYPE_REQUEST_ALIVE);
    147     net_log_ = BoundNetLog();
    148 
    149     if (context) {
    150       net_log_ = BoundNetLog::Make(
    151           context->net_log(),
    152           NetLog::SOURCE_SOCKET_STREAM);
    153 
    154       net_log_.BeginEvent(NetLog::TYPE_REQUEST_ALIVE);
    155     }
    156   }
    157 }
    158 
    159 void SocketStream::CheckPrivacyMode() {
    160   if (context_ && context_->network_delegate()) {
    161     bool enable = context_->network_delegate()->CanEnablePrivacyMode(url_,
    162                                                                      url_);
    163     privacy_mode_ = enable ? kPrivacyModeEnabled : kPrivacyModeDisabled;
    164     // Disable Channel ID if privacy mode is enabled.
    165     if (enable)
    166       server_ssl_config_.channel_id_enabled = false;
    167   }
    168 }
    169 
    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";
    175   if (context_) {
    176     context_->ssl_config_service()->GetSSLConfig(&server_ssl_config_);
    177     proxy_ssl_config_ = server_ssl_config_;
    178   }
    179   CheckPrivacyMode();
    180 
    181   DCHECK_EQ(next_state_, STATE_NONE);
    182 
    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;
    187   net_log_.BeginEvent(
    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));
    192 }
    193 
    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();
    198        ++iter)
    199     total_size += (*iter)->size();
    200   return total_size;
    201 }
    202 
    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";
    208   DCHECK_GT(len, 0);
    209 
    210   if (!connection_->socket() ||
    211       !connection_->socket()->IsConnected() || next_state_ == STATE_NONE) {
    212     return false;
    213   }
    214 
    215   int total_buffered_bytes = len;
    216   if (current_write_buf_.get()) {
    217     // Since
    218     // - the purpose of this check is to limit the amount of buffer used by
    219     //   this instance.
    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();
    223   }
    224   total_buffered_bytes += GetTotalSizeOfPendingWriteBufs();
    225   if (total_buffered_bytes > max_pending_send_allowed_)
    226     return false;
    227 
    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);
    233 
    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));
    245   }
    246 
    247   return true;
    248 }
    249 
    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)
    260     return;
    261   base::MessageLoop::current()->PostTask(
    262       FROM_HERE, base::Bind(&SocketStream::DoClose, this));
    263 }
    264 
    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.";
    273     return;
    274   }
    275 
    276   proxy_auth_controller_->ResetAuth(credentials);
    277 
    278   base::MessageLoop::current()->PostTask(
    279       FROM_HERE, base::Bind(&SocketStream::DoRestartWithAuth, this));
    280 }
    281 
    282 void SocketStream::DetachDelegate() {
    283   if (!delegate_)
    284     return;
    285   delegate_ = NULL;
    286   // Prevent the rest of the function from executing if we are being called from
    287   // within Finish().
    288   if (next_state_ == STATE_NONE)
    289     return;
    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();
    293   Close();
    294 }
    295 
    296 const ProxyServer& SocketStream::proxy_server() const {
    297   return proxy_info_.proxy_server();
    298 }
    299 
    300 void SocketStream::SetClientSocketFactory(
    301     ClientSocketFactory* factory) {
    302   DCHECK(factory);
    303   factory_ = factory;
    304 }
    305 
    306 void SocketStream::CancelWithError(int error) {
    307   base::MessageLoop::current()->PostTask(
    308       FROM_HERE, base::Bind(&SocketStream::DoLoop, this, error));
    309 }
    310 
    311 void SocketStream::CancelWithSSLError(const SSLInfo& ssl_info) {
    312   CancelWithError(MapCertStatusToNetError(ssl_info.cert_status));
    313 }
    314 
    315 void SocketStream::ContinueDespiteError() {
    316   base::MessageLoop::current()->PostTask(
    317       FROM_HERE, base::Bind(&SocketStream::DoLoop, this, OK));
    318 }
    319 
    320 SocketStream::~SocketStream() {
    321   set_context(NULL);
    322   DCHECK(!delegate_);
    323   DCHECK(!pac_request_);
    324 }
    325 
    326 SocketStream::RequestHeaders::~RequestHeaders() { data_ = NULL; }
    327 
    328 void SocketStream::set_addresses(const AddressList& addresses) {
    329   addresses_ = addresses;
    330 }
    331 
    332 void SocketStream::DoClose() {
    333   closing_ = true;
    334   // If next_state_ is:
    335   // - STATE_TCP_CONNECT_COMPLETE, it's waiting other socket establishing
    336   //   connection.
    337   // - STATE_AUTH_REQUIRED, it's waiting for restarting.
    338   // - STATE_RESOLVE_PROTOCOL_COMPLETE, it's waiting for delegate_ to finish
    339   //   OnStartOpenConnection method call
    340   // In these states, we'll close the SocketStream now.
    341   if (next_state_ == STATE_TCP_CONNECT_COMPLETE ||
    342       next_state_ == STATE_AUTH_REQUIRED ||
    343       next_state_ == STATE_RESOLVE_PROTOCOL_COMPLETE) {
    344     DoLoop(ERR_ABORTED);
    345     return;
    346   }
    347   // If next_state_ is STATE_READ_WRITE, we'll run DoLoop and close
    348   // the SocketStream.
    349   // If it's writing now, we should defer the closing after the current
    350   // writing is completed.
    351   if (next_state_ == STATE_READ_WRITE && !current_write_buf_.get())
    352     DoLoop(ERR_ABORTED);
    353 
    354   // In other next_state_, we'll wait for callback of other APIs, such as
    355   // ResolveProxy().
    356 }
    357 
    358 void SocketStream::Finish(int result) {
    359   DCHECK(base::MessageLoop::current())
    360       << "The current base::MessageLoop must exist";
    361   DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type())
    362       << "The current base::MessageLoop must be TYPE_IO";
    363   DCHECK_LE(result, OK);
    364   if (result == OK)
    365     result = ERR_CONNECTION_CLOSED;
    366   DCHECK_EQ(next_state_, STATE_NONE);
    367   DVLOG(1) << "Finish result=" << ErrorToString(result);
    368 
    369   metrics_->OnClose();
    370 
    371   if (result != ERR_CONNECTION_CLOSED && delegate_)
    372     delegate_->OnError(this, result);
    373   if (result != ERR_PROTOCOL_SWITCHED && delegate_)
    374     delegate_->OnClose(this);
    375   delegate_ = NULL;
    376 
    377   Release();
    378 }
    379 
    380 int SocketStream::DidEstablishConnection() {
    381   if (!connection_->socket() || !connection_->socket()->IsConnected()) {
    382     next_state_ = STATE_CLOSE;
    383     return ERR_CONNECTION_FAILED;
    384   }
    385   next_state_ = STATE_READ_WRITE;
    386   metrics_->OnConnected();
    387 
    388   net_log_.EndEvent(NetLog::TYPE_SOCKET_STREAM_CONNECT);
    389   if (delegate_)
    390     delegate_->OnConnected(this, max_pending_send_allowed_);
    391 
    392   return OK;
    393 }
    394 
    395 int SocketStream::DidReceiveData(int result) {
    396   DCHECK(read_buf_.get());
    397   DCHECK_GT(result, 0);
    398   net_log_.AddEvent(NetLog::TYPE_SOCKET_STREAM_RECEIVED);
    399   int len = result;
    400   metrics_->OnRead(len);
    401   if (delegate_) {
    402     // Notify recevied data to delegate.
    403     delegate_->OnReceivedData(this, read_buf_->data(), len);
    404   }
    405   read_buf_ = NULL;
    406   return OK;
    407 }
    408 
    409 void SocketStream::DidSendData(int result) {
    410   DCHECK_GT(result, 0);
    411   DCHECK(current_write_buf_.get());
    412   net_log_.AddEvent(NetLog::TYPE_SOCKET_STREAM_SENT);
    413 
    414   int bytes_sent = result;
    415 
    416   metrics_->OnWrite(bytes_sent);
    417 
    418   current_write_buf_->DidConsume(result);
    419 
    420   if (current_write_buf_->BytesRemaining())
    421     return;
    422 
    423   size_t bytes_freed = current_write_buf_->size();
    424 
    425   current_write_buf_ = NULL;
    426 
    427   // We freed current_write_buf_ and this instance is now able to accept more
    428   // data via SendData() (note that DidConsume() doesn't free consumed memory).
    429   // We can tell that to delegate_ by calling OnSentData().
    430   if (delegate_)
    431     delegate_->OnSentData(this, bytes_freed);
    432 }
    433 
    434 void SocketStream::OnIOCompleted(int result) {
    435   DoLoop(result);
    436 }
    437 
    438 void SocketStream::OnReadCompleted(int result) {
    439   if (result == 0) {
    440     // 0 indicates end-of-file, so socket was closed.
    441     // Don't close the socket if it's still writing.
    442     server_closed_ = true;
    443   } else if (result > 0 && read_buf_.get()) {
    444     result = DidReceiveData(result);
    445   }
    446   DoLoop(result);
    447 }
    448 
    449 void SocketStream::OnWriteCompleted(int result) {
    450   waiting_for_write_completion_ = false;
    451   if (result > 0) {
    452     DidSendData(result);
    453     result = OK;
    454   }
    455   DoLoop(result);
    456 }
    457 
    458 void SocketStream::DoLoop(int result) {
    459   if (next_state_ == STATE_NONE)
    460     return;
    461 
    462   // If context was not set, close immediately.
    463   if (!context_)
    464     next_state_ = STATE_CLOSE;
    465 
    466   do {
    467     State state = next_state_;
    468     next_state_ = STATE_NONE;
    469     switch (state) {
    470       case STATE_BEFORE_CONNECT:
    471         DCHECK_EQ(OK, result);
    472         result = DoBeforeConnect();
    473         break;
    474       case STATE_BEFORE_CONNECT_COMPLETE:
    475         result = DoBeforeConnectComplete(result);
    476         break;
    477       case STATE_RESOLVE_PROXY:
    478         DCHECK_EQ(OK, result);
    479         result = DoResolveProxy();
    480         break;
    481       case STATE_RESOLVE_PROXY_COMPLETE:
    482         result = DoResolveProxyComplete(result);
    483         break;
    484       case STATE_RESOLVE_HOST:
    485         DCHECK_EQ(OK, result);
    486         result = DoResolveHost();
    487         break;
    488       case STATE_RESOLVE_HOST_COMPLETE:
    489         result = DoResolveHostComplete(result);
    490         break;
    491       case STATE_RESOLVE_PROTOCOL:
    492         result = DoResolveProtocol(result);
    493         break;
    494       case STATE_RESOLVE_PROTOCOL_COMPLETE:
    495         result = DoResolveProtocolComplete(result);
    496         break;
    497       case STATE_TCP_CONNECT:
    498         result = DoTcpConnect(result);
    499         break;
    500       case STATE_TCP_CONNECT_COMPLETE:
    501         result = DoTcpConnectComplete(result);
    502         break;
    503       case STATE_GENERATE_PROXY_AUTH_TOKEN:
    504         result = DoGenerateProxyAuthToken();
    505         break;
    506       case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
    507         result = DoGenerateProxyAuthTokenComplete(result);
    508         break;
    509       case STATE_WRITE_TUNNEL_HEADERS:
    510         DCHECK_EQ(OK, result);
    511         result = DoWriteTunnelHeaders();
    512         break;
    513       case STATE_WRITE_TUNNEL_HEADERS_COMPLETE:
    514         result = DoWriteTunnelHeadersComplete(result);
    515         break;
    516       case STATE_READ_TUNNEL_HEADERS:
    517         DCHECK_EQ(OK, result);
    518         result = DoReadTunnelHeaders();
    519         break;
    520       case STATE_READ_TUNNEL_HEADERS_COMPLETE:
    521         result = DoReadTunnelHeadersComplete(result);
    522         break;
    523       case STATE_SOCKS_CONNECT:
    524         DCHECK_EQ(OK, result);
    525         result = DoSOCKSConnect();
    526         break;
    527       case STATE_SOCKS_CONNECT_COMPLETE:
    528         result = DoSOCKSConnectComplete(result);
    529         break;
    530       case STATE_SECURE_PROXY_CONNECT:
    531         DCHECK_EQ(OK, result);
    532         result = DoSecureProxyConnect();
    533         break;
    534       case STATE_SECURE_PROXY_CONNECT_COMPLETE:
    535         result = DoSecureProxyConnectComplete(result);
    536         break;
    537       case STATE_SECURE_PROXY_HANDLE_CERT_ERROR:
    538         result = DoSecureProxyHandleCertError(result);
    539         break;
    540       case STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE:
    541         result = DoSecureProxyHandleCertErrorComplete(result);
    542         break;
    543       case STATE_SSL_CONNECT:
    544         DCHECK_EQ(OK, result);
    545         result = DoSSLConnect();
    546         break;
    547       case STATE_SSL_CONNECT_COMPLETE:
    548         result = DoSSLConnectComplete(result);
    549         break;
    550       case STATE_SSL_HANDLE_CERT_ERROR:
    551         result = DoSSLHandleCertError(result);
    552         break;
    553       case STATE_SSL_HANDLE_CERT_ERROR_COMPLETE:
    554         result = DoSSLHandleCertErrorComplete(result);
    555         break;
    556       case STATE_READ_WRITE:
    557         result = DoReadWrite(result);
    558         break;
    559       case STATE_AUTH_REQUIRED:
    560         // It might be called when DoClose is called while waiting in
    561         // STATE_AUTH_REQUIRED.
    562         Finish(result);
    563         return;
    564       case STATE_CLOSE:
    565         DCHECK_LE(result, OK);
    566         Finish(result);
    567         return;
    568       default:
    569         NOTREACHED() << "bad state " << state;
    570         Finish(result);
    571         return;
    572     }
    573     if (state == STATE_RESOLVE_PROTOCOL && result == ERR_PROTOCOL_SWITCHED)
    574       continue;
    575     // If the connection is not established yet and had actual errors,
    576     // record the error.  In next iteration, it will close the connection.
    577     if (state != STATE_READ_WRITE && result < ERR_IO_PENDING) {
    578       net_log_.EndEventWithNetErrorCode(
    579           NetLog::TYPE_SOCKET_STREAM_CONNECT, result);
    580     }
    581   } while (result != ERR_IO_PENDING);
    582 }
    583 
    584 int SocketStream::DoBeforeConnect() {
    585   next_state_ = STATE_BEFORE_CONNECT_COMPLETE;
    586   if (!context_ || !context_->network_delegate())
    587     return OK;
    588 
    589   int result = context_->network_delegate()->NotifyBeforeSocketStreamConnect(
    590       this, io_callback_);
    591   if (result != OK && result != ERR_IO_PENDING)
    592     next_state_ = STATE_CLOSE;
    593 
    594   return result;
    595 }
    596 
    597 int SocketStream::DoBeforeConnectComplete(int result) {
    598   DCHECK_NE(ERR_IO_PENDING, result);
    599 
    600   if (result == OK)
    601     next_state_ = STATE_RESOLVE_PROXY;
    602   else
    603     next_state_ = STATE_CLOSE;
    604 
    605   return result;
    606 }
    607 
    608 int SocketStream::DoResolveProxy() {
    609   DCHECK(context_);
    610   DCHECK(!pac_request_);
    611   next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
    612 
    613   if (!proxy_url_.is_valid()) {
    614     next_state_ = STATE_CLOSE;
    615     return ERR_INVALID_ARGUMENT;
    616   }
    617 
    618   // TODO(toyoshim): Check server advertisement of SPDY through the HTTP
    619   // Alternate-Protocol header, then switch to SPDY if SPDY is available.
    620   // Usually we already have a session to the SPDY server because JavaScript
    621   // running WebSocket itself would be served by SPDY. But, in some situation
    622   // (E.g. Used by Chrome Extensions or used for cross origin connection), this
    623   // connection might be the first one. At that time, we should check
    624   // Alternate-Protocol header here for ws:// or TLS NPN extension for wss:// .
    625 
    626   return context_->proxy_service()->ResolveProxy(
    627       proxy_url_, &proxy_info_, io_callback_, &pac_request_, net_log_);
    628 }
    629 
    630 int SocketStream::DoResolveProxyComplete(int result) {
    631   pac_request_ = NULL;
    632   if (result != OK) {
    633     DVLOG(1) << "Failed to resolve proxy: " << result;
    634     if (delegate_)
    635       delegate_->OnError(this, result);
    636     proxy_info_.UseDirect();
    637   }
    638   if (proxy_info_.is_direct()) {
    639     // If proxy was not found for original URL (i.e. websocket URL),
    640     // try again with https URL, like Safari implementation.
    641     // Note that we don't want to use http proxy, because we'll use tunnel
    642     // proxy using CONNECT method, which is used by https proxy.
    643     if (!proxy_url_.SchemeIs("https")) {
    644       const std::string scheme = "https";
    645       GURL::Replacements repl;
    646       repl.SetSchemeStr(scheme);
    647       proxy_url_ = url_.ReplaceComponents(repl);
    648       DVLOG(1) << "Try https proxy: " << proxy_url_;
    649       next_state_ = STATE_RESOLVE_PROXY;
    650       return OK;
    651     }
    652   }
    653 
    654   if (proxy_info_.is_empty()) {
    655     // No proxies/direct to choose from. This happens when we don't support any
    656     // of the proxies in the returned list.
    657     return ERR_NO_SUPPORTED_PROXIES;
    658   }
    659 
    660   next_state_ = STATE_RESOLVE_HOST;
    661   return OK;
    662 }
    663 
    664 int SocketStream::DoResolveHost() {
    665   next_state_ = STATE_RESOLVE_HOST_COMPLETE;
    666 
    667   DCHECK(!proxy_info_.is_empty());
    668   if (proxy_info_.is_direct())
    669     proxy_mode_ = kDirectConnection;
    670   else if (proxy_info_.proxy_server().is_socks())
    671     proxy_mode_ = kSOCKSProxy;
    672   else
    673     proxy_mode_ = kTunnelProxy;
    674 
    675   // Determine the host and port to connect to.
    676   HostPortPair host_port_pair;
    677   if (proxy_mode_ != kDirectConnection) {
    678     host_port_pair = proxy_info_.proxy_server().host_port_pair();
    679   } else {
    680     host_port_pair = HostPortPair::FromURL(url_);
    681   }
    682 
    683   HostResolver::RequestInfo resolve_info(host_port_pair);
    684 
    685   DCHECK(context_->host_resolver());
    686   resolver_.reset(new SingleRequestHostResolver(context_->host_resolver()));
    687   return resolver_->Resolve(resolve_info,
    688                             DEFAULT_PRIORITY,
    689                             &addresses_,
    690                             base::Bind(&SocketStream::OnIOCompleted, this),
    691                             net_log_);
    692 }
    693 
    694 int SocketStream::DoResolveHostComplete(int result) {
    695   if (result == OK)
    696     next_state_ = STATE_RESOLVE_PROTOCOL;
    697   else
    698     next_state_ = STATE_CLOSE;
    699   // TODO(ukai): if error occured, reconsider proxy after error.
    700   return result;
    701 }
    702 
    703 int SocketStream::DoResolveProtocol(int result) {
    704   DCHECK_EQ(OK, result);
    705 
    706   if (!delegate_) {
    707     next_state_ = STATE_CLOSE;
    708     return result;
    709   }
    710 
    711   next_state_ = STATE_RESOLVE_PROTOCOL_COMPLETE;
    712   result = delegate_->OnStartOpenConnection(this, io_callback_);
    713   if (result == ERR_IO_PENDING)
    714     metrics_->OnWaitConnection();
    715   else if (result != OK && result != ERR_PROTOCOL_SWITCHED)
    716     next_state_ = STATE_CLOSE;
    717   return result;
    718 }
    719 
    720 int SocketStream::DoResolveProtocolComplete(int result) {
    721   DCHECK_NE(ERR_IO_PENDING, result);
    722 
    723   if (result == ERR_PROTOCOL_SWITCHED) {
    724     next_state_ = STATE_CLOSE;
    725     metrics_->OnCountWireProtocolType(
    726         SocketStreamMetrics::WIRE_PROTOCOL_SPDY);
    727   } else if (result == OK) {
    728     next_state_ = STATE_TCP_CONNECT;
    729     metrics_->OnCountWireProtocolType(
    730         SocketStreamMetrics::WIRE_PROTOCOL_WEBSOCKET);
    731   } else {
    732     next_state_ = STATE_CLOSE;
    733   }
    734   return result;
    735 }
    736 
    737 int SocketStream::DoTcpConnect(int result) {
    738   if (result != OK) {
    739     next_state_ = STATE_CLOSE;
    740     return result;
    741   }
    742   next_state_ = STATE_TCP_CONNECT_COMPLETE;
    743   DCHECK(factory_);
    744   connection_->SetSocket(
    745       factory_->CreateTransportClientSocket(addresses_,
    746                                             net_log_.net_log(),
    747                                             net_log_.source()));
    748   metrics_->OnStartConnection();
    749   return connection_->socket()->Connect(io_callback_);
    750 }
    751 
    752 int SocketStream::DoTcpConnectComplete(int result) {
    753   // TODO(ukai): if error occured, reconsider proxy after error.
    754   if (result != OK) {
    755     next_state_ = STATE_CLOSE;
    756     return result;
    757   }
    758 
    759   if (proxy_mode_ == kTunnelProxy) {
    760     if (proxy_info_.is_https())
    761       next_state_ = STATE_SECURE_PROXY_CONNECT;
    762     else
    763       next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
    764   } else if (proxy_mode_ == kSOCKSProxy) {
    765     next_state_ = STATE_SOCKS_CONNECT;
    766   } else if (is_secure()) {
    767     next_state_ = STATE_SSL_CONNECT;
    768   } else {
    769     result = DidEstablishConnection();
    770   }
    771   return result;
    772 }
    773 
    774 int SocketStream::DoGenerateProxyAuthToken() {
    775   next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE;
    776   if (!proxy_auth_controller_.get()) {
    777     DCHECK(context_);
    778     DCHECK(context_->http_transaction_factory());
    779     DCHECK(context_->http_transaction_factory()->GetSession());
    780     HttpNetworkSession* session =
    781         context_->http_transaction_factory()->GetSession();
    782     const char* scheme = proxy_info_.is_https() ? "https://" : "http://";
    783     GURL auth_url(scheme +
    784                   proxy_info_.proxy_server().host_port_pair().ToString());
    785     proxy_auth_controller_ =
    786         new HttpAuthController(HttpAuth::AUTH_PROXY,
    787                                auth_url,
    788                                session->http_auth_cache(),
    789                                session->http_auth_handler_factory());
    790   }
    791   HttpRequestInfo request_info;
    792   request_info.url = url_;
    793   request_info.method = "CONNECT";
    794   return proxy_auth_controller_->MaybeGenerateAuthToken(
    795       &request_info, io_callback_, net_log_);
    796 }
    797 
    798 int SocketStream::DoGenerateProxyAuthTokenComplete(int result) {
    799   if (result != OK) {
    800     next_state_ = STATE_CLOSE;
    801     return result;
    802   }
    803 
    804   next_state_ = STATE_WRITE_TUNNEL_HEADERS;
    805   return result;
    806 }
    807 
    808 int SocketStream::DoWriteTunnelHeaders() {
    809   DCHECK_EQ(kTunnelProxy, proxy_mode_);
    810 
    811   next_state_ = STATE_WRITE_TUNNEL_HEADERS_COMPLETE;
    812 
    813   if (!tunnel_request_headers_.get()) {
    814     metrics_->OnCountConnectionType(SocketStreamMetrics::TUNNEL_CONNECTION);
    815     tunnel_request_headers_ = new RequestHeaders();
    816     tunnel_request_headers_bytes_sent_ = 0;
    817   }
    818   if (tunnel_request_headers_->headers_.empty()) {
    819     HttpRequestHeaders request_headers;
    820     request_headers.SetHeader("Host", GetHostAndOptionalPort(url_));
    821     request_headers.SetHeader("Proxy-Connection", "keep-alive");
    822     if (proxy_auth_controller_.get() && proxy_auth_controller_->HaveAuth())
    823       proxy_auth_controller_->AddAuthorizationHeader(&request_headers);
    824     tunnel_request_headers_->headers_ = base::StringPrintf(
    825         "CONNECT %s HTTP/1.1\r\n"
    826         "%s",
    827         GetHostAndPort(url_).c_str(),
    828         request_headers.ToString().c_str());
    829   }
    830   tunnel_request_headers_->SetDataOffset(tunnel_request_headers_bytes_sent_);
    831   int buf_len = static_cast<int>(tunnel_request_headers_->headers_.size() -
    832                                  tunnel_request_headers_bytes_sent_);
    833   DCHECK_GT(buf_len, 0);
    834   return connection_->socket()->Write(
    835       tunnel_request_headers_.get(), buf_len, io_callback_);
    836 }
    837 
    838 int SocketStream::DoWriteTunnelHeadersComplete(int result) {
    839   DCHECK_EQ(kTunnelProxy, proxy_mode_);
    840 
    841   if (result < 0) {
    842     next_state_ = STATE_CLOSE;
    843     return result;
    844   }
    845 
    846   tunnel_request_headers_bytes_sent_ += result;
    847   if (tunnel_request_headers_bytes_sent_ <
    848       tunnel_request_headers_->headers_.size()) {
    849     next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
    850   } else {
    851     // Handling a cert error or a client cert request requires reconnection.
    852     // DoWriteTunnelHeaders() will be called again.
    853     // Thus |tunnel_request_headers_bytes_sent_| should be reset to 0 for
    854     // sending |tunnel_request_headers_| correctly.
    855     tunnel_request_headers_bytes_sent_ = 0;
    856     next_state_ = STATE_READ_TUNNEL_HEADERS;
    857   }
    858   return OK;
    859 }
    860 
    861 int SocketStream::DoReadTunnelHeaders() {
    862   DCHECK_EQ(kTunnelProxy, proxy_mode_);
    863 
    864   next_state_ = STATE_READ_TUNNEL_HEADERS_COMPLETE;
    865 
    866   if (!tunnel_response_headers_.get()) {
    867     tunnel_response_headers_ = new ResponseHeaders();
    868     tunnel_response_headers_capacity_ = kMaxTunnelResponseHeadersSize;
    869     tunnel_response_headers_->Realloc(tunnel_response_headers_capacity_);
    870     tunnel_response_headers_len_ = 0;
    871   }
    872 
    873   int buf_len = tunnel_response_headers_capacity_ -
    874       tunnel_response_headers_len_;
    875   tunnel_response_headers_->SetDataOffset(tunnel_response_headers_len_);
    876   CHECK(tunnel_response_headers_->data());
    877 
    878   return connection_->socket()->Read(
    879       tunnel_response_headers_.get(), buf_len, io_callback_);
    880 }
    881 
    882 int SocketStream::DoReadTunnelHeadersComplete(int result) {
    883   DCHECK_EQ(kTunnelProxy, proxy_mode_);
    884 
    885   if (result < 0) {
    886     next_state_ = STATE_CLOSE;
    887     return result;
    888   }
    889 
    890   if (result == 0) {
    891     // 0 indicates end-of-file, so socket was closed.
    892     next_state_ = STATE_CLOSE;
    893     return ERR_CONNECTION_CLOSED;
    894   }
    895 
    896   tunnel_response_headers_len_ += result;
    897   DCHECK(tunnel_response_headers_len_ <= tunnel_response_headers_capacity_);
    898 
    899   int eoh = HttpUtil::LocateEndOfHeaders(
    900       tunnel_response_headers_->headers(), tunnel_response_headers_len_, 0);
    901   if (eoh == -1) {
    902     if (tunnel_response_headers_len_ >= kMaxTunnelResponseHeadersSize) {
    903       next_state_ = STATE_CLOSE;
    904       return ERR_RESPONSE_HEADERS_TOO_BIG;
    905     }
    906 
    907     next_state_ = STATE_READ_TUNNEL_HEADERS;
    908     return OK;
    909   }
    910   // DidReadResponseHeaders
    911   scoped_refptr<HttpResponseHeaders> headers;
    912   headers = new HttpResponseHeaders(
    913       HttpUtil::AssembleRawHeaders(tunnel_response_headers_->headers(), eoh));
    914   if (headers->GetParsedHttpVersion() < HttpVersion(1, 0)) {
    915     // Require the "HTTP/1.x" status line.
    916     next_state_ = STATE_CLOSE;
    917     return ERR_TUNNEL_CONNECTION_FAILED;
    918   }
    919   switch (headers->response_code()) {
    920     case 200:  // OK
    921       if (is_secure()) {
    922         DCHECK_EQ(eoh, tunnel_response_headers_len_);
    923         next_state_ = STATE_SSL_CONNECT;
    924       } else {
    925         result = DidEstablishConnection();
    926         if (result < 0) {
    927           next_state_ = STATE_CLOSE;
    928           return result;
    929         }
    930         if ((eoh < tunnel_response_headers_len_) && delegate_)
    931           delegate_->OnReceivedData(
    932               this, tunnel_response_headers_->headers() + eoh,
    933               tunnel_response_headers_len_ - eoh);
    934       }
    935       return OK;
    936     case 407:  // Proxy Authentication Required.
    937       if (proxy_mode_ != kTunnelProxy)
    938         return ERR_UNEXPECTED_PROXY_AUTH;
    939 
    940       result = proxy_auth_controller_->HandleAuthChallenge(
    941           headers, false, true, net_log_);
    942       if (result != OK)
    943         return result;
    944       DCHECK(!proxy_info_.is_empty());
    945       next_state_ = STATE_AUTH_REQUIRED;
    946       if (proxy_auth_controller_->HaveAuth()) {
    947         base::MessageLoop::current()->PostTask(
    948             FROM_HERE, base::Bind(&SocketStream::DoRestartWithAuth, this));
    949         return ERR_IO_PENDING;
    950       }
    951       if (delegate_) {
    952         // Wait until RestartWithAuth or Close is called.
    953         base::MessageLoop::current()->PostTask(
    954             FROM_HERE, base::Bind(&SocketStream::DoAuthRequired, this));
    955         return ERR_IO_PENDING;
    956       }
    957       break;
    958     default:
    959       break;
    960   }
    961   next_state_ = STATE_CLOSE;
    962   return ERR_TUNNEL_CONNECTION_FAILED;
    963 }
    964 
    965 int SocketStream::DoSOCKSConnect() {
    966   DCHECK_EQ(kSOCKSProxy, proxy_mode_);
    967 
    968   next_state_ = STATE_SOCKS_CONNECT_COMPLETE;
    969 
    970   HostResolver::RequestInfo req_info(HostPortPair::FromURL(url_));
    971 
    972   DCHECK(!proxy_info_.is_empty());
    973   scoped_ptr<StreamSocket> s;
    974   if (proxy_info_.proxy_server().scheme() == ProxyServer::SCHEME_SOCKS5) {
    975     s.reset(new SOCKS5ClientSocket(connection_.Pass(), req_info));
    976   } else {
    977     s.reset(new SOCKSClientSocket(connection_.Pass(),
    978                                   req_info,
    979                                   DEFAULT_PRIORITY,
    980                                   context_->host_resolver()));
    981   }
    982   connection_.reset(new ClientSocketHandle);
    983   connection_->SetSocket(s.Pass());
    984   metrics_->OnCountConnectionType(SocketStreamMetrics::SOCKS_CONNECTION);
    985   return connection_->socket()->Connect(io_callback_);
    986 }
    987 
    988 int SocketStream::DoSOCKSConnectComplete(int result) {
    989   DCHECK_EQ(kSOCKSProxy, proxy_mode_);
    990 
    991   if (result == OK) {
    992     if (is_secure())
    993       next_state_ = STATE_SSL_CONNECT;
    994     else
    995       result = DidEstablishConnection();
    996   } else {
    997     next_state_ = STATE_CLOSE;
    998   }
    999   return result;
   1000 }
   1001 
   1002 int SocketStream::DoSecureProxyConnect() {
   1003   DCHECK(factory_);
   1004   SSLClientSocketContext ssl_context;
   1005   ssl_context.cert_verifier = context_->cert_verifier();
   1006   ssl_context.transport_security_state = context_->transport_security_state();
   1007   ssl_context.server_bound_cert_service = context_->server_bound_cert_service();
   1008   scoped_ptr<StreamSocket> socket(factory_->CreateSSLClientSocket(
   1009       connection_.Pass(),
   1010       proxy_info_.proxy_server().host_port_pair(),
   1011       proxy_ssl_config_,
   1012       ssl_context));
   1013   connection_.reset(new ClientSocketHandle);
   1014   connection_->SetSocket(socket.Pass());
   1015   next_state_ = STATE_SECURE_PROXY_CONNECT_COMPLETE;
   1016   metrics_->OnCountConnectionType(SocketStreamMetrics::SECURE_PROXY_CONNECTION);
   1017   return connection_->socket()->Connect(io_callback_);
   1018 }
   1019 
   1020 int SocketStream::DoSecureProxyConnectComplete(int result) {
   1021   DCHECK_EQ(STATE_NONE, next_state_);
   1022   // Reconnect with client authentication.
   1023   if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED)
   1024     return HandleCertificateRequest(result, &proxy_ssl_config_);
   1025 
   1026   if (IsCertificateError(result))
   1027     next_state_ = STATE_SECURE_PROXY_HANDLE_CERT_ERROR;
   1028   else if (result == OK)
   1029     next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
   1030   else
   1031     next_state_ = STATE_CLOSE;
   1032   return result;
   1033 }
   1034 
   1035 int SocketStream::DoSecureProxyHandleCertError(int result) {
   1036   DCHECK_EQ(STATE_NONE, next_state_);
   1037   DCHECK(IsCertificateError(result));
   1038   result = HandleCertificateError(result);
   1039   if (result == ERR_IO_PENDING)
   1040     next_state_ = STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE;
   1041   else
   1042     next_state_ = STATE_CLOSE;
   1043   return result;
   1044 }
   1045 
   1046 int SocketStream::DoSecureProxyHandleCertErrorComplete(int result) {
   1047   DCHECK_EQ(STATE_NONE, next_state_);
   1048   if (result == OK) {
   1049     if (!connection_->socket()->IsConnectedAndIdle())
   1050       return AllowCertErrorForReconnection(&proxy_ssl_config_);
   1051     next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
   1052   } else {
   1053     next_state_ = STATE_CLOSE;
   1054   }
   1055   return result;
   1056 }
   1057 
   1058 int SocketStream::DoSSLConnect() {
   1059   DCHECK(factory_);
   1060   SSLClientSocketContext ssl_context;
   1061   ssl_context.cert_verifier = context_->cert_verifier();
   1062   ssl_context.transport_security_state = context_->transport_security_state();
   1063   ssl_context.server_bound_cert_service = context_->server_bound_cert_service();
   1064   scoped_ptr<StreamSocket> socket(
   1065       factory_->CreateSSLClientSocket(connection_.Pass(),
   1066                                       HostPortPair::FromURL(url_),
   1067                                       server_ssl_config_,
   1068                                       ssl_context));
   1069   connection_.reset(new ClientSocketHandle);
   1070   connection_->SetSocket(socket.Pass());
   1071   next_state_ = STATE_SSL_CONNECT_COMPLETE;
   1072   metrics_->OnCountConnectionType(SocketStreamMetrics::SSL_CONNECTION);
   1073   return connection_->socket()->Connect(io_callback_);
   1074 }
   1075 
   1076 int SocketStream::DoSSLConnectComplete(int result) {
   1077   DCHECK_EQ(STATE_NONE, next_state_);
   1078   // Reconnect with client authentication.
   1079   if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED)
   1080     return HandleCertificateRequest(result, &server_ssl_config_);
   1081 
   1082   if (IsCertificateError(result))
   1083     next_state_ = STATE_SSL_HANDLE_CERT_ERROR;
   1084   else if (result == OK)
   1085     result = DidEstablishConnection();
   1086   else
   1087     next_state_ = STATE_CLOSE;
   1088   return result;
   1089 }
   1090 
   1091 int SocketStream::DoSSLHandleCertError(int result) {
   1092   DCHECK_EQ(STATE_NONE, next_state_);
   1093   DCHECK(IsCertificateError(result));
   1094   result = HandleCertificateError(result);
   1095   if (result == OK || result == ERR_IO_PENDING)
   1096     next_state_ = STATE_SSL_HANDLE_CERT_ERROR_COMPLETE;
   1097   else
   1098     next_state_ = STATE_CLOSE;
   1099   return result;
   1100 }
   1101 
   1102 int SocketStream::DoSSLHandleCertErrorComplete(int result) {
   1103   DCHECK_EQ(STATE_NONE, next_state_);
   1104   // TODO(toyoshim): Upgrade to SPDY through TLS NPN extension if possible.
   1105   // If we use HTTPS and this is the first connection to the SPDY server,
   1106   // we should take care of TLS NPN extension here.
   1107 
   1108   if (result == OK) {
   1109     if (!connection_->socket()->IsConnectedAndIdle())
   1110       return AllowCertErrorForReconnection(&server_ssl_config_);
   1111     result = DidEstablishConnection();
   1112   } else {
   1113     next_state_ = STATE_CLOSE;
   1114   }
   1115   return result;
   1116 }
   1117 
   1118 int SocketStream::DoReadWrite(int result) {
   1119   if (result < OK) {
   1120     next_state_ = STATE_CLOSE;
   1121     return result;
   1122   }
   1123   if (!connection_->socket() || !connection_->socket()->IsConnected()) {
   1124     next_state_ = STATE_CLOSE;
   1125     return ERR_CONNECTION_CLOSED;
   1126   }
   1127 
   1128   // If client has requested close(), and there's nothing to write, then
   1129   // let's close the socket.
   1130   // We don't care about receiving data after the socket is closed.
   1131   if (closing_ && !current_write_buf_.get() && pending_write_bufs_.empty()) {
   1132     connection_->socket()->Disconnect();
   1133     next_state_ = STATE_CLOSE;
   1134     return OK;
   1135   }
   1136 
   1137   next_state_ = STATE_READ_WRITE;
   1138 
   1139   // If server already closed the socket, we don't try to read.
   1140   if (!server_closed_) {
   1141     if (!read_buf_.get()) {
   1142       // No read pending and server didn't close the socket.
   1143       read_buf_ = new IOBuffer(kReadBufferSize);
   1144       result = connection_->socket()->Read(
   1145           read_buf_.get(),
   1146           kReadBufferSize,
   1147           base::Bind(&SocketStream::OnReadCompleted, base::Unretained(this)));
   1148       if (result > 0) {
   1149         return DidReceiveData(result);
   1150       } else if (result == 0) {
   1151         // 0 indicates end-of-file, so socket was closed.
   1152         next_state_ = STATE_CLOSE;
   1153         server_closed_ = true;
   1154         return ERR_CONNECTION_CLOSED;
   1155       }
   1156       // If read is pending, try write as well.
   1157       // Otherwise, return the result and do next loop (to close the
   1158       // connection).
   1159       if (result != ERR_IO_PENDING) {
   1160         next_state_ = STATE_CLOSE;
   1161         server_closed_ = true;
   1162         return result;
   1163       }
   1164     }
   1165     // Read is pending.
   1166     DCHECK(read_buf_.get());
   1167   }
   1168 
   1169   if (waiting_for_write_completion_)
   1170     return ERR_IO_PENDING;
   1171 
   1172   if (!current_write_buf_.get()) {
   1173     if (pending_write_bufs_.empty()) {
   1174       // Nothing buffered for send.
   1175       return ERR_IO_PENDING;
   1176     }
   1177 
   1178     current_write_buf_ = new DrainableIOBuffer(
   1179         pending_write_bufs_.front().get(), pending_write_bufs_.front()->size());
   1180     pending_write_bufs_.pop_front();
   1181   }
   1182 
   1183   result = connection_->socket()->Write(
   1184       current_write_buf_.get(),
   1185       current_write_buf_->BytesRemaining(),
   1186       base::Bind(&SocketStream::OnWriteCompleted, base::Unretained(this)));
   1187 
   1188   if (result == ERR_IO_PENDING) {
   1189     waiting_for_write_completion_ = true;
   1190   } else if (result < 0) {
   1191     // Shortcut. Enter STATE_CLOSE now by changing next_state_ here than by
   1192     // calling DoReadWrite() again with the error code.
   1193     next_state_ = STATE_CLOSE;
   1194   } else if (result > 0) {
   1195     // Write is not pending. Return OK and do next loop.
   1196     DidSendData(result);
   1197     result = OK;
   1198   }
   1199 
   1200   return result;
   1201 }
   1202 
   1203 GURL SocketStream::ProxyAuthOrigin() const {
   1204   DCHECK(!proxy_info_.is_empty());
   1205   return GURL("http://" +
   1206               proxy_info_.proxy_server().host_port_pair().ToString());
   1207 }
   1208 
   1209 int SocketStream::HandleCertificateRequest(int result, SSLConfig* ssl_config) {
   1210   if (ssl_config->send_client_cert) {
   1211     // We already have performed SSL client authentication once and failed.
   1212     return result;
   1213   }
   1214 
   1215   DCHECK(connection_->socket());
   1216   scoped_refptr<SSLCertRequestInfo> cert_request_info = new SSLCertRequestInfo;
   1217   SSLClientSocket* ssl_socket =
   1218       static_cast<SSLClientSocket*>(connection_->socket());
   1219   ssl_socket->GetSSLCertRequestInfo(cert_request_info.get());
   1220 
   1221   HttpTransactionFactory* factory = context_->http_transaction_factory();
   1222   if (!factory)
   1223     return result;
   1224   scoped_refptr<HttpNetworkSession> session = factory->GetSession();
   1225   if (!session.get())
   1226     return result;
   1227 
   1228   // If the user selected one of the certificates in client_certs or declined
   1229   // to provide one for this server before, use the past decision
   1230   // automatically.
   1231   scoped_refptr<X509Certificate> client_cert;
   1232   if (!session->ssl_client_auth_cache()->Lookup(
   1233           cert_request_info->host_and_port, &client_cert)) {
   1234     return result;
   1235   }
   1236 
   1237   // Note: |client_cert| may be NULL, indicating that the caller
   1238   // wishes to proceed anonymously (eg: continue the handshake
   1239   // without sending a client cert)
   1240   //
   1241   // Check that the certificate selected is still a certificate the server
   1242   // is likely to accept, based on the criteria supplied in the
   1243   // CertificateRequest message.
   1244   const std::vector<std::string>& cert_authorities =
   1245       cert_request_info->cert_authorities;
   1246   if (client_cert.get() && !cert_authorities.empty() &&
   1247       !client_cert->IsIssuedByEncoded(cert_authorities)) {
   1248     return result;
   1249   }
   1250 
   1251   ssl_config->send_client_cert = true;
   1252   ssl_config->client_cert = client_cert;
   1253   next_state_ = STATE_TCP_CONNECT;
   1254   return OK;
   1255 }
   1256 
   1257 int SocketStream::AllowCertErrorForReconnection(SSLConfig* ssl_config) {
   1258   DCHECK(ssl_config);
   1259   // The SSL handshake didn't finish, or the server closed the SSL connection.
   1260   // So, we should restart establishing connection with the certificate in
   1261   // allowed bad certificates in |ssl_config|.
   1262   // See also net/http/http_network_transaction.cc HandleCertificateError() and
   1263   // RestartIgnoringLastError().
   1264   SSLClientSocket* ssl_socket =
   1265       static_cast<SSLClientSocket*>(connection_->socket());
   1266   SSLInfo ssl_info;
   1267   ssl_socket->GetSSLInfo(&ssl_info);
   1268   if (ssl_info.cert.get() == NULL ||
   1269       ssl_config->IsAllowedBadCert(ssl_info.cert.get(), NULL)) {
   1270     // If we already have the certificate in the set of allowed bad
   1271     // certificates, we did try it and failed again, so we should not
   1272     // retry again: the connection should fail at last.
   1273     next_state_ = STATE_CLOSE;
   1274     return ERR_UNEXPECTED;
   1275   }
   1276   // Add the bad certificate to the set of allowed certificates in the
   1277   // SSL config object.
   1278   SSLConfig::CertAndStatus bad_cert;
   1279   if (!X509Certificate::GetDEREncoded(ssl_info.cert->os_cert_handle(),
   1280                                       &bad_cert.der_cert)) {
   1281     next_state_ = STATE_CLOSE;
   1282     return ERR_UNEXPECTED;
   1283   }
   1284   bad_cert.cert_status = ssl_info.cert_status;
   1285   ssl_config->allowed_bad_certs.push_back(bad_cert);
   1286   // Restart connection ignoring the bad certificate.
   1287   connection_->socket()->Disconnect();
   1288   connection_->SetSocket(scoped_ptr<StreamSocket>());
   1289   next_state_ = STATE_TCP_CONNECT;
   1290   return OK;
   1291 }
   1292 
   1293 void SocketStream::DoAuthRequired() {
   1294   if (delegate_ && proxy_auth_controller_.get())
   1295     delegate_->OnAuthRequired(this, proxy_auth_controller_->auth_info().get());
   1296   else
   1297     DoLoop(ERR_UNEXPECTED);
   1298 }
   1299 
   1300 void SocketStream::DoRestartWithAuth() {
   1301   DCHECK_EQ(next_state_, STATE_AUTH_REQUIRED);
   1302   tunnel_request_headers_ = NULL;
   1303   tunnel_request_headers_bytes_sent_ = 0;
   1304   tunnel_response_headers_ = NULL;
   1305   tunnel_response_headers_capacity_ = 0;
   1306   tunnel_response_headers_len_ = 0;
   1307 
   1308   next_state_ = STATE_TCP_CONNECT;
   1309   DoLoop(OK);
   1310 }
   1311 
   1312 int SocketStream::HandleCertificateError(int result) {
   1313   DCHECK(IsCertificateError(result));
   1314   SSLClientSocket* ssl_socket =
   1315       static_cast<SSLClientSocket*>(connection_->socket());
   1316   DCHECK(ssl_socket);
   1317 
   1318   if (!context_)
   1319     return result;
   1320 
   1321   if (SSLClientSocket::IgnoreCertError(result, LOAD_IGNORE_ALL_CERT_ERRORS)) {
   1322     const HttpNetworkSession::Params* session_params =
   1323         context_->GetNetworkSessionParams();
   1324     if (session_params && session_params->ignore_certificate_errors)
   1325       return OK;
   1326   }
   1327 
   1328   if (!delegate_)
   1329     return result;
   1330 
   1331   SSLInfo ssl_info;
   1332   ssl_socket->GetSSLInfo(&ssl_info);
   1333 
   1334   TransportSecurityState::DomainState domain_state;
   1335   const bool fatal = context_->transport_security_state() &&
   1336       context_->transport_security_state()->GetDomainState(url_.host(),
   1337           SSLConfigService::IsSNIAvailable(context_->ssl_config_service()),
   1338           &domain_state) &&
   1339       domain_state.ShouldSSLErrorsBeFatal();
   1340 
   1341   delegate_->OnSSLCertificateError(this, ssl_info, fatal);
   1342   return ERR_IO_PENDING;
   1343 }
   1344 
   1345 }  // namespace net
   1346