http_network_transaction.cc revision 868fa2fe829687343ffae624259930155e16dbd8
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_.get());
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.get()) ||
366          response_.ssl_info.cert.get() || response_.cert_request_info.get())
367             ? &response_
368             : NULL;
369}
370
371LoadState HttpNetworkTransaction::GetLoadState() const {
372  // TODO(wtc): Define a new LoadState value for the
373  // STATE_INIT_CONNECTION_COMPLETE state, which delays the HTTP request.
374  switch (next_state_) {
375    case STATE_CREATE_STREAM_COMPLETE:
376      return stream_request_->GetLoadState();
377    case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
378    case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE:
379    case STATE_SEND_REQUEST_COMPLETE:
380      return LOAD_STATE_SENDING_REQUEST;
381    case STATE_READ_HEADERS_COMPLETE:
382      return LOAD_STATE_WAITING_FOR_RESPONSE;
383    case STATE_READ_BODY_COMPLETE:
384      return LOAD_STATE_READING_RESPONSE;
385    default:
386      return LOAD_STATE_IDLE;
387  }
388}
389
390UploadProgress HttpNetworkTransaction::GetUploadProgress() const {
391  if (!stream_.get())
392    return UploadProgress();
393
394  // TODO(bashi): This cast is temporary. Remove later.
395  return static_cast<HttpStream*>(stream_.get())->GetUploadProgress();
396}
397
398bool HttpNetworkTransaction::GetLoadTimingInfo(
399    LoadTimingInfo* load_timing_info) const {
400  if (!stream_ || !stream_->GetLoadTimingInfo(load_timing_info))
401    return false;
402
403  load_timing_info->proxy_resolve_start =
404      proxy_info_.proxy_resolve_start_time();
405  load_timing_info->proxy_resolve_end = proxy_info_.proxy_resolve_end_time();
406  load_timing_info->send_start = send_start_time_;
407  load_timing_info->send_end = send_end_time_;
408  return true;
409}
410
411void HttpNetworkTransaction::SetPriority(RequestPriority priority) {
412  priority_ = priority;
413  // TODO(akalin): Plumb this through to |stream_request_| and
414  // |stream_|.
415}
416
417void HttpNetworkTransaction::OnStreamReady(const SSLConfig& used_ssl_config,
418                                           const ProxyInfo& used_proxy_info,
419                                           HttpStreamBase* stream) {
420  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
421  DCHECK(stream_request_.get());
422
423  stream_.reset(stream);
424  server_ssl_config_ = used_ssl_config;
425  proxy_info_ = used_proxy_info;
426  response_.was_npn_negotiated = stream_request_->was_npn_negotiated();
427  response_.npn_negotiated_protocol = SSLClientSocket::NextProtoToString(
428      stream_request_->protocol_negotiated());
429  response_.was_fetched_via_spdy = stream_request_->using_spdy();
430  response_.was_fetched_via_proxy = !proxy_info_.is_direct();
431
432  OnIOComplete(OK);
433}
434
435void HttpNetworkTransaction::OnStreamFailed(int result,
436                                            const SSLConfig& used_ssl_config) {
437  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
438  DCHECK_NE(OK, result);
439  DCHECK(stream_request_.get());
440  DCHECK(!stream_.get());
441  server_ssl_config_ = used_ssl_config;
442
443  OnIOComplete(result);
444}
445
446void HttpNetworkTransaction::OnCertificateError(
447    int result,
448    const SSLConfig& used_ssl_config,
449    const SSLInfo& ssl_info) {
450  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
451  DCHECK_NE(OK, result);
452  DCHECK(stream_request_.get());
453  DCHECK(!stream_.get());
454
455  response_.ssl_info = ssl_info;
456  server_ssl_config_ = used_ssl_config;
457
458  // TODO(mbelshe):  For now, we're going to pass the error through, and that
459  // will close the stream_request in all cases.  This means that we're always
460  // going to restart an entire STATE_CREATE_STREAM, even if the connection is
461  // good and the user chooses to ignore the error.  This is not ideal, but not
462  // the end of the world either.
463
464  OnIOComplete(result);
465}
466
467void HttpNetworkTransaction::OnNeedsProxyAuth(
468    const HttpResponseInfo& proxy_response,
469    const SSLConfig& used_ssl_config,
470    const ProxyInfo& used_proxy_info,
471    HttpAuthController* auth_controller) {
472  DCHECK(stream_request_.get());
473  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
474
475  establishing_tunnel_ = true;
476  response_.headers = proxy_response.headers;
477  response_.auth_challenge = proxy_response.auth_challenge;
478  headers_valid_ = true;
479  server_ssl_config_ = used_ssl_config;
480  proxy_info_ = used_proxy_info;
481
482  auth_controllers_[HttpAuth::AUTH_PROXY] = auth_controller;
483  pending_auth_target_ = HttpAuth::AUTH_PROXY;
484
485  DoCallback(OK);
486}
487
488void HttpNetworkTransaction::OnNeedsClientAuth(
489    const SSLConfig& used_ssl_config,
490    SSLCertRequestInfo* cert_info) {
491  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
492
493  server_ssl_config_ = used_ssl_config;
494  response_.cert_request_info = cert_info;
495  OnIOComplete(ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
496}
497
498void HttpNetworkTransaction::OnHttpsProxyTunnelResponse(
499    const HttpResponseInfo& response_info,
500    const SSLConfig& used_ssl_config,
501    const ProxyInfo& used_proxy_info,
502    HttpStreamBase* stream) {
503  DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
504
505  headers_valid_ = true;
506  response_ = response_info;
507  server_ssl_config_ = used_ssl_config;
508  proxy_info_ = used_proxy_info;
509  stream_.reset(stream);
510  stream_request_.reset();  // we're done with the stream request
511  OnIOComplete(ERR_HTTPS_PROXY_TUNNEL_RESPONSE);
512}
513
514bool HttpNetworkTransaction::is_https_request() const {
515  return request_->url.SchemeIs("https");
516}
517
518void HttpNetworkTransaction::DoCallback(int rv) {
519  DCHECK_NE(rv, ERR_IO_PENDING);
520  DCHECK(!callback_.is_null());
521
522  // Since Run may result in Read being called, clear user_callback_ up front.
523  CompletionCallback c = callback_;
524  callback_.Reset();
525  c.Run(rv);
526}
527
528void HttpNetworkTransaction::OnIOComplete(int result) {
529  int rv = DoLoop(result);
530  if (rv != ERR_IO_PENDING)
531    DoCallback(rv);
532}
533
534int HttpNetworkTransaction::DoLoop(int result) {
535  DCHECK(next_state_ != STATE_NONE);
536
537  int rv = result;
538  do {
539    State state = next_state_;
540    next_state_ = STATE_NONE;
541    switch (state) {
542      case STATE_CREATE_STREAM:
543        DCHECK_EQ(OK, rv);
544        rv = DoCreateStream();
545        break;
546      case STATE_CREATE_STREAM_COMPLETE:
547        rv = DoCreateStreamComplete(rv);
548        break;
549      case STATE_INIT_STREAM:
550        DCHECK_EQ(OK, rv);
551        rv = DoInitStream();
552        break;
553      case STATE_INIT_STREAM_COMPLETE:
554        rv = DoInitStreamComplete(rv);
555        break;
556      case STATE_GENERATE_PROXY_AUTH_TOKEN:
557        DCHECK_EQ(OK, rv);
558        rv = DoGenerateProxyAuthToken();
559        break;
560      case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
561        rv = DoGenerateProxyAuthTokenComplete(rv);
562        break;
563      case STATE_GENERATE_SERVER_AUTH_TOKEN:
564        DCHECK_EQ(OK, rv);
565        rv = DoGenerateServerAuthToken();
566        break;
567      case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE:
568        rv = DoGenerateServerAuthTokenComplete(rv);
569        break;
570      case STATE_INIT_REQUEST_BODY:
571        DCHECK_EQ(OK, rv);
572        rv = DoInitRequestBody();
573        break;
574      case STATE_INIT_REQUEST_BODY_COMPLETE:
575        rv = DoInitRequestBodyComplete(rv);
576        break;
577      case STATE_BUILD_REQUEST:
578        DCHECK_EQ(OK, rv);
579        net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST);
580        rv = DoBuildRequest();
581        break;
582      case STATE_BUILD_REQUEST_COMPLETE:
583        rv = DoBuildRequestComplete(rv);
584        break;
585      case STATE_SEND_REQUEST:
586        DCHECK_EQ(OK, rv);
587        rv = DoSendRequest();
588        break;
589      case STATE_SEND_REQUEST_COMPLETE:
590        rv = DoSendRequestComplete(rv);
591        net_log_.EndEventWithNetErrorCode(
592            NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST, rv);
593        break;
594      case STATE_READ_HEADERS:
595        DCHECK_EQ(OK, rv);
596        net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS);
597        rv = DoReadHeaders();
598        break;
599      case STATE_READ_HEADERS_COMPLETE:
600        rv = DoReadHeadersComplete(rv);
601        net_log_.EndEventWithNetErrorCode(
602            NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS, rv);
603        break;
604      case STATE_READ_BODY:
605        DCHECK_EQ(OK, rv);
606        net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_BODY);
607        rv = DoReadBody();
608        break;
609      case STATE_READ_BODY_COMPLETE:
610        rv = DoReadBodyComplete(rv);
611        net_log_.EndEventWithNetErrorCode(
612            NetLog::TYPE_HTTP_TRANSACTION_READ_BODY, rv);
613        break;
614      case STATE_DRAIN_BODY_FOR_AUTH_RESTART:
615        DCHECK_EQ(OK, rv);
616        net_log_.BeginEvent(
617            NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART);
618        rv = DoDrainBodyForAuthRestart();
619        break;
620      case STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE:
621        rv = DoDrainBodyForAuthRestartComplete(rv);
622        net_log_.EndEventWithNetErrorCode(
623            NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART, rv);
624        break;
625      default:
626        NOTREACHED() << "bad state";
627        rv = ERR_FAILED;
628        break;
629    }
630  } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
631
632  return rv;
633}
634
635int HttpNetworkTransaction::DoCreateStream() {
636  next_state_ = STATE_CREATE_STREAM_COMPLETE;
637
638  stream_request_.reset(
639      session_->http_stream_factory()->RequestStream(
640          *request_,
641          priority_,
642          server_ssl_config_,
643          proxy_ssl_config_,
644          this,
645          net_log_));
646  DCHECK(stream_request_.get());
647  return ERR_IO_PENDING;
648}
649
650int HttpNetworkTransaction::DoCreateStreamComplete(int result) {
651  if (result == OK) {
652    next_state_ = STATE_INIT_STREAM;
653    DCHECK(stream_.get());
654  } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
655    result = HandleCertificateRequest(result);
656  } else if (result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
657    // Return OK and let the caller read the proxy's error page
658    next_state_ = STATE_NONE;
659    return OK;
660  }
661
662  // Handle possible handshake errors that may have occurred if the stream
663  // used SSL for one or more of the layers.
664  result = HandleSSLHandshakeError(result);
665
666  // At this point we are done with the stream_request_.
667  stream_request_.reset();
668  return result;
669}
670
671int HttpNetworkTransaction::DoInitStream() {
672  DCHECK(stream_.get());
673  next_state_ = STATE_INIT_STREAM_COMPLETE;
674  return stream_->InitializeStream(request_, priority_, net_log_, io_callback_);
675}
676
677int HttpNetworkTransaction::DoInitStreamComplete(int result) {
678  if (result == OK) {
679    next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
680  } else {
681    if (result < 0)
682      result = HandleIOError(result);
683
684    // The stream initialization failed, so this stream will never be useful.
685    stream_.reset();
686  }
687
688  return result;
689}
690
691int HttpNetworkTransaction::DoGenerateProxyAuthToken() {
692  next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE;
693  if (!ShouldApplyProxyAuth())
694    return OK;
695  HttpAuth::Target target = HttpAuth::AUTH_PROXY;
696  if (!auth_controllers_[target].get())
697    auth_controllers_[target] =
698        new HttpAuthController(target,
699                               AuthURL(target),
700                               session_->http_auth_cache(),
701                               session_->http_auth_handler_factory());
702  return auth_controllers_[target]->MaybeGenerateAuthToken(request_,
703                                                           io_callback_,
704                                                           net_log_);
705}
706
707int HttpNetworkTransaction::DoGenerateProxyAuthTokenComplete(int rv) {
708  DCHECK_NE(ERR_IO_PENDING, rv);
709  if (rv == OK)
710    next_state_ = STATE_GENERATE_SERVER_AUTH_TOKEN;
711  return rv;
712}
713
714int HttpNetworkTransaction::DoGenerateServerAuthToken() {
715  next_state_ = STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE;
716  HttpAuth::Target target = HttpAuth::AUTH_SERVER;
717  if (!auth_controllers_[target].get())
718    auth_controllers_[target] =
719        new HttpAuthController(target,
720                               AuthURL(target),
721                               session_->http_auth_cache(),
722                               session_->http_auth_handler_factory());
723  if (!ShouldApplyServerAuth())
724    return OK;
725  return auth_controllers_[target]->MaybeGenerateAuthToken(request_,
726                                                           io_callback_,
727                                                           net_log_);
728}
729
730int HttpNetworkTransaction::DoGenerateServerAuthTokenComplete(int rv) {
731  DCHECK_NE(ERR_IO_PENDING, rv);
732  if (rv == OK)
733    next_state_ = STATE_INIT_REQUEST_BODY;
734  return rv;
735}
736
737void HttpNetworkTransaction::BuildRequestHeaders(bool using_proxy) {
738  request_headers_.SetHeader(HttpRequestHeaders::kHost,
739                             GetHostAndOptionalPort(request_->url));
740
741  // For compat with HTTP/1.0 servers and proxies:
742  if (using_proxy) {
743    request_headers_.SetHeader(HttpRequestHeaders::kProxyConnection,
744                               "keep-alive");
745  } else {
746    request_headers_.SetHeader(HttpRequestHeaders::kConnection, "keep-alive");
747  }
748
749  // Add a content length header?
750  if (request_->upload_data_stream) {
751    if (request_->upload_data_stream->is_chunked()) {
752      request_headers_.SetHeader(
753          HttpRequestHeaders::kTransferEncoding, "chunked");
754    } else {
755      request_headers_.SetHeader(
756          HttpRequestHeaders::kContentLength,
757          base::Uint64ToString(request_->upload_data_stream->size()));
758    }
759  } else if (request_->method == "POST" || request_->method == "PUT" ||
760             request_->method == "HEAD") {
761    // An empty POST/PUT request still needs a content length.  As for HEAD,
762    // IE and Safari also add a content length header.  Presumably it is to
763    // support sending a HEAD request to an URL that only expects to be sent a
764    // POST or some other method that normally would have a message body.
765    request_headers_.SetHeader(HttpRequestHeaders::kContentLength, "0");
766  }
767
768  // Honor load flags that impact proxy caches.
769  if (request_->load_flags & LOAD_BYPASS_CACHE) {
770    request_headers_.SetHeader(HttpRequestHeaders::kPragma, "no-cache");
771    request_headers_.SetHeader(HttpRequestHeaders::kCacheControl, "no-cache");
772  } else if (request_->load_flags & LOAD_VALIDATE_CACHE) {
773    request_headers_.SetHeader(HttpRequestHeaders::kCacheControl, "max-age=0");
774  }
775
776  if (ShouldApplyProxyAuth() && HaveAuth(HttpAuth::AUTH_PROXY))
777    auth_controllers_[HttpAuth::AUTH_PROXY]->AddAuthorizationHeader(
778        &request_headers_);
779  if (ShouldApplyServerAuth() && HaveAuth(HttpAuth::AUTH_SERVER))
780    auth_controllers_[HttpAuth::AUTH_SERVER]->AddAuthorizationHeader(
781        &request_headers_);
782
783  request_headers_.MergeFrom(request_->extra_headers);
784  response_.did_use_http_auth =
785      request_headers_.HasHeader(HttpRequestHeaders::kAuthorization) ||
786      request_headers_.HasHeader(HttpRequestHeaders::kProxyAuthorization);
787}
788
789int HttpNetworkTransaction::DoInitRequestBody() {
790  next_state_ = STATE_INIT_REQUEST_BODY_COMPLETE;
791  int rv = OK;
792  if (request_->upload_data_stream)
793    rv = request_->upload_data_stream->Init(io_callback_);
794  return rv;
795}
796
797int HttpNetworkTransaction::DoInitRequestBodyComplete(int result) {
798  if (result == OK)
799    next_state_ = STATE_BUILD_REQUEST;
800  return result;
801}
802
803int HttpNetworkTransaction::DoBuildRequest() {
804  next_state_ = STATE_BUILD_REQUEST_COMPLETE;
805  headers_valid_ = false;
806
807  // This is constructed lazily (instead of within our Start method), so that
808  // we have proxy info available.
809  if (request_headers_.IsEmpty()) {
810    bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
811                        !is_https_request();
812    BuildRequestHeaders(using_proxy);
813  }
814
815  return OK;
816}
817
818int HttpNetworkTransaction::DoBuildRequestComplete(int result) {
819  if (result == OK)
820    next_state_ = STATE_SEND_REQUEST;
821  return result;
822}
823
824int HttpNetworkTransaction::DoSendRequest() {
825  send_start_time_ = base::TimeTicks::Now();
826  next_state_ = STATE_SEND_REQUEST_COMPLETE;
827
828  return stream_->SendRequest(request_headers_, &response_, io_callback_);
829}
830
831int HttpNetworkTransaction::DoSendRequestComplete(int result) {
832  send_end_time_ = base::TimeTicks::Now();
833  if (result < 0)
834    return HandleIOError(result);
835  response_.network_accessed = true;
836  next_state_ = STATE_READ_HEADERS;
837  return OK;
838}
839
840int HttpNetworkTransaction::DoReadHeaders() {
841  next_state_ = STATE_READ_HEADERS_COMPLETE;
842  return stream_->ReadResponseHeaders(io_callback_);
843}
844
845int HttpNetworkTransaction::HandleConnectionClosedBeforeEndOfHeaders() {
846  if (!response_.headers.get() && !stream_->IsConnectionReused()) {
847    // The connection was closed before any data was sent. Likely an error
848    // rather than empty HTTP/0.9 response.
849    return ERR_EMPTY_RESPONSE;
850  }
851
852  return OK;
853}
854
855int HttpNetworkTransaction::DoReadHeadersComplete(int result) {
856  // We can get a certificate error or ERR_SSL_CLIENT_AUTH_CERT_NEEDED here
857  // due to SSL renegotiation.
858  if (IsCertificateError(result)) {
859    // We don't handle a certificate error during SSL renegotiation, so we
860    // have to return an error that's not in the certificate error range
861    // (-2xx).
862    LOG(ERROR) << "Got a server certificate with error " << result
863               << " during SSL renegotiation";
864    result = ERR_CERT_ERROR_IN_SSL_RENEGOTIATION;
865  } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
866    // TODO(wtc): Need a test case for this code path!
867    DCHECK(stream_.get());
868    DCHECK(is_https_request());
869    response_.cert_request_info = new SSLCertRequestInfo;
870    stream_->GetSSLCertRequestInfo(response_.cert_request_info.get());
871    result = HandleCertificateRequest(result);
872    if (result == OK)
873      return result;
874  }
875
876  if (result < 0 && result != ERR_CONNECTION_CLOSED)
877    return HandleIOError(result);
878
879  if (result == ERR_CONNECTION_CLOSED && ShouldResendRequest(result)) {
880    ResetConnectionAndRequestForResend();
881    return OK;
882  }
883
884  // After we call RestartWithAuth a new response_time will be recorded, and
885  // we need to be cautious about incorrectly logging the duration across the
886  // authentication activity.
887  if (result == OK)
888    LogTransactionConnectedMetrics();
889
890  if (result == ERR_CONNECTION_CLOSED) {
891    // For now, if we get at least some data, we do the best we can to make
892    // sense of it and send it back up the stack.
893    int rv = HandleConnectionClosedBeforeEndOfHeaders();
894    if (rv != OK)
895      return rv;
896  }
897  DCHECK(response_.headers.get());
898
899  // Server-induced fallback is supported only if this is a PAC configured
900  // proxy. See: http://crbug.com/143712
901  if (response_.was_fetched_via_proxy && proxy_info_.did_use_pac_script() &&
902      response_.headers.get() != NULL) {
903    bool should_fallback =
904        response_.headers->HasHeaderValue("connection", "proxy-bypass");
905    // Additionally, fallback if a 500 is returned via the data reduction proxy.
906    // This is conservative, as the 500 might have been generated by the origin,
907    // and not the proxy.
908#if defined(SPDY_PROXY_AUTH_ORIGIN)
909    if (!should_fallback) {
910      should_fallback =
911          response_.headers->response_code() == HTTP_INTERNAL_SERVER_ERROR &&
912          proxy_info_.proxy_server().host_port_pair().Equals(
913              HostPortPair::FromURL(GURL(SPDY_PROXY_AUTH_ORIGIN)));
914    }
915#endif
916    if (should_fallback) {
917      ProxyService* proxy_service = session_->proxy_service();
918      if (proxy_service->MarkProxyAsBad(proxy_info_, net_log_)) {
919        // Only retry in the case of GETs. We don't want to resubmit a POST
920        // if the proxy took some action.
921        if (request_->method == "GET") {
922          ResetConnectionAndRequestForResend();
923          return OK;
924        }
925      }
926    }
927  }
928
929  // Like Net.HttpResponseCode, but only for MAIN_FRAME loads.
930  if (request_->load_flags & LOAD_MAIN_FRAME) {
931    const int response_code = response_.headers->response_code();
932    UMA_HISTOGRAM_ENUMERATION(
933        "Net.HttpResponseCode_Nxx_MainFrame", response_code/100, 10);
934  }
935
936  net_log_.AddEvent(
937      NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS,
938      base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers));
939
940  if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0)) {
941    // HTTP/0.9 doesn't support the PUT method, so lack of response headers
942    // indicates a buggy server.  See:
943    // https://bugzilla.mozilla.org/show_bug.cgi?id=193921
944    if (request_->method == "PUT")
945      return ERR_METHOD_NOT_SUPPORTED;
946  }
947
948  // Check for an intermediate 100 Continue response.  An origin server is
949  // allowed to send this response even if we didn't ask for it, so we just
950  // need to skip over it.
951  // We treat any other 1xx in this same way (although in practice getting
952  // a 1xx that isn't a 100 is rare).
953  if (response_.headers->response_code() / 100 == 1) {
954    response_.headers = new HttpResponseHeaders(std::string());
955    next_state_ = STATE_READ_HEADERS;
956    return OK;
957  }
958
959  HostPortPair endpoint = HostPortPair(request_->url.HostNoBrackets(),
960                                       request_->url.EffectiveIntPort());
961  ProcessAlternateProtocol(session_->http_stream_factory(),
962                           session_->http_server_properties(),
963                           *response_.headers.get(),
964                           endpoint);
965
966  int rv = HandleAuthChallenge();
967  if (rv != OK)
968    return rv;
969
970  if (is_https_request())
971    stream_->GetSSLInfo(&response_.ssl_info);
972
973  headers_valid_ = true;
974  return OK;
975}
976
977int HttpNetworkTransaction::DoReadBody() {
978  DCHECK(read_buf_.get());
979  DCHECK_GT(read_buf_len_, 0);
980  DCHECK(stream_ != NULL);
981
982  next_state_ = STATE_READ_BODY_COMPLETE;
983  return stream_->ReadResponseBody(
984      read_buf_.get(), read_buf_len_, io_callback_);
985}
986
987int HttpNetworkTransaction::DoReadBodyComplete(int result) {
988  // We are done with the Read call.
989  bool done = false;
990  if (result <= 0) {
991    DCHECK_NE(ERR_IO_PENDING, result);
992    done = true;
993  }
994
995  bool keep_alive = false;
996  if (stream_->IsResponseBodyComplete()) {
997    // Note: Just because IsResponseBodyComplete is true, we're not
998    // necessarily "done".  We're only "done" when it is the last
999    // read on this HttpNetworkTransaction, which will be signified
1000    // by a zero-length read.
1001    // TODO(mbelshe): The keepalive property is really a property of
1002    //    the stream.  No need to compute it here just to pass back
1003    //    to the stream's Close function.
1004    // TODO(rtenneti): CanFindEndOfResponse should return false if there are no
1005    // ResponseHeaders.
1006    if (stream_->CanFindEndOfResponse()) {
1007      HttpResponseHeaders* headers = GetResponseHeaders();
1008      if (headers)
1009        keep_alive = headers->IsKeepAlive();
1010    }
1011  }
1012
1013  // Clean up connection if we are done.
1014  if (done) {
1015    LogTransactionMetrics();
1016    stream_->Close(!keep_alive);
1017    // Note: we don't reset the stream here.  We've closed it, but we still
1018    // need it around so that callers can call methods such as
1019    // GetUploadProgress() and have them be meaningful.
1020    // TODO(mbelshe): This means we closed the stream here, and we close it
1021    // again in ~HttpNetworkTransaction.  Clean that up.
1022
1023    // The next Read call will return 0 (EOF).
1024  }
1025
1026  // Clear these to avoid leaving around old state.
1027  read_buf_ = NULL;
1028  read_buf_len_ = 0;
1029
1030  return result;
1031}
1032
1033int HttpNetworkTransaction::DoDrainBodyForAuthRestart() {
1034  // This method differs from DoReadBody only in the next_state_.  So we just
1035  // call DoReadBody and override the next_state_.  Perhaps there is a more
1036  // elegant way for these two methods to share code.
1037  int rv = DoReadBody();
1038  DCHECK(next_state_ == STATE_READ_BODY_COMPLETE);
1039  next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE;
1040  return rv;
1041}
1042
1043// TODO(wtc): This method and the DoReadBodyComplete method are almost
1044// the same.  Figure out a good way for these two methods to share code.
1045int HttpNetworkTransaction::DoDrainBodyForAuthRestartComplete(int result) {
1046  // keep_alive defaults to true because the very reason we're draining the
1047  // response body is to reuse the connection for auth restart.
1048  bool done = false, keep_alive = true;
1049  if (result < 0) {
1050    // Error or closed connection while reading the socket.
1051    done = true;
1052    keep_alive = false;
1053  } else if (stream_->IsResponseBodyComplete()) {
1054    done = true;
1055  }
1056
1057  if (done) {
1058    DidDrainBodyForAuthRestart(keep_alive);
1059  } else {
1060    // Keep draining.
1061    next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
1062  }
1063
1064  return OK;
1065}
1066
1067void HttpNetworkTransaction::LogTransactionConnectedMetrics() {
1068  if (logged_response_time_)
1069    return;
1070
1071  logged_response_time_ = true;
1072
1073  base::TimeDelta total_duration = response_.response_time - start_time_;
1074
1075  UMA_HISTOGRAM_CUSTOM_TIMES(
1076      "Net.Transaction_Connected",
1077      total_duration,
1078      base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1079      100);
1080
1081  bool reused_socket = stream_->IsConnectionReused();
1082  if (!reused_socket) {
1083    UMA_HISTOGRAM_CUSTOM_TIMES(
1084        "Net.Transaction_Connected_New_b",
1085        total_duration,
1086        base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1087        100);
1088  }
1089
1090  // Currently, non-HIGHEST priority requests are frame or sub-frame resource
1091  // types.  This will change when we also prioritize certain subresources like
1092  // css, js, etc.
1093  if (priority_ != HIGHEST) {
1094    UMA_HISTOGRAM_CUSTOM_TIMES(
1095        "Net.Priority_High_Latency_b",
1096        total_duration,
1097        base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1098        100);
1099  } else {
1100    UMA_HISTOGRAM_CUSTOM_TIMES(
1101        "Net.Priority_Low_Latency_b",
1102        total_duration,
1103        base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1104        100);
1105  }
1106}
1107
1108void HttpNetworkTransaction::LogTransactionMetrics() const {
1109  base::TimeDelta duration = base::Time::Now() -
1110                             response_.request_time;
1111  if (60 < duration.InMinutes())
1112    return;
1113
1114  base::TimeDelta total_duration = base::Time::Now() - start_time_;
1115
1116  UMA_HISTOGRAM_CUSTOM_TIMES("Net.Transaction_Latency_b", duration,
1117                             base::TimeDelta::FromMilliseconds(1),
1118                             base::TimeDelta::FromMinutes(10),
1119                             100);
1120  UMA_HISTOGRAM_CUSTOM_TIMES("Net.Transaction_Latency_Total",
1121                             total_duration,
1122                             base::TimeDelta::FromMilliseconds(1),
1123                             base::TimeDelta::FromMinutes(10), 100);
1124
1125  if (!stream_->IsConnectionReused()) {
1126    UMA_HISTOGRAM_CUSTOM_TIMES(
1127        "Net.Transaction_Latency_Total_New_Connection",
1128        total_duration, base::TimeDelta::FromMilliseconds(1),
1129        base::TimeDelta::FromMinutes(10), 100);
1130  }
1131}
1132
1133int HttpNetworkTransaction::HandleCertificateRequest(int error) {
1134  // There are two paths through which the server can request a certificate
1135  // from us.  The first is during the initial handshake, the second is
1136  // during SSL renegotiation.
1137  //
1138  // In both cases, we want to close the connection before proceeding.
1139  // We do this for two reasons:
1140  //   First, we don't want to keep the connection to the server hung for a
1141  //   long time while the user selects a certificate.
1142  //   Second, even if we did keep the connection open, NSS has a bug where
1143  //   restarting the handshake for ClientAuth is currently broken.
1144  DCHECK_EQ(error, ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
1145
1146  if (stream_.get()) {
1147    // Since we already have a stream, we're being called as part of SSL
1148    // renegotiation.
1149    DCHECK(!stream_request_.get());
1150    stream_->Close(true);
1151    stream_.reset();
1152  }
1153
1154  // The server is asking for a client certificate during the initial
1155  // handshake.
1156  stream_request_.reset();
1157
1158  // If the user selected one of the certificates in client_certs or declined
1159  // to provide one for this server before, use the past decision
1160  // automatically.
1161  scoped_refptr<X509Certificate> client_cert;
1162  bool found_cached_cert = session_->ssl_client_auth_cache()->Lookup(
1163      response_.cert_request_info->host_and_port, &client_cert);
1164  if (!found_cached_cert)
1165    return error;
1166
1167  // Check that the certificate selected is still a certificate the server
1168  // is likely to accept, based on the criteria supplied in the
1169  // CertificateRequest message.
1170  if (client_cert.get()) {
1171    const std::vector<std::string>& cert_authorities =
1172        response_.cert_request_info->cert_authorities;
1173
1174    bool cert_still_valid = cert_authorities.empty() ||
1175        client_cert->IsIssuedByEncoded(cert_authorities);
1176    if (!cert_still_valid)
1177      return error;
1178  }
1179
1180  // TODO(davidben): Add a unit test which covers this path; we need to be
1181  // able to send a legitimate certificate and also bypass/clear the
1182  // SSL session cache.
1183  SSLConfig* ssl_config = response_.cert_request_info->is_proxy ?
1184      &proxy_ssl_config_ : &server_ssl_config_;
1185  ssl_config->send_client_cert = true;
1186  ssl_config->client_cert = client_cert;
1187  next_state_ = STATE_CREATE_STREAM;
1188  // Reset the other member variables.
1189  // Note: this is necessary only with SSL renegotiation.
1190  ResetStateForRestart();
1191  return OK;
1192}
1193
1194// TODO(rch): This does not correctly handle errors when an SSL proxy is
1195// being used, as all of the errors are handled as if they were generated
1196// by the endpoint host, request_->url, rather than considering if they were
1197// generated by the SSL proxy. http://crbug.com/69329
1198int HttpNetworkTransaction::HandleSSLHandshakeError(int error) {
1199  DCHECK(request_);
1200  if (server_ssl_config_.send_client_cert &&
1201      (error == ERR_SSL_PROTOCOL_ERROR || IsClientCertificateError(error))) {
1202    session_->ssl_client_auth_cache()->Remove(
1203        GetHostAndPort(request_->url));
1204  }
1205
1206  uint16 version_max = server_ssl_config_.version_max;
1207
1208  switch (error) {
1209    case ERR_SSL_PROTOCOL_ERROR:
1210    case ERR_SSL_VERSION_OR_CIPHER_MISMATCH:
1211      if (version_max >= SSL_PROTOCOL_VERSION_TLS1 &&
1212          version_max > server_ssl_config_.version_min) {
1213        // This could be a TLS-intolerant server or a server that chose a
1214        // cipher suite defined only for higher protocol versions (such as
1215        // an SSL 3.0 server that chose a TLS-only cipher suite).  Fall
1216        // back to the next lower version and retry.
1217        // NOTE: if the SSLClientSocket class doesn't support TLS 1.1,
1218        // specifying TLS 1.1 in version_max will result in a TLS 1.0
1219        // handshake, so falling back from TLS 1.1 to TLS 1.0 will simply
1220        // repeat the TLS 1.0 handshake. To avoid this problem, the default
1221        // version_max should match the maximum protocol version supported
1222        // by the SSLClientSocket class.
1223        version_max--;
1224
1225        // Fallback to the lower SSL version.
1226        // While SSL 3.0 fallback should be eliminated because of security
1227        // reasons, there is a high risk of breaking the servers if this is
1228        // done in general.
1229        // For now SSL 3.0 fallback is disabled for Google servers first,
1230        // and will be expanded to other servers after enough experiences
1231        // have been gained showing that this experiment works well with
1232        // today's Internet.
1233        if (version_max > SSL_PROTOCOL_VERSION_SSL3 ||
1234            (server_ssl_config_.unrestricted_ssl3_fallback_enabled ||
1235             !TransportSecurityState::IsGooglePinnedProperty(
1236                 request_->url.host(), true /* include SNI */))) {
1237          net_log_.AddEvent(
1238              NetLog::TYPE_SSL_VERSION_FALLBACK,
1239              base::Bind(&NetLogSSLVersionFallbackCallback,
1240                         &request_->url, error, server_ssl_config_.version_max,
1241                         version_max));
1242          server_ssl_config_.version_max = version_max;
1243          server_ssl_config_.version_fallback = true;
1244          ResetConnectionAndRequestForResend();
1245          error = OK;
1246        }
1247      }
1248      break;
1249  }
1250
1251  return error;
1252}
1253
1254// This method determines whether it is safe to resend the request after an
1255// IO error.  It can only be called in response to request header or body
1256// write errors or response header read errors.  It should not be used in
1257// other cases, such as a Connect error.
1258int HttpNetworkTransaction::HandleIOError(int error) {
1259  // SSL errors may happen at any time during the stream and indicate issues
1260  // with the underlying connection. Because the peer may request
1261  // renegotiation at any time, check and handle any possible SSL handshake
1262  // related errors. In addition to renegotiation, TLS False Start may cause
1263  // SSL handshake errors (specifically servers with buggy DEFLATE support)
1264  // to be delayed until the first Read on the underlying connection.
1265  error = HandleSSLHandshakeError(error);
1266
1267  switch (error) {
1268    // If we try to reuse a connection that the server is in the process of
1269    // closing, we may end up successfully writing out our request (or a
1270    // portion of our request) only to find a connection error when we try to
1271    // read from (or finish writing to) the socket.
1272    case ERR_CONNECTION_RESET:
1273    case ERR_CONNECTION_CLOSED:
1274    case ERR_CONNECTION_ABORTED:
1275    // There can be a race between the socket pool checking checking whether a
1276    // socket is still connected, receiving the FIN, and sending/reading data
1277    // on a reused socket.  If we receive the FIN between the connectedness
1278    // check and writing/reading from the socket, we may first learn the socket
1279    // is disconnected when we get a ERR_SOCKET_NOT_CONNECTED.  This will most
1280    // likely happen when trying to retrieve its IP address.
1281    // See http://crbug.com/105824 for more details.
1282    case ERR_SOCKET_NOT_CONNECTED:
1283      if (ShouldResendRequest(error)) {
1284        net_log_.AddEventWithNetErrorCode(
1285            NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
1286        ResetConnectionAndRequestForResend();
1287        error = OK;
1288      }
1289      break;
1290    case ERR_PIPELINE_EVICTION:
1291      if (!session_->force_http_pipelining()) {
1292        net_log_.AddEventWithNetErrorCode(
1293            NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
1294        ResetConnectionAndRequestForResend();
1295        error = OK;
1296      }
1297      break;
1298    case ERR_SPDY_PING_FAILED:
1299    case ERR_SPDY_SERVER_REFUSED_STREAM:
1300      net_log_.AddEventWithNetErrorCode(
1301          NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
1302      ResetConnectionAndRequestForResend();
1303      error = OK;
1304      break;
1305  }
1306  return error;
1307}
1308
1309void HttpNetworkTransaction::ResetStateForRestart() {
1310  ResetStateForAuthRestart();
1311  stream_.reset();
1312}
1313
1314void HttpNetworkTransaction::ResetStateForAuthRestart() {
1315  send_start_time_ = base::TimeTicks();
1316  send_end_time_ = base::TimeTicks();
1317
1318  pending_auth_target_ = HttpAuth::AUTH_NONE;
1319  read_buf_ = NULL;
1320  read_buf_len_ = 0;
1321  headers_valid_ = false;
1322  request_headers_.Clear();
1323  response_ = HttpResponseInfo();
1324  establishing_tunnel_ = false;
1325}
1326
1327HttpResponseHeaders* HttpNetworkTransaction::GetResponseHeaders() const {
1328  return response_.headers.get();
1329}
1330
1331bool HttpNetworkTransaction::ShouldResendRequest(int error) const {
1332  bool connection_is_proven = stream_->IsConnectionReused();
1333  bool has_received_headers = GetResponseHeaders() != NULL;
1334
1335  // NOTE: we resend a request only if we reused a keep-alive connection.
1336  // This automatically prevents an infinite resend loop because we'll run
1337  // out of the cached keep-alive connections eventually.
1338  if (connection_is_proven && !has_received_headers)
1339    return true;
1340  return false;
1341}
1342
1343void HttpNetworkTransaction::ResetConnectionAndRequestForResend() {
1344  if (stream_.get()) {
1345    stream_->Close(true);
1346    stream_.reset();
1347  }
1348
1349  // We need to clear request_headers_ because it contains the real request
1350  // headers, but we may need to resend the CONNECT request first to recreate
1351  // the SSL tunnel.
1352  request_headers_.Clear();
1353  next_state_ = STATE_CREATE_STREAM;  // Resend the request.
1354}
1355
1356bool HttpNetworkTransaction::ShouldApplyProxyAuth() const {
1357  return !is_https_request() &&
1358      (proxy_info_.is_https() || proxy_info_.is_http());
1359}
1360
1361bool HttpNetworkTransaction::ShouldApplyServerAuth() const {
1362  return !(request_->load_flags & LOAD_DO_NOT_SEND_AUTH_DATA);
1363}
1364
1365int HttpNetworkTransaction::HandleAuthChallenge() {
1366  scoped_refptr<HttpResponseHeaders> headers(GetResponseHeaders());
1367  DCHECK(headers.get());
1368
1369  int status = headers->response_code();
1370  if (status != HTTP_UNAUTHORIZED &&
1371      status != HTTP_PROXY_AUTHENTICATION_REQUIRED)
1372    return OK;
1373  HttpAuth::Target target = status == HTTP_PROXY_AUTHENTICATION_REQUIRED ?
1374                            HttpAuth::AUTH_PROXY : HttpAuth::AUTH_SERVER;
1375  if (target == HttpAuth::AUTH_PROXY && proxy_info_.is_direct())
1376    return ERR_UNEXPECTED_PROXY_AUTH;
1377
1378  // This case can trigger when an HTTPS server responds with a "Proxy
1379  // authentication required" status code through a non-authenticating
1380  // proxy.
1381  if (!auth_controllers_[target].get())
1382    return ERR_UNEXPECTED_PROXY_AUTH;
1383
1384  int rv = auth_controllers_[target]->HandleAuthChallenge(
1385      headers, (request_->load_flags & LOAD_DO_NOT_SEND_AUTH_DATA) != 0, false,
1386      net_log_);
1387  if (auth_controllers_[target]->HaveAuthHandler())
1388      pending_auth_target_ = target;
1389
1390  scoped_refptr<AuthChallengeInfo> auth_info =
1391      auth_controllers_[target]->auth_info();
1392  if (auth_info.get())
1393      response_.auth_challenge = auth_info;
1394
1395  return rv;
1396}
1397
1398bool HttpNetworkTransaction::HaveAuth(HttpAuth::Target target) const {
1399  return auth_controllers_[target].get() &&
1400      auth_controllers_[target]->HaveAuth();
1401}
1402
1403GURL HttpNetworkTransaction::AuthURL(HttpAuth::Target target) const {
1404  switch (target) {
1405    case HttpAuth::AUTH_PROXY: {
1406      if (!proxy_info_.proxy_server().is_valid() ||
1407          proxy_info_.proxy_server().is_direct()) {
1408        return GURL();  // There is no proxy server.
1409      }
1410      const char* scheme = proxy_info_.is_https() ? "https://" : "http://";
1411      return GURL(scheme +
1412                  proxy_info_.proxy_server().host_port_pair().ToString());
1413    }
1414    case HttpAuth::AUTH_SERVER:
1415      return request_->url;
1416    default:
1417     return GURL();
1418  }
1419}
1420
1421#define STATE_CASE(s) \
1422  case s: \
1423    description = base::StringPrintf("%s (0x%08X)", #s, s); \
1424    break
1425
1426std::string HttpNetworkTransaction::DescribeState(State state) {
1427  std::string description;
1428  switch (state) {
1429    STATE_CASE(STATE_CREATE_STREAM);
1430    STATE_CASE(STATE_CREATE_STREAM_COMPLETE);
1431    STATE_CASE(STATE_INIT_REQUEST_BODY);
1432    STATE_CASE(STATE_INIT_REQUEST_BODY_COMPLETE);
1433    STATE_CASE(STATE_BUILD_REQUEST);
1434    STATE_CASE(STATE_BUILD_REQUEST_COMPLETE);
1435    STATE_CASE(STATE_SEND_REQUEST);
1436    STATE_CASE(STATE_SEND_REQUEST_COMPLETE);
1437    STATE_CASE(STATE_READ_HEADERS);
1438    STATE_CASE(STATE_READ_HEADERS_COMPLETE);
1439    STATE_CASE(STATE_READ_BODY);
1440    STATE_CASE(STATE_READ_BODY_COMPLETE);
1441    STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART);
1442    STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE);
1443    STATE_CASE(STATE_NONE);
1444    default:
1445      description = base::StringPrintf("Unknown state 0x%08X (%u)", state,
1446                                       state);
1447      break;
1448  }
1449  return description;
1450}
1451
1452#undef STATE_CASE
1453
1454}  // namespace net
1455