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