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