http_network_transaction.cc revision 90dce4d38c5ff5333bea97d859d4e484e27edf0c
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#include "net/http/http_network_transaction.h"
6
7#include <set>
8#include <vector>
9
10#include "base/bind.h"
11#include "base/bind_helpers.h"
12#include "base/compiler_specific.h"
13#include "base/format_macros.h"
14#include "base/memory/scoped_ptr.h"
15#include "base/metrics/field_trial.h"
16#include "base/metrics/histogram.h"
17#include "base/metrics/stats_counters.h"
18#include "base/stl_util.h"
19#include "base/string_number_conversions.h"
20#include "base/string_util.h"
21#include "base/stringprintf.h"
22#include "base/values.h"
23#include "build/build_config.h"
24#include "googleurl/src/gurl.h"
25#include "net/base/auth.h"
26#include "net/base/host_port_pair.h"
27#include "net/base/io_buffer.h"
28#include "net/base/load_flags.h"
29#include "net/base/load_timing_info.h"
30#include "net/base/net_errors.h"
31#include "net/base/net_util.h"
32#include "net/base/upload_data_stream.h"
33#include "net/http/http_auth.h"
34#include "net/http/http_auth_handler.h"
35#include "net/http/http_auth_handler_factory.h"
36#include "net/http/http_basic_stream.h"
37#include "net/http/http_chunked_decoder.h"
38#include "net/http/http_network_session.h"
39#include "net/http/http_proxy_client_socket.h"
40#include "net/http/http_proxy_client_socket_pool.h"
41#include "net/http/http_request_headers.h"
42#include "net/http/http_request_info.h"
43#include "net/http/http_response_headers.h"
44#include "net/http/http_response_info.h"
45#include "net/http/http_server_properties.h"
46#include "net/http/http_status_code.h"
47#include "net/http/http_stream_base.h"
48#include "net/http/http_stream_factory.h"
49#include "net/http/http_util.h"
50#include "net/http/transport_security_state.h"
51#include "net/http/url_security_manager.h"
52#include "net/socket/client_socket_factory.h"
53#include "net/socket/socks_client_socket_pool.h"
54#include "net/socket/ssl_client_socket.h"
55#include "net/socket/ssl_client_socket_pool.h"
56#include "net/socket/transport_client_socket_pool.h"
57#include "net/spdy/spdy_http_stream.h"
58#include "net/spdy/spdy_session.h"
59#include "net/spdy/spdy_session_pool.h"
60#include "net/ssl/ssl_cert_request_info.h"
61#include "net/ssl/ssl_connection_status_flags.h"
62
63using base::Time;
64
65namespace net {
66
67namespace {
68
69void ProcessAlternateProtocol(HttpStreamFactory* factory,
70                              HttpServerProperties* http_server_properties,
71                              const HttpResponseHeaders& headers,
72                              const HostPortPair& http_host_port_pair) {
73  std::string alternate_protocol_str;
74
75  if (!headers.EnumerateHeader(NULL, kAlternateProtocolHeader,
76                               &alternate_protocol_str)) {
77    // Header is not present.
78    return;
79  }
80
81  factory->ProcessAlternateProtocol(http_server_properties,
82                                    alternate_protocol_str,
83                                    http_host_port_pair);
84}
85
86// Returns true if |error| is a client certificate authentication error.
87bool IsClientCertificateError(int error) {
88  switch (error) {
89    case ERR_BAD_SSL_CLIENT_AUTH_CERT:
90    case ERR_SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED:
91    case ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY:
92    case ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED:
93      return true;
94    default:
95      return false;
96  }
97}
98
99Value* NetLogSSLVersionFallbackCallback(const GURL* url,
100                                        int net_error,
101                                        uint16 version_before,
102                                        uint16 version_after,
103                                        NetLog::LogLevel /* log_level */) {
104  DictionaryValue* dict = new DictionaryValue();
105  dict->SetString("host_and_port", GetHostAndPort(*url));
106  dict->SetInteger("net_error", net_error);
107  dict->SetInteger("version_before", version_before);
108  dict->SetInteger("version_after", version_after);
109  return dict;
110}
111
112}  // namespace
113
114//-----------------------------------------------------------------------------
115
116HttpNetworkTransaction::HttpNetworkTransaction(RequestPriority priority,
117                                               HttpNetworkSession* session)
118    : pending_auth_target_(HttpAuth::AUTH_NONE),
119      io_callback_(base::Bind(&HttpNetworkTransaction::OnIOComplete,
120                              base::Unretained(this))),
121      session_(session),
122      request_(NULL),
123      priority_(priority),
124      headers_valid_(false),
125      logged_response_time_(false),
126      request_headers_(),
127      read_buf_len_(0),
128      next_state_(STATE_NONE),
129      establishing_tunnel_(false) {
130  session->ssl_config_service()->GetSSLConfig(&server_ssl_config_);
131  if (session->http_stream_factory()->has_next_protos()) {
132    server_ssl_config_.next_protos =
133        session->http_stream_factory()->next_protos();
134  }
135  proxy_ssl_config_ = server_ssl_config_;
136}
137
138HttpNetworkTransaction::~HttpNetworkTransaction() {
139  if (stream_.get()) {
140    HttpResponseHeaders* headers = GetResponseHeaders();
141    // TODO(mbelshe): The stream_ should be able to compute whether or not the
142    //                stream should be kept alive.  No reason to compute here
143    //                and pass it in.
144    bool try_to_keep_alive =
145        next_state_ == STATE_NONE &&
146        stream_->CanFindEndOfResponse() &&
147        (!headers || headers->IsKeepAlive());
148    if (!try_to_keep_alive) {
149      stream_->Close(true /* not reusable */);
150    } else {
151      if (stream_->IsResponseBodyComplete()) {
152        // If the response body is complete, we can just reuse the socket.
153        stream_->Close(false /* reusable */);
154      } else if (stream_->IsSpdyHttpStream()) {
155        // Doesn't really matter for SpdyHttpStream. Just close it.
156        stream_->Close(true /* not reusable */);
157      } else {
158        // Otherwise, we try to drain the response body.
159        HttpStreamBase* stream = stream_.release();
160        stream->Drain(session_);
161      }
162    }
163  }
164}
165
166int HttpNetworkTransaction::Start(const HttpRequestInfo* request_info,
167                                  const CompletionCallback& callback,
168                                  const BoundNetLog& net_log) {
169  SIMPLE_STATS_COUNTER("HttpNetworkTransaction.Count");
170
171  net_log_ = net_log;
172  request_ = request_info;
173  start_time_ = base::Time::Now();
174
175  if (request_->load_flags & LOAD_DISABLE_CERT_REVOCATION_CHECKING) {
176    server_ssl_config_.rev_checking_enabled = false;
177    proxy_ssl_config_.rev_checking_enabled = false;
178  }
179
180  // Channel ID is enabled unless --disable-tls-channel-id flag is set,
181  // or if privacy mode is enabled.
182  bool channel_id_enabled = server_ssl_config_.channel_id_enabled &&
183      (request_->privacy_mode == kPrivacyModeDisabled);
184  server_ssl_config_.channel_id_enabled = channel_id_enabled;
185
186  next_state_ = STATE_CREATE_STREAM;
187  int rv = DoLoop(OK);
188  if (rv == ERR_IO_PENDING)
189    callback_ = callback;
190  return rv;
191}
192
193int HttpNetworkTransaction::RestartIgnoringLastError(
194    const CompletionCallback& callback) {
195  DCHECK(!stream_.get());
196  DCHECK(!stream_request_.get());
197  DCHECK_EQ(STATE_NONE, next_state_);
198
199  next_state_ = STATE_CREATE_STREAM;
200
201  int rv = DoLoop(OK);
202  if (rv == ERR_IO_PENDING)
203    callback_ = callback;
204  return rv;
205}
206
207int HttpNetworkTransaction::RestartWithCertificate(
208    X509Certificate* client_cert, const CompletionCallback& callback) {
209  // In HandleCertificateRequest(), we always tear down existing stream
210  // requests to force a new connection.  So we shouldn't have one here.
211  DCHECK(!stream_request_.get());
212  DCHECK(!stream_.get());
213  DCHECK_EQ(STATE_NONE, next_state_);
214
215  SSLConfig* ssl_config = response_.cert_request_info->is_proxy ?
216      &proxy_ssl_config_ : &server_ssl_config_;
217  ssl_config->send_client_cert = true;
218  ssl_config->client_cert = client_cert;
219  session_->ssl_client_auth_cache()->Add(
220      response_.cert_request_info->host_and_port, client_cert);
221  // Reset the other member variables.
222  // Note: this is necessary only with SSL renegotiation.
223  ResetStateForRestart();
224  next_state_ = STATE_CREATE_STREAM;
225  int rv = DoLoop(OK);
226  if (rv == ERR_IO_PENDING)
227    callback_ = callback;
228  return rv;
229}
230
231int HttpNetworkTransaction::RestartWithAuth(
232    const AuthCredentials& credentials, const CompletionCallback& callback) {
233  HttpAuth::Target target = pending_auth_target_;
234  if (target == HttpAuth::AUTH_NONE) {
235    NOTREACHED();
236    return ERR_UNEXPECTED;
237  }
238  pending_auth_target_ = HttpAuth::AUTH_NONE;
239
240  auth_controllers_[target]->ResetAuth(credentials);
241
242  DCHECK(callback_.is_null());
243
244  int rv = OK;
245  if (target == HttpAuth::AUTH_PROXY && establishing_tunnel_) {
246    // In this case, we've gathered credentials for use with proxy
247    // authentication of a tunnel.
248    DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
249    DCHECK(stream_request_ != NULL);
250    auth_controllers_[target] = NULL;
251    ResetStateForRestart();
252    rv = stream_request_->RestartTunnelWithProxyAuth(credentials);
253  } else {
254    // In this case, we've gathered credentials for the server or the proxy
255    // but it is not during the tunneling phase.
256    DCHECK(stream_request_ == NULL);
257    PrepareForAuthRestart(target);
258    rv = DoLoop(OK);
259  }
260
261  if (rv == ERR_IO_PENDING)
262    callback_ = callback;
263  return rv;
264}
265
266void HttpNetworkTransaction::PrepareForAuthRestart(HttpAuth::Target target) {
267  DCHECK(HaveAuth(target));
268  DCHECK(!stream_request_.get());
269
270  bool keep_alive = false;
271  // Even if the server says the connection is keep-alive, we have to be
272  // able to find the end of each response in order to reuse the connection.
273  if (GetResponseHeaders()->IsKeepAlive() &&
274      stream_->CanFindEndOfResponse()) {
275    // If the response body hasn't been completely read, we need to drain
276    // it first.
277    if (!stream_->IsResponseBodyComplete()) {
278      next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
279      read_buf_ = new IOBuffer(kDrainBodyBufferSize);  // A bit bucket.
280      read_buf_len_ = kDrainBodyBufferSize;
281      return;
282    }
283    keep_alive = true;
284  }
285
286  // We don't need to drain the response body, so we act as if we had drained
287  // the response body.
288  DidDrainBodyForAuthRestart(keep_alive);
289}
290
291void HttpNetworkTransaction::DidDrainBodyForAuthRestart(bool keep_alive) {
292  DCHECK(!stream_request_.get());
293
294  if (stream_.get()) {
295    HttpStream* new_stream = NULL;
296    if (keep_alive && stream_->IsConnectionReusable()) {
297      // We should call connection_->set_idle_time(), but this doesn't occur
298      // often enough to be worth the trouble.
299      stream_->SetConnectionReused();
300      new_stream =
301          static_cast<HttpStream*>(stream_.get())->RenewStreamForAuth();
302    }
303
304    if (!new_stream) {
305      // Close the stream and mark it as not_reusable.  Even in the
306      // keep_alive case, we've determined that the stream_ is not
307      // reusable if new_stream is NULL.
308      stream_->Close(true);
309      next_state_ = STATE_CREATE_STREAM;
310    } else {
311      next_state_ = STATE_INIT_STREAM;
312    }
313    stream_.reset(new_stream);
314  }
315
316  // Reset the other member variables.
317  ResetStateForAuthRestart();
318}
319
320bool HttpNetworkTransaction::IsReadyToRestartForAuth() {
321  return pending_auth_target_ != HttpAuth::AUTH_NONE &&
322      HaveAuth(pending_auth_target_);
323}
324
325int HttpNetworkTransaction::Read(IOBuffer* buf, int buf_len,
326                                 const CompletionCallback& callback) {
327  DCHECK(buf);
328  DCHECK_LT(0, buf_len);
329
330  State next_state = STATE_NONE;
331
332  scoped_refptr<HttpResponseHeaders> headers(GetResponseHeaders());
333  if (headers_valid_ && headers.get() && stream_request_.get()) {
334    // We're trying to read the body of the response but we're still trying
335    // to establish an SSL tunnel through an HTTP proxy.  We can't read these
336    // bytes when establishing a tunnel because they might be controlled by
337    // an active network attacker.  We don't worry about this for HTTP
338    // because an active network attacker can already control HTTP sessions.
339    // We reach this case when the user cancels a 407 proxy auth prompt.  We
340    // also don't worry about this for an HTTPS Proxy, because the
341    // communication with the proxy is secure.
342    // See http://crbug.com/8473.
343    DCHECK(proxy_info_.is_http() || proxy_info_.is_https());
344    DCHECK_EQ(headers->response_code(), HTTP_PROXY_AUTHENTICATION_REQUIRED);
345    LOG(WARNING) << "Blocked proxy response with status "
346                 << headers->response_code() << " to CONNECT request for "
347                 << GetHostAndPort(request_->url) << ".";
348    return ERR_TUNNEL_CONNECTION_FAILED;
349  }
350
351  // Are we using SPDY or HTTP?
352  next_state = STATE_READ_BODY;
353
354  read_buf_ = buf;
355  read_buf_len_ = buf_len;
356
357  next_state_ = next_state;
358  int rv = DoLoop(OK);
359  if (rv == ERR_IO_PENDING)
360    callback_ = callback;
361  return rv;
362}
363
364const HttpResponseInfo* HttpNetworkTransaction::GetResponseInfo() const {
365  return ((headers_valid_ && response_.headers) || response_.ssl_info.cert ||
366          response_.cert_request_info) ? &response_ : NULL;
367}
368
369LoadState HttpNetworkTransaction::GetLoadState() const {
370  // TODO(wtc): Define a new LoadState value for the
371  // STATE_INIT_CONNECTION_COMPLETE state, which delays the HTTP request.
372  switch (next_state_) {
373    case STATE_CREATE_STREAM_COMPLETE:
374      return stream_request_->GetLoadState();
375    case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
376    case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE:
377    case STATE_SEND_REQUEST_COMPLETE:
378      return LOAD_STATE_SENDING_REQUEST;
379    case STATE_READ_HEADERS_COMPLETE:
380      return LOAD_STATE_WAITING_FOR_RESPONSE;
381    case STATE_READ_BODY_COMPLETE:
382      return LOAD_STATE_READING_RESPONSE;
383    default:
384      return LOAD_STATE_IDLE;
385  }
386}
387
388UploadProgress HttpNetworkTransaction::GetUploadProgress() const {
389  if (!stream_.get())
390    return UploadProgress();
391
392  // TODO(bashi): This cast is temporary. Remove later.
393  return static_cast<HttpStream*>(stream_.get())->GetUploadProgress();
394}
395
396bool HttpNetworkTransaction::GetLoadTimingInfo(
397    LoadTimingInfo* load_timing_info) const {
398  if (!stream_ || !stream_->GetLoadTimingInfo(load_timing_info))
399    return false;
400
401  load_timing_info->proxy_resolve_start =
402      proxy_info_.proxy_resolve_start_time();
403  load_timing_info->proxy_resolve_end = proxy_info_.proxy_resolve_end_time();
404  load_timing_info->send_start = send_start_time_;
405  load_timing_info->send_end = send_end_time_;
406  return true;
407}
408
409void HttpNetworkTransaction::SetPriority(RequestPriority priority) {
410  priority_ = priority;
411  // TODO(akalin): Plumb this through to |stream_request_| and
412  // |stream_|.
413}
414
415void HttpNetworkTransaction::OnStreamReady(const SSLConfig& used_ssl_config,
416                                           const ProxyInfo& used_proxy_info,
417                                           HttpStreamBase* stream) {
418  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
419  DCHECK(stream_request_.get());
420
421  stream_.reset(stream);
422  server_ssl_config_ = used_ssl_config;
423  proxy_info_ = used_proxy_info;
424  response_.was_npn_negotiated = stream_request_->was_npn_negotiated();
425  response_.npn_negotiated_protocol = SSLClientSocket::NextProtoToString(
426      stream_request_->protocol_negotiated());
427  response_.was_fetched_via_spdy = stream_request_->using_spdy();
428  response_.was_fetched_via_proxy = !proxy_info_.is_direct();
429
430  OnIOComplete(OK);
431}
432
433void HttpNetworkTransaction::OnStreamFailed(int result,
434                                            const SSLConfig& used_ssl_config) {
435  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
436  DCHECK_NE(OK, result);
437  DCHECK(stream_request_.get());
438  DCHECK(!stream_.get());
439  server_ssl_config_ = used_ssl_config;
440
441  OnIOComplete(result);
442}
443
444void HttpNetworkTransaction::OnCertificateError(
445    int result,
446    const SSLConfig& used_ssl_config,
447    const SSLInfo& ssl_info) {
448  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
449  DCHECK_NE(OK, result);
450  DCHECK(stream_request_.get());
451  DCHECK(!stream_.get());
452
453  response_.ssl_info = ssl_info;
454  server_ssl_config_ = used_ssl_config;
455
456  // TODO(mbelshe):  For now, we're going to pass the error through, and that
457  // will close the stream_request in all cases.  This means that we're always
458  // going to restart an entire STATE_CREATE_STREAM, even if the connection is
459  // good and the user chooses to ignore the error.  This is not ideal, but not
460  // the end of the world either.
461
462  OnIOComplete(result);
463}
464
465void HttpNetworkTransaction::OnNeedsProxyAuth(
466    const HttpResponseInfo& proxy_response,
467    const SSLConfig& used_ssl_config,
468    const ProxyInfo& used_proxy_info,
469    HttpAuthController* auth_controller) {
470  DCHECK(stream_request_.get());
471  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
472
473  establishing_tunnel_ = true;
474  response_.headers = proxy_response.headers;
475  response_.auth_challenge = proxy_response.auth_challenge;
476  headers_valid_ = true;
477  server_ssl_config_ = used_ssl_config;
478  proxy_info_ = used_proxy_info;
479
480  auth_controllers_[HttpAuth::AUTH_PROXY] = auth_controller;
481  pending_auth_target_ = HttpAuth::AUTH_PROXY;
482
483  DoCallback(OK);
484}
485
486void HttpNetworkTransaction::OnNeedsClientAuth(
487    const SSLConfig& used_ssl_config,
488    SSLCertRequestInfo* cert_info) {
489  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
490
491  server_ssl_config_ = used_ssl_config;
492  response_.cert_request_info = cert_info;
493  OnIOComplete(ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
494}
495
496void HttpNetworkTransaction::OnHttpsProxyTunnelResponse(
497    const HttpResponseInfo& response_info,
498    const SSLConfig& used_ssl_config,
499    const ProxyInfo& used_proxy_info,
500    HttpStreamBase* stream) {
501  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
502
503  headers_valid_ = true;
504  response_ = response_info;
505  server_ssl_config_ = used_ssl_config;
506  proxy_info_ = used_proxy_info;
507  stream_.reset(stream);
508  stream_request_.reset();  // we're done with the stream request
509  OnIOComplete(ERR_HTTPS_PROXY_TUNNEL_RESPONSE);
510}
511
512bool HttpNetworkTransaction::is_https_request() const {
513  return request_->url.SchemeIs("https");
514}
515
516void HttpNetworkTransaction::DoCallback(int rv) {
517  DCHECK_NE(rv, ERR_IO_PENDING);
518  DCHECK(!callback_.is_null());
519
520  // Since Run may result in Read being called, clear user_callback_ up front.
521  CompletionCallback c = callback_;
522  callback_.Reset();
523  c.Run(rv);
524}
525
526void HttpNetworkTransaction::OnIOComplete(int result) {
527  int rv = DoLoop(result);
528  if (rv != ERR_IO_PENDING)
529    DoCallback(rv);
530}
531
532int HttpNetworkTransaction::DoLoop(int result) {
533  DCHECK(next_state_ != STATE_NONE);
534
535  int rv = result;
536  do {
537    State state = next_state_;
538    next_state_ = STATE_NONE;
539    switch (state) {
540      case STATE_CREATE_STREAM:
541        DCHECK_EQ(OK, rv);
542        rv = DoCreateStream();
543        break;
544      case STATE_CREATE_STREAM_COMPLETE:
545        rv = DoCreateStreamComplete(rv);
546        break;
547      case STATE_INIT_STREAM:
548        DCHECK_EQ(OK, rv);
549        rv = DoInitStream();
550        break;
551      case STATE_INIT_STREAM_COMPLETE:
552        rv = DoInitStreamComplete(rv);
553        break;
554      case STATE_GENERATE_PROXY_AUTH_TOKEN:
555        DCHECK_EQ(OK, rv);
556        rv = DoGenerateProxyAuthToken();
557        break;
558      case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
559        rv = DoGenerateProxyAuthTokenComplete(rv);
560        break;
561      case STATE_GENERATE_SERVER_AUTH_TOKEN:
562        DCHECK_EQ(OK, rv);
563        rv = DoGenerateServerAuthToken();
564        break;
565      case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE:
566        rv = DoGenerateServerAuthTokenComplete(rv);
567        break;
568      case STATE_INIT_REQUEST_BODY:
569        DCHECK_EQ(OK, rv);
570        rv = DoInitRequestBody();
571        break;
572      case STATE_INIT_REQUEST_BODY_COMPLETE:
573        rv = DoInitRequestBodyComplete(rv);
574        break;
575      case STATE_BUILD_REQUEST:
576        DCHECK_EQ(OK, rv);
577        net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST);
578        rv = DoBuildRequest();
579        break;
580      case STATE_BUILD_REQUEST_COMPLETE:
581        rv = DoBuildRequestComplete(rv);
582        break;
583      case STATE_SEND_REQUEST:
584        DCHECK_EQ(OK, rv);
585        rv = DoSendRequest();
586        break;
587      case STATE_SEND_REQUEST_COMPLETE:
588        rv = DoSendRequestComplete(rv);
589        net_log_.EndEventWithNetErrorCode(
590            NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST, rv);
591        break;
592      case STATE_READ_HEADERS:
593        DCHECK_EQ(OK, rv);
594        net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS);
595        rv = DoReadHeaders();
596        break;
597      case STATE_READ_HEADERS_COMPLETE:
598        rv = DoReadHeadersComplete(rv);
599        net_log_.EndEventWithNetErrorCode(
600            NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS, rv);
601        break;
602      case STATE_READ_BODY:
603        DCHECK_EQ(OK, rv);
604        net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_BODY);
605        rv = DoReadBody();
606        break;
607      case STATE_READ_BODY_COMPLETE:
608        rv = DoReadBodyComplete(rv);
609        net_log_.EndEventWithNetErrorCode(
610            NetLog::TYPE_HTTP_TRANSACTION_READ_BODY, rv);
611        break;
612      case STATE_DRAIN_BODY_FOR_AUTH_RESTART:
613        DCHECK_EQ(OK, rv);
614        net_log_.BeginEvent(
615            NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART);
616        rv = DoDrainBodyForAuthRestart();
617        break;
618      case STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE:
619        rv = DoDrainBodyForAuthRestartComplete(rv);
620        net_log_.EndEventWithNetErrorCode(
621            NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART, rv);
622        break;
623      default:
624        NOTREACHED() << "bad state";
625        rv = ERR_FAILED;
626        break;
627    }
628  } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
629
630  return rv;
631}
632
633int HttpNetworkTransaction::DoCreateStream() {
634  next_state_ = STATE_CREATE_STREAM_COMPLETE;
635
636  stream_request_.reset(
637      session_->http_stream_factory()->RequestStream(
638          *request_,
639          priority_,
640          server_ssl_config_,
641          proxy_ssl_config_,
642          this,
643          net_log_));
644  DCHECK(stream_request_.get());
645  return ERR_IO_PENDING;
646}
647
648int HttpNetworkTransaction::DoCreateStreamComplete(int result) {
649  if (result == OK) {
650    next_state_ = STATE_INIT_STREAM;
651    DCHECK(stream_.get());
652  } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
653    result = HandleCertificateRequest(result);
654  } else if (result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
655    // Return OK and let the caller read the proxy's error page
656    next_state_ = STATE_NONE;
657    return OK;
658  }
659
660  // Handle possible handshake errors that may have occurred if the stream
661  // used SSL for one or more of the layers.
662  result = HandleSSLHandshakeError(result);
663
664  // At this point we are done with the stream_request_.
665  stream_request_.reset();
666  return result;
667}
668
669int HttpNetworkTransaction::DoInitStream() {
670  DCHECK(stream_.get());
671  next_state_ = STATE_INIT_STREAM_COMPLETE;
672  return stream_->InitializeStream(request_, priority_, net_log_, io_callback_);
673}
674
675int HttpNetworkTransaction::DoInitStreamComplete(int result) {
676  if (result == OK) {
677    next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
678  } else {
679    if (result < 0)
680      result = HandleIOError(result);
681
682    // The stream initialization failed, so this stream will never be useful.
683    stream_.reset();
684  }
685
686  return result;
687}
688
689int HttpNetworkTransaction::DoGenerateProxyAuthToken() {
690  next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE;
691  if (!ShouldApplyProxyAuth())
692    return OK;
693  HttpAuth::Target target = HttpAuth::AUTH_PROXY;
694  if (!auth_controllers_[target].get())
695    auth_controllers_[target] =
696        new HttpAuthController(target,
697                               AuthURL(target),
698                               session_->http_auth_cache(),
699                               session_->http_auth_handler_factory());
700  return auth_controllers_[target]->MaybeGenerateAuthToken(request_,
701                                                           io_callback_,
702                                                           net_log_);
703}
704
705int HttpNetworkTransaction::DoGenerateProxyAuthTokenComplete(int rv) {
706  DCHECK_NE(ERR_IO_PENDING, rv);
707  if (rv == OK)
708    next_state_ = STATE_GENERATE_SERVER_AUTH_TOKEN;
709  return rv;
710}
711
712int HttpNetworkTransaction::DoGenerateServerAuthToken() {
713  next_state_ = STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE;
714  HttpAuth::Target target = HttpAuth::AUTH_SERVER;
715  if (!auth_controllers_[target].get())
716    auth_controllers_[target] =
717        new HttpAuthController(target,
718                               AuthURL(target),
719                               session_->http_auth_cache(),
720                               session_->http_auth_handler_factory());
721  if (!ShouldApplyServerAuth())
722    return OK;
723  return auth_controllers_[target]->MaybeGenerateAuthToken(request_,
724                                                           io_callback_,
725                                                           net_log_);
726}
727
728int HttpNetworkTransaction::DoGenerateServerAuthTokenComplete(int rv) {
729  DCHECK_NE(ERR_IO_PENDING, rv);
730  if (rv == OK)
731    next_state_ = STATE_INIT_REQUEST_BODY;
732  return rv;
733}
734
735void HttpNetworkTransaction::BuildRequestHeaders(bool using_proxy) {
736  request_headers_.SetHeader(HttpRequestHeaders::kHost,
737                             GetHostAndOptionalPort(request_->url));
738
739  // For compat with HTTP/1.0 servers and proxies:
740  if (using_proxy) {
741    request_headers_.SetHeader(HttpRequestHeaders::kProxyConnection,
742                               "keep-alive");
743  } else {
744    request_headers_.SetHeader(HttpRequestHeaders::kConnection, "keep-alive");
745  }
746
747  // Add a content length header?
748  if (request_->upload_data_stream) {
749    if (request_->upload_data_stream->is_chunked()) {
750      request_headers_.SetHeader(
751          HttpRequestHeaders::kTransferEncoding, "chunked");
752    } else {
753      request_headers_.SetHeader(
754          HttpRequestHeaders::kContentLength,
755          base::Uint64ToString(request_->upload_data_stream->size()));
756    }
757  } else if (request_->method == "POST" || request_->method == "PUT" ||
758             request_->method == "HEAD") {
759    // An empty POST/PUT request still needs a content length.  As for HEAD,
760    // IE and Safari also add a content length header.  Presumably it is to
761    // support sending a HEAD request to an URL that only expects to be sent a
762    // POST or some other method that normally would have a message body.
763    request_headers_.SetHeader(HttpRequestHeaders::kContentLength, "0");
764  }
765
766  // Honor load flags that impact proxy caches.
767  if (request_->load_flags & LOAD_BYPASS_CACHE) {
768    request_headers_.SetHeader(HttpRequestHeaders::kPragma, "no-cache");
769    request_headers_.SetHeader(HttpRequestHeaders::kCacheControl, "no-cache");
770  } else if (request_->load_flags & LOAD_VALIDATE_CACHE) {
771    request_headers_.SetHeader(HttpRequestHeaders::kCacheControl, "max-age=0");
772  }
773
774  if (ShouldApplyProxyAuth() && HaveAuth(HttpAuth::AUTH_PROXY))
775    auth_controllers_[HttpAuth::AUTH_PROXY]->AddAuthorizationHeader(
776        &request_headers_);
777  if (ShouldApplyServerAuth() && HaveAuth(HttpAuth::AUTH_SERVER))
778    auth_controllers_[HttpAuth::AUTH_SERVER]->AddAuthorizationHeader(
779        &request_headers_);
780
781  request_headers_.MergeFrom(request_->extra_headers);
782  response_.did_use_http_auth =
783      request_headers_.HasHeader(HttpRequestHeaders::kAuthorization) ||
784      request_headers_.HasHeader(HttpRequestHeaders::kProxyAuthorization);
785}
786
787int HttpNetworkTransaction::DoInitRequestBody() {
788  next_state_ = STATE_INIT_REQUEST_BODY_COMPLETE;
789  int rv = OK;
790  if (request_->upload_data_stream)
791    rv = request_->upload_data_stream->Init(io_callback_);
792  return rv;
793}
794
795int HttpNetworkTransaction::DoInitRequestBodyComplete(int result) {
796  if (result == OK)
797    next_state_ = STATE_BUILD_REQUEST;
798  return result;
799}
800
801int HttpNetworkTransaction::DoBuildRequest() {
802  next_state_ = STATE_BUILD_REQUEST_COMPLETE;
803  headers_valid_ = false;
804
805  // This is constructed lazily (instead of within our Start method), so that
806  // we have proxy info available.
807  if (request_headers_.IsEmpty()) {
808    bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
809                        !is_https_request();
810    BuildRequestHeaders(using_proxy);
811  }
812
813  return OK;
814}
815
816int HttpNetworkTransaction::DoBuildRequestComplete(int result) {
817  if (result == OK)
818    next_state_ = STATE_SEND_REQUEST;
819  return result;
820}
821
822int HttpNetworkTransaction::DoSendRequest() {
823  send_start_time_ = base::TimeTicks::Now();
824  next_state_ = STATE_SEND_REQUEST_COMPLETE;
825
826  return stream_->SendRequest(request_headers_, &response_, io_callback_);
827}
828
829int HttpNetworkTransaction::DoSendRequestComplete(int result) {
830  send_end_time_ = base::TimeTicks::Now();
831  if (result < 0)
832    return HandleIOError(result);
833  response_.network_accessed = true;
834  next_state_ = STATE_READ_HEADERS;
835  return OK;
836}
837
838int HttpNetworkTransaction::DoReadHeaders() {
839  next_state_ = STATE_READ_HEADERS_COMPLETE;
840  return stream_->ReadResponseHeaders(io_callback_);
841}
842
843int HttpNetworkTransaction::HandleConnectionClosedBeforeEndOfHeaders() {
844  if (!response_.headers && !stream_->IsConnectionReused()) {
845    // The connection was closed before any data was sent. Likely an error
846    // rather than empty HTTP/0.9 response.
847    return ERR_EMPTY_RESPONSE;
848  }
849
850  return OK;
851}
852
853int HttpNetworkTransaction::DoReadHeadersComplete(int result) {
854  // We can get a certificate error or ERR_SSL_CLIENT_AUTH_CERT_NEEDED here
855  // due to SSL renegotiation.
856  if (IsCertificateError(result)) {
857    // We don't handle a certificate error during SSL renegotiation, so we
858    // have to return an error that's not in the certificate error range
859    // (-2xx).
860    LOG(ERROR) << "Got a server certificate with error " << result
861               << " during SSL renegotiation";
862    result = ERR_CERT_ERROR_IN_SSL_RENEGOTIATION;
863  } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
864    // TODO(wtc): Need a test case for this code path!
865    DCHECK(stream_.get());
866    DCHECK(is_https_request());
867    response_.cert_request_info = new SSLCertRequestInfo;
868    stream_->GetSSLCertRequestInfo(response_.cert_request_info);
869    result = HandleCertificateRequest(result);
870    if (result == OK)
871      return result;
872  }
873
874  if (result < 0 && result != ERR_CONNECTION_CLOSED)
875    return HandleIOError(result);
876
877  if (result == ERR_CONNECTION_CLOSED && ShouldResendRequest(result)) {
878    ResetConnectionAndRequestForResend();
879    return OK;
880  }
881
882  // After we call RestartWithAuth a new response_time will be recorded, and
883  // we need to be cautious about incorrectly logging the duration across the
884  // authentication activity.
885  if (result == OK)
886    LogTransactionConnectedMetrics();
887
888  if (result == ERR_CONNECTION_CLOSED) {
889    // For now, if we get at least some data, we do the best we can to make
890    // sense of it and send it back up the stack.
891    int rv = HandleConnectionClosedBeforeEndOfHeaders();
892    if (rv != OK)
893      return rv;
894  }
895  DCHECK(response_.headers);
896
897  // Server-induced fallback is supported only if this is a PAC configured
898  // proxy. See: http://crbug.com/143712
899  if (response_.was_fetched_via_proxy && proxy_info_.did_use_pac_script() &&
900      response_.headers != NULL) {
901    bool should_fallback =
902        response_.headers->HasHeaderValue("connection", "proxy-bypass");
903    // Additionally, fallback if a 500 is returned via the data reduction proxy.
904    // This is conservative, as the 500 might have been generated by the origin,
905    // and not the proxy.
906#if defined(SPDY_PROXY_AUTH_ORIGIN)
907    if (!should_fallback) {
908      should_fallback =
909          response_.headers->response_code() == HTTP_INTERNAL_SERVER_ERROR &&
910          proxy_info_.proxy_server().host_port_pair().Equals(
911              HostPortPair::FromURL(GURL(SPDY_PROXY_AUTH_ORIGIN)));
912    }
913#endif
914    if (should_fallback) {
915      ProxyService* proxy_service = session_->proxy_service();
916      if (proxy_service->MarkProxyAsBad(proxy_info_, net_log_)) {
917        // Only retry in the case of GETs. We don't want to resubmit a POST
918        // if the proxy took some action.
919        if (request_->method == "GET") {
920          ResetConnectionAndRequestForResend();
921          return OK;
922        }
923      }
924    }
925  }
926
927  // Like Net.HttpResponseCode, but only for MAIN_FRAME loads.
928  if (request_->load_flags & LOAD_MAIN_FRAME) {
929    const int response_code = response_.headers->response_code();
930    UMA_HISTOGRAM_ENUMERATION(
931        "Net.HttpResponseCode_Nxx_MainFrame", response_code/100, 10);
932  }
933
934  net_log_.AddEvent(
935      NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS,
936      base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers));
937
938  if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0)) {
939    // HTTP/0.9 doesn't support the PUT method, so lack of response headers
940    // indicates a buggy server.  See:
941    // https://bugzilla.mozilla.org/show_bug.cgi?id=193921
942    if (request_->method == "PUT")
943      return ERR_METHOD_NOT_SUPPORTED;
944  }
945
946  // Check for an intermediate 100 Continue response.  An origin server is
947  // allowed to send this response even if we didn't ask for it, so we just
948  // need to skip over it.
949  // We treat any other 1xx in this same way (although in practice getting
950  // a 1xx that isn't a 100 is rare).
951  if (response_.headers->response_code() / 100 == 1) {
952    response_.headers = new HttpResponseHeaders(std::string());
953    next_state_ = STATE_READ_HEADERS;
954    return OK;
955  }
956
957  HostPortPair endpoint = HostPortPair(request_->url.HostNoBrackets(),
958                                       request_->url.EffectiveIntPort());
959  ProcessAlternateProtocol(session_->http_stream_factory(),
960                           session_->http_server_properties(),
961                           *response_.headers,
962                           endpoint);
963
964  int rv = HandleAuthChallenge();
965  if (rv != OK)
966    return rv;
967
968  if (is_https_request())
969    stream_->GetSSLInfo(&response_.ssl_info);
970
971  headers_valid_ = true;
972  return OK;
973}
974
975int HttpNetworkTransaction::DoReadBody() {
976  DCHECK(read_buf_);
977  DCHECK_GT(read_buf_len_, 0);
978  DCHECK(stream_ != NULL);
979
980  next_state_ = STATE_READ_BODY_COMPLETE;
981  return stream_->ReadResponseBody(read_buf_, read_buf_len_, io_callback_);
982}
983
984int HttpNetworkTransaction::DoReadBodyComplete(int result) {
985  // We are done with the Read call.
986  bool done = false;
987  if (result <= 0) {
988    DCHECK_NE(ERR_IO_PENDING, result);
989    done = true;
990  }
991
992  bool keep_alive = false;
993  if (stream_->IsResponseBodyComplete()) {
994    // Note: Just because IsResponseBodyComplete is true, we're not
995    // necessarily "done".  We're only "done" when it is the last
996    // read on this HttpNetworkTransaction, which will be signified
997    // by a zero-length read.
998    // TODO(mbelshe): The keepalive property is really a property of
999    //    the stream.  No need to compute it here just to pass back
1000    //    to the stream's Close function.
1001    // TODO(rtenneti): CanFindEndOfResponse should return false if there are no
1002    // ResponseHeaders.
1003    if (stream_->CanFindEndOfResponse()) {
1004      HttpResponseHeaders* headers = GetResponseHeaders();
1005      if (headers)
1006        keep_alive = headers->IsKeepAlive();
1007    }
1008  }
1009
1010  // Clean up connection if we are done.
1011  if (done) {
1012    LogTransactionMetrics();
1013    stream_->Close(!keep_alive);
1014    // Note: we don't reset the stream here.  We've closed it, but we still
1015    // need it around so that callers can call methods such as
1016    // GetUploadProgress() and have them be meaningful.
1017    // TODO(mbelshe): This means we closed the stream here, and we close it
1018    // again in ~HttpNetworkTransaction.  Clean that up.
1019
1020    // The next Read call will return 0 (EOF).
1021  }
1022
1023  // Clear these to avoid leaving around old state.
1024  read_buf_ = NULL;
1025  read_buf_len_ = 0;
1026
1027  return result;
1028}
1029
1030int HttpNetworkTransaction::DoDrainBodyForAuthRestart() {
1031  // This method differs from DoReadBody only in the next_state_.  So we just
1032  // call DoReadBody and override the next_state_.  Perhaps there is a more
1033  // elegant way for these two methods to share code.
1034  int rv = DoReadBody();
1035  DCHECK(next_state_ == STATE_READ_BODY_COMPLETE);
1036  next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE;
1037  return rv;
1038}
1039
1040// TODO(wtc): This method and the DoReadBodyComplete method are almost
1041// the same.  Figure out a good way for these two methods to share code.
1042int HttpNetworkTransaction::DoDrainBodyForAuthRestartComplete(int result) {
1043  // keep_alive defaults to true because the very reason we're draining the
1044  // response body is to reuse the connection for auth restart.
1045  bool done = false, keep_alive = true;
1046  if (result < 0) {
1047    // Error or closed connection while reading the socket.
1048    done = true;
1049    keep_alive = false;
1050  } else if (stream_->IsResponseBodyComplete()) {
1051    done = true;
1052  }
1053
1054  if (done) {
1055    DidDrainBodyForAuthRestart(keep_alive);
1056  } else {
1057    // Keep draining.
1058    next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
1059  }
1060
1061  return OK;
1062}
1063
1064void HttpNetworkTransaction::LogTransactionConnectedMetrics() {
1065  if (logged_response_time_)
1066    return;
1067
1068  logged_response_time_ = true;
1069
1070  base::TimeDelta total_duration = response_.response_time - start_time_;
1071
1072  UMA_HISTOGRAM_CUSTOM_TIMES(
1073      "Net.Transaction_Connected",
1074      total_duration,
1075      base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1076      100);
1077
1078  bool reused_socket = stream_->IsConnectionReused();
1079  if (!reused_socket) {
1080    UMA_HISTOGRAM_CUSTOM_TIMES(
1081        "Net.Transaction_Connected_New_b",
1082        total_duration,
1083        base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1084        100);
1085  }
1086
1087  // Currently, non-HIGHEST priority requests are frame or sub-frame resource
1088  // types.  This will change when we also prioritize certain subresources like
1089  // css, js, etc.
1090  if (priority_ != HIGHEST) {
1091    UMA_HISTOGRAM_CUSTOM_TIMES(
1092        "Net.Priority_High_Latency_b",
1093        total_duration,
1094        base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1095        100);
1096  } else {
1097    UMA_HISTOGRAM_CUSTOM_TIMES(
1098        "Net.Priority_Low_Latency_b",
1099        total_duration,
1100        base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1101        100);
1102  }
1103}
1104
1105void HttpNetworkTransaction::LogTransactionMetrics() const {
1106  base::TimeDelta duration = base::Time::Now() -
1107                             response_.request_time;
1108  if (60 < duration.InMinutes())
1109    return;
1110
1111  base::TimeDelta total_duration = base::Time::Now() - start_time_;
1112
1113  UMA_HISTOGRAM_CUSTOM_TIMES("Net.Transaction_Latency_b", duration,
1114                             base::TimeDelta::FromMilliseconds(1),
1115                             base::TimeDelta::FromMinutes(10),
1116                             100);
1117  UMA_HISTOGRAM_CUSTOM_TIMES("Net.Transaction_Latency_Total",
1118                             total_duration,
1119                             base::TimeDelta::FromMilliseconds(1),
1120                             base::TimeDelta::FromMinutes(10), 100);
1121
1122  if (!stream_->IsConnectionReused()) {
1123    UMA_HISTOGRAM_CUSTOM_TIMES(
1124        "Net.Transaction_Latency_Total_New_Connection",
1125        total_duration, base::TimeDelta::FromMilliseconds(1),
1126        base::TimeDelta::FromMinutes(10), 100);
1127  }
1128}
1129
1130int HttpNetworkTransaction::HandleCertificateRequest(int error) {
1131  // There are two paths through which the server can request a certificate
1132  // from us.  The first is during the initial handshake, the second is
1133  // during SSL renegotiation.
1134  //
1135  // In both cases, we want to close the connection before proceeding.
1136  // We do this for two reasons:
1137  //   First, we don't want to keep the connection to the server hung for a
1138  //   long time while the user selects a certificate.
1139  //   Second, even if we did keep the connection open, NSS has a bug where
1140  //   restarting the handshake for ClientAuth is currently broken.
1141  DCHECK_EQ(error, ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
1142
1143  if (stream_.get()) {
1144    // Since we already have a stream, we're being called as part of SSL
1145    // renegotiation.
1146    DCHECK(!stream_request_.get());
1147    stream_->Close(true);
1148    stream_.reset();
1149  }
1150
1151  // The server is asking for a client certificate during the initial
1152  // handshake.
1153  stream_request_.reset();
1154
1155  // If the user selected one of the certificates in client_certs or declined
1156  // to provide one for this server before, use the past decision
1157  // automatically.
1158  scoped_refptr<X509Certificate> client_cert;
1159  bool found_cached_cert = session_->ssl_client_auth_cache()->Lookup(
1160      response_.cert_request_info->host_and_port, &client_cert);
1161  if (!found_cached_cert)
1162    return error;
1163
1164  // Check that the certificate selected is still a certificate the server
1165  // is likely to accept, based on the criteria supplied in the
1166  // CertificateRequest message.
1167  if (client_cert) {
1168    const std::vector<std::string>& cert_authorities =
1169        response_.cert_request_info->cert_authorities;
1170
1171    bool cert_still_valid = cert_authorities.empty() ||
1172        client_cert->IsIssuedByEncoded(cert_authorities);
1173    if (!cert_still_valid)
1174      return error;
1175  }
1176
1177  // TODO(davidben): Add a unit test which covers this path; we need to be
1178  // able to send a legitimate certificate and also bypass/clear the
1179  // SSL session cache.
1180  SSLConfig* ssl_config = response_.cert_request_info->is_proxy ?
1181      &proxy_ssl_config_ : &server_ssl_config_;
1182  ssl_config->send_client_cert = true;
1183  ssl_config->client_cert = client_cert;
1184  next_state_ = STATE_CREATE_STREAM;
1185  // Reset the other member variables.
1186  // Note: this is necessary only with SSL renegotiation.
1187  ResetStateForRestart();
1188  return OK;
1189}
1190
1191// TODO(rch): This does not correctly handle errors when an SSL proxy is
1192// being used, as all of the errors are handled as if they were generated
1193// by the endpoint host, request_->url, rather than considering if they were
1194// generated by the SSL proxy. http://crbug.com/69329
1195int HttpNetworkTransaction::HandleSSLHandshakeError(int error) {
1196  DCHECK(request_);
1197  if (server_ssl_config_.send_client_cert &&
1198      (error == ERR_SSL_PROTOCOL_ERROR || IsClientCertificateError(error))) {
1199    session_->ssl_client_auth_cache()->Remove(
1200        GetHostAndPort(request_->url));
1201  }
1202
1203  uint16 version_max = server_ssl_config_.version_max;
1204
1205  switch (error) {
1206    case ERR_SSL_PROTOCOL_ERROR:
1207    case ERR_SSL_VERSION_OR_CIPHER_MISMATCH:
1208      if (version_max >= SSL_PROTOCOL_VERSION_TLS1 &&
1209          version_max > server_ssl_config_.version_min) {
1210        // This could be a TLS-intolerant server or a server that chose a
1211        // cipher suite defined only for higher protocol versions (such as
1212        // an SSL 3.0 server that chose a TLS-only cipher suite).  Fall
1213        // back to the next lower version and retry.
1214        // NOTE: if the SSLClientSocket class doesn't support TLS 1.1,
1215        // specifying TLS 1.1 in version_max will result in a TLS 1.0
1216        // handshake, so falling back from TLS 1.1 to TLS 1.0 will simply
1217        // repeat the TLS 1.0 handshake. To avoid this problem, the default
1218        // version_max should match the maximum protocol version supported
1219        // by the SSLClientSocket class.
1220        version_max--;
1221
1222        // Fallback to the lower SSL version.
1223        // While SSL 3.0 fallback should be eliminated because of security
1224        // reasons, there is a high risk of breaking the servers if this is
1225        // done in general.
1226        // For now SSL 3.0 fallback is disabled for Google servers first,
1227        // and will be expanded to other servers after enough experiences
1228        // have been gained showing that this experiment works well with
1229        // today's Internet.
1230        if (version_max > SSL_PROTOCOL_VERSION_SSL3 ||
1231            (server_ssl_config_.unrestricted_ssl3_fallback_enabled ||
1232             !TransportSecurityState::IsGooglePinnedProperty(
1233                 request_->url.host(), true /* include SNI */))) {
1234          net_log_.AddEvent(
1235              NetLog::TYPE_SSL_VERSION_FALLBACK,
1236              base::Bind(&NetLogSSLVersionFallbackCallback,
1237                         &request_->url, error, server_ssl_config_.version_max,
1238                         version_max));
1239          server_ssl_config_.version_max = version_max;
1240          server_ssl_config_.version_fallback = true;
1241          ResetConnectionAndRequestForResend();
1242          error = OK;
1243        }
1244      }
1245      break;
1246  }
1247
1248  return error;
1249}
1250
1251// This method determines whether it is safe to resend the request after an
1252// IO error.  It can only be called in response to request header or body
1253// write errors or response header read errors.  It should not be used in
1254// other cases, such as a Connect error.
1255int HttpNetworkTransaction::HandleIOError(int error) {
1256  // SSL errors may happen at any time during the stream and indicate issues
1257  // with the underlying connection. Because the peer may request
1258  // renegotiation at any time, check and handle any possible SSL handshake
1259  // related errors. In addition to renegotiation, TLS False Start may cause
1260  // SSL handshake errors (specifically servers with buggy DEFLATE support)
1261  // to be delayed until the first Read on the underlying connection.
1262  error = HandleSSLHandshakeError(error);
1263
1264  switch (error) {
1265    // If we try to reuse a connection that the server is in the process of
1266    // closing, we may end up successfully writing out our request (or a
1267    // portion of our request) only to find a connection error when we try to
1268    // read from (or finish writing to) the socket.
1269    case ERR_CONNECTION_RESET:
1270    case ERR_CONNECTION_CLOSED:
1271    case ERR_CONNECTION_ABORTED:
1272    // There can be a race between the socket pool checking checking whether a
1273    // socket is still connected, receiving the FIN, and sending/reading data
1274    // on a reused socket.  If we receive the FIN between the connectedness
1275    // check and writing/reading from the socket, we may first learn the socket
1276    // is disconnected when we get a ERR_SOCKET_NOT_CONNECTED.  This will most
1277    // likely happen when trying to retrieve its IP address.
1278    // See http://crbug.com/105824 for more details.
1279    case ERR_SOCKET_NOT_CONNECTED:
1280      if (ShouldResendRequest(error)) {
1281        net_log_.AddEventWithNetErrorCode(
1282            NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
1283        ResetConnectionAndRequestForResend();
1284        error = OK;
1285      }
1286      break;
1287    case ERR_PIPELINE_EVICTION:
1288      if (!session_->force_http_pipelining()) {
1289        net_log_.AddEventWithNetErrorCode(
1290            NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
1291        ResetConnectionAndRequestForResend();
1292        error = OK;
1293      }
1294      break;
1295    case ERR_SPDY_PING_FAILED:
1296    case ERR_SPDY_SERVER_REFUSED_STREAM:
1297      net_log_.AddEventWithNetErrorCode(
1298          NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
1299      ResetConnectionAndRequestForResend();
1300      error = OK;
1301      break;
1302  }
1303  return error;
1304}
1305
1306void HttpNetworkTransaction::ResetStateForRestart() {
1307  ResetStateForAuthRestart();
1308  stream_.reset();
1309}
1310
1311void HttpNetworkTransaction::ResetStateForAuthRestart() {
1312  send_start_time_ = base::TimeTicks();
1313  send_end_time_ = base::TimeTicks();
1314
1315  pending_auth_target_ = HttpAuth::AUTH_NONE;
1316  read_buf_ = NULL;
1317  read_buf_len_ = 0;
1318  headers_valid_ = false;
1319  request_headers_.Clear();
1320  response_ = HttpResponseInfo();
1321  establishing_tunnel_ = false;
1322}
1323
1324HttpResponseHeaders* HttpNetworkTransaction::GetResponseHeaders() const {
1325  return response_.headers;
1326}
1327
1328bool HttpNetworkTransaction::ShouldResendRequest(int error) const {
1329  bool connection_is_proven = stream_->IsConnectionReused();
1330  bool has_received_headers = GetResponseHeaders() != NULL;
1331
1332  // NOTE: we resend a request only if we reused a keep-alive connection.
1333  // This automatically prevents an infinite resend loop because we'll run
1334  // out of the cached keep-alive connections eventually.
1335  if (connection_is_proven && !has_received_headers)
1336    return true;
1337  return false;
1338}
1339
1340void HttpNetworkTransaction::ResetConnectionAndRequestForResend() {
1341  if (stream_.get()) {
1342    stream_->Close(true);
1343    stream_.reset();
1344  }
1345
1346  // We need to clear request_headers_ because it contains the real request
1347  // headers, but we may need to resend the CONNECT request first to recreate
1348  // the SSL tunnel.
1349  request_headers_.Clear();
1350  next_state_ = STATE_CREATE_STREAM;  // Resend the request.
1351}
1352
1353bool HttpNetworkTransaction::ShouldApplyProxyAuth() const {
1354  return !is_https_request() &&
1355      (proxy_info_.is_https() || proxy_info_.is_http());
1356}
1357
1358bool HttpNetworkTransaction::ShouldApplyServerAuth() const {
1359  return !(request_->load_flags & LOAD_DO_NOT_SEND_AUTH_DATA);
1360}
1361
1362int HttpNetworkTransaction::HandleAuthChallenge() {
1363  scoped_refptr<HttpResponseHeaders> headers(GetResponseHeaders());
1364  DCHECK(headers);
1365
1366  int status = headers->response_code();
1367  if (status != HTTP_UNAUTHORIZED &&
1368      status != HTTP_PROXY_AUTHENTICATION_REQUIRED)
1369    return OK;
1370  HttpAuth::Target target = status == HTTP_PROXY_AUTHENTICATION_REQUIRED ?
1371                            HttpAuth::AUTH_PROXY : HttpAuth::AUTH_SERVER;
1372  if (target == HttpAuth::AUTH_PROXY && proxy_info_.is_direct())
1373    return ERR_UNEXPECTED_PROXY_AUTH;
1374
1375  // This case can trigger when an HTTPS server responds with a "Proxy
1376  // authentication required" status code through a non-authenticating
1377  // proxy.
1378  if (!auth_controllers_[target].get())
1379    return ERR_UNEXPECTED_PROXY_AUTH;
1380
1381  int rv = auth_controllers_[target]->HandleAuthChallenge(
1382      headers, (request_->load_flags & LOAD_DO_NOT_SEND_AUTH_DATA) != 0, false,
1383      net_log_);
1384  if (auth_controllers_[target]->HaveAuthHandler())
1385      pending_auth_target_ = target;
1386
1387  scoped_refptr<AuthChallengeInfo> auth_info =
1388      auth_controllers_[target]->auth_info();
1389  if (auth_info.get())
1390      response_.auth_challenge = auth_info;
1391
1392  return rv;
1393}
1394
1395bool HttpNetworkTransaction::HaveAuth(HttpAuth::Target target) const {
1396  return auth_controllers_[target].get() &&
1397      auth_controllers_[target]->HaveAuth();
1398}
1399
1400GURL HttpNetworkTransaction::AuthURL(HttpAuth::Target target) const {
1401  switch (target) {
1402    case HttpAuth::AUTH_PROXY: {
1403      if (!proxy_info_.proxy_server().is_valid() ||
1404          proxy_info_.proxy_server().is_direct()) {
1405        return GURL();  // There is no proxy server.
1406      }
1407      const char* scheme = proxy_info_.is_https() ? "https://" : "http://";
1408      return GURL(scheme +
1409                  proxy_info_.proxy_server().host_port_pair().ToString());
1410    }
1411    case HttpAuth::AUTH_SERVER:
1412      return request_->url;
1413    default:
1414     return GURL();
1415  }
1416}
1417
1418#define STATE_CASE(s) \
1419  case s: \
1420    description = base::StringPrintf("%s (0x%08X)", #s, s); \
1421    break
1422
1423std::string HttpNetworkTransaction::DescribeState(State state) {
1424  std::string description;
1425  switch (state) {
1426    STATE_CASE(STATE_CREATE_STREAM);
1427    STATE_CASE(STATE_CREATE_STREAM_COMPLETE);
1428    STATE_CASE(STATE_INIT_REQUEST_BODY);
1429    STATE_CASE(STATE_INIT_REQUEST_BODY_COMPLETE);
1430    STATE_CASE(STATE_BUILD_REQUEST);
1431    STATE_CASE(STATE_BUILD_REQUEST_COMPLETE);
1432    STATE_CASE(STATE_SEND_REQUEST);
1433    STATE_CASE(STATE_SEND_REQUEST_COMPLETE);
1434    STATE_CASE(STATE_READ_HEADERS);
1435    STATE_CASE(STATE_READ_HEADERS_COMPLETE);
1436    STATE_CASE(STATE_READ_BODY);
1437    STATE_CASE(STATE_READ_BODY_COMPLETE);
1438    STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART);
1439    STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE);
1440    STATE_CASE(STATE_NONE);
1441    default:
1442      description = base::StringPrintf("Unknown state 0x%08X (%u)", state,
1443                                       state);
1444      break;
1445  }
1446  return description;
1447}
1448
1449#undef STATE_CASE
1450
1451}  // namespace net
1452