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