Roll src/third_party/WebKit 8b42d1d:744641d (svn 186770:186771)
[chromium-blink-merge.git] / net / http / http_network_transaction.cc
blobb4ef356df1531babba69f2198a5e639df910d684
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.
5 #include "net/http/http_network_transaction.h"
7 #include <set>
8 #include <vector>
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/profiler/scoped_tracker.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/time/time.h"
24 #include "base/values.h"
25 #include "build/build_config.h"
26 #include "net/base/auth.h"
27 #include "net/base/host_port_pair.h"
28 #include "net/base/io_buffer.h"
29 #include "net/base/load_flags.h"
30 #include "net/base/load_timing_info.h"
31 #include "net/base/net_errors.h"
32 #include "net/base/net_util.h"
33 #include "net/base/upload_data_stream.h"
34 #include "net/http/http_auth.h"
35 #include "net/http/http_auth_handler.h"
36 #include "net/http/http_auth_handler_factory.h"
37 #include "net/http/http_basic_stream.h"
38 #include "net/http/http_chunked_decoder.h"
39 #include "net/http/http_network_session.h"
40 #include "net/http/http_proxy_client_socket.h"
41 #include "net/http/http_proxy_client_socket_pool.h"
42 #include "net/http/http_request_headers.h"
43 #include "net/http/http_request_info.h"
44 #include "net/http/http_response_headers.h"
45 #include "net/http/http_response_info.h"
46 #include "net/http/http_server_properties.h"
47 #include "net/http/http_status_code.h"
48 #include "net/http/http_stream.h"
49 #include "net/http/http_stream_factory.h"
50 #include "net/http/http_util.h"
51 #include "net/http/transport_security_state.h"
52 #include "net/http/url_security_manager.h"
53 #include "net/socket/client_socket_factory.h"
54 #include "net/socket/socks_client_socket_pool.h"
55 #include "net/socket/ssl_client_socket.h"
56 #include "net/socket/ssl_client_socket_pool.h"
57 #include "net/socket/transport_client_socket_pool.h"
58 #include "net/spdy/hpack_huffman_aggregator.h"
59 #include "net/spdy/spdy_http_stream.h"
60 #include "net/spdy/spdy_session.h"
61 #include "net/spdy/spdy_session_pool.h"
62 #include "net/ssl/ssl_cert_request_info.h"
63 #include "net/ssl/ssl_connection_status_flags.h"
64 #include "url/gurl.h"
65 #include "url/url_canon.h"
67 namespace net {
69 namespace {
71 void ProcessAlternateProtocol(
72 HttpNetworkSession* session,
73 const HttpResponseHeaders& headers,
74 const HostPortPair& http_host_port_pair) {
75 if (!headers.HasHeader(kAlternateProtocolHeader))
76 return;
78 std::vector<std::string> alternate_protocol_values;
79 void* iter = NULL;
80 std::string alternate_protocol_str;
81 while (headers.EnumerateHeader(&iter, kAlternateProtocolHeader,
82 &alternate_protocol_str)) {
83 alternate_protocol_values.push_back(alternate_protocol_str);
86 session->http_stream_factory()->ProcessAlternateProtocol(
87 session->http_server_properties(),
88 alternate_protocol_values,
89 http_host_port_pair,
90 *session);
93 base::Value* NetLogSSLVersionFallbackCallback(
94 const GURL* url,
95 int net_error,
96 uint16 version_before,
97 uint16 version_after,
98 NetLog::LogLevel /* log_level */) {
99 base::DictionaryValue* dict = new base::DictionaryValue();
100 dict->SetString("host_and_port", GetHostAndPort(*url));
101 dict->SetInteger("net_error", net_error);
102 dict->SetInteger("version_before", version_before);
103 dict->SetInteger("version_after", version_after);
104 return dict;
107 } // namespace
109 //-----------------------------------------------------------------------------
111 HttpNetworkTransaction::HttpNetworkTransaction(RequestPriority priority,
112 HttpNetworkSession* session)
113 : pending_auth_target_(HttpAuth::AUTH_NONE),
114 io_callback_(base::Bind(&HttpNetworkTransaction::OnIOComplete,
115 base::Unretained(this))),
116 session_(session),
117 request_(NULL),
118 priority_(priority),
119 headers_valid_(false),
120 fallback_error_code_(ERR_SSL_INAPPROPRIATE_FALLBACK),
121 request_headers_(),
122 read_buf_len_(0),
123 total_received_bytes_(0),
124 next_state_(STATE_NONE),
125 establishing_tunnel_(false),
126 websocket_handshake_stream_base_create_helper_(NULL) {
127 session->ssl_config_service()->GetSSLConfig(&server_ssl_config_);
128 session->GetNextProtos(&server_ssl_config_.next_protos);
129 proxy_ssl_config_ = server_ssl_config_;
132 HttpNetworkTransaction::~HttpNetworkTransaction() {
133 if (stream_.get()) {
134 HttpResponseHeaders* headers = GetResponseHeaders();
135 // TODO(mbelshe): The stream_ should be able to compute whether or not the
136 // stream should be kept alive. No reason to compute here
137 // and pass it in.
138 bool try_to_keep_alive =
139 next_state_ == STATE_NONE &&
140 stream_->CanFindEndOfResponse() &&
141 (!headers || headers->IsKeepAlive());
142 if (!try_to_keep_alive) {
143 stream_->Close(true /* not reusable */);
144 } else {
145 if (stream_->IsResponseBodyComplete()) {
146 // If the response body is complete, we can just reuse the socket.
147 stream_->Close(false /* reusable */);
148 } else if (stream_->IsSpdyHttpStream()) {
149 // Doesn't really matter for SpdyHttpStream. Just close it.
150 stream_->Close(true /* not reusable */);
151 } else {
152 // Otherwise, we try to drain the response body.
153 HttpStream* stream = stream_.release();
154 stream->Drain(session_);
159 if (request_ && request_->upload_data_stream)
160 request_->upload_data_stream->Reset(); // Invalidate pending callbacks.
163 int HttpNetworkTransaction::Start(const HttpRequestInfo* request_info,
164 const CompletionCallback& callback,
165 const BoundNetLog& net_log) {
166 SIMPLE_STATS_COUNTER("HttpNetworkTransaction.Count");
168 net_log_ = net_log;
169 request_ = request_info;
171 if (request_->load_flags & LOAD_DISABLE_CERT_REVOCATION_CHECKING) {
172 server_ssl_config_.rev_checking_enabled = false;
173 proxy_ssl_config_.rev_checking_enabled = false;
176 // Channel ID is disabled if privacy mode is enabled for this request.
177 if (request_->privacy_mode == PRIVACY_MODE_ENABLED)
178 server_ssl_config_.channel_id_enabled = false;
180 next_state_ = STATE_NOTIFY_BEFORE_CREATE_STREAM;
181 int rv = DoLoop(OK);
182 if (rv == ERR_IO_PENDING)
183 callback_ = callback;
184 return rv;
187 int HttpNetworkTransaction::RestartIgnoringLastError(
188 const CompletionCallback& callback) {
189 DCHECK(!stream_.get());
190 DCHECK(!stream_request_.get());
191 DCHECK_EQ(STATE_NONE, next_state_);
193 next_state_ = STATE_CREATE_STREAM;
195 int rv = DoLoop(OK);
196 if (rv == ERR_IO_PENDING)
197 callback_ = callback;
198 return rv;
201 int 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_);
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;
225 int 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;
232 pending_auth_target_ = HttpAuth::AUTH_NONE;
234 auth_controllers_[target]->ResetAuth(credentials);
236 DCHECK(callback_.is_null());
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);
255 if (rv == ERR_IO_PENDING)
256 callback_ = callback;
257 return rv;
260 void HttpNetworkTransaction::PrepareForAuthRestart(HttpAuth::Target target) {
261 DCHECK(HaveAuth(target));
262 DCHECK(!stream_request_.get());
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;
277 keep_alive = true;
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);
285 void HttpNetworkTransaction::DidDrainBodyForAuthRestart(bool keep_alive) {
286 DCHECK(!stream_request_.get());
288 if (stream_.get()) {
289 total_received_bytes_ += stream_->GetTotalReceivedBytes();
290 HttpStream* new_stream = NULL;
291 if (keep_alive && stream_->IsConnectionReusable()) {
292 // We should call connection_->set_idle_time(), but this doesn't occur
293 // often enough to be worth the trouble.
294 stream_->SetConnectionReused();
295 new_stream = stream_->RenewStreamForAuth();
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 // Renewed streams shouldn't carry over received bytes.
306 DCHECK_EQ(0, new_stream->GetTotalReceivedBytes());
307 next_state_ = STATE_INIT_STREAM;
309 stream_.reset(new_stream);
312 // Reset the other member variables.
313 ResetStateForAuthRestart();
316 bool HttpNetworkTransaction::IsReadyToRestartForAuth() {
317 return pending_auth_target_ != HttpAuth::AUTH_NONE &&
318 HaveAuth(pending_auth_target_);
321 int HttpNetworkTransaction::Read(IOBuffer* buf, int buf_len,
322 const CompletionCallback& callback) {
323 DCHECK(buf);
324 DCHECK_LT(0, buf_len);
326 State next_state = STATE_NONE;
328 scoped_refptr<HttpResponseHeaders> headers(GetResponseHeaders());
329 if (headers_valid_ && headers.get() && stream_request_.get()) {
330 // We're trying to read the body of the response but we're still trying
331 // to establish an SSL tunnel through an HTTP proxy. We can't read these
332 // bytes when establishing a tunnel because they might be controlled by
333 // an active network attacker. We don't worry about this for HTTP
334 // because an active network attacker can already control HTTP sessions.
335 // We reach this case when the user cancels a 407 proxy auth prompt. We
336 // also don't worry about this for an HTTPS Proxy, because the
337 // communication with the proxy is secure.
338 // See http://crbug.com/8473.
339 DCHECK(proxy_info_.is_http() || proxy_info_.is_https());
340 DCHECK_EQ(headers->response_code(), HTTP_PROXY_AUTHENTICATION_REQUIRED);
341 LOG(WARNING) << "Blocked proxy response with status "
342 << headers->response_code() << " to CONNECT request for "
343 << GetHostAndPort(request_->url) << ".";
344 return ERR_TUNNEL_CONNECTION_FAILED;
347 // Are we using SPDY or HTTP?
348 next_state = STATE_READ_BODY;
350 read_buf_ = buf;
351 read_buf_len_ = buf_len;
353 next_state_ = next_state;
354 int rv = DoLoop(OK);
355 if (rv == ERR_IO_PENDING)
356 callback_ = callback;
357 return rv;
360 void HttpNetworkTransaction::StopCaching() {}
362 bool HttpNetworkTransaction::GetFullRequestHeaders(
363 HttpRequestHeaders* headers) const {
364 // TODO(ttuttle): Make sure we've populated request_headers_.
365 *headers = request_headers_;
366 return true;
369 int64 HttpNetworkTransaction::GetTotalReceivedBytes() const {
370 int64 total_received_bytes = total_received_bytes_;
371 if (stream_)
372 total_received_bytes += stream_->GetTotalReceivedBytes();
373 return total_received_bytes;
376 void HttpNetworkTransaction::DoneReading() {}
378 const HttpResponseInfo* HttpNetworkTransaction::GetResponseInfo() const {
379 return ((headers_valid_ && response_.headers.get()) ||
380 response_.ssl_info.cert.get() || response_.cert_request_info.get())
381 ? &response_
382 : NULL;
385 LoadState HttpNetworkTransaction::GetLoadState() const {
386 // TODO(wtc): Define a new LoadState value for the
387 // STATE_INIT_CONNECTION_COMPLETE state, which delays the HTTP request.
388 switch (next_state_) {
389 case STATE_CREATE_STREAM:
390 return LOAD_STATE_WAITING_FOR_DELEGATE;
391 case STATE_CREATE_STREAM_COMPLETE:
392 return stream_request_->GetLoadState();
393 case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
394 case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE:
395 case STATE_SEND_REQUEST_COMPLETE:
396 return LOAD_STATE_SENDING_REQUEST;
397 case STATE_READ_HEADERS_COMPLETE:
398 return LOAD_STATE_WAITING_FOR_RESPONSE;
399 case STATE_READ_BODY_COMPLETE:
400 return LOAD_STATE_READING_RESPONSE;
401 default:
402 return LOAD_STATE_IDLE;
406 UploadProgress HttpNetworkTransaction::GetUploadProgress() const {
407 if (!stream_.get())
408 return UploadProgress();
410 return stream_->GetUploadProgress();
413 void HttpNetworkTransaction::SetQuicServerInfo(
414 QuicServerInfo* quic_server_info) {}
416 bool HttpNetworkTransaction::GetLoadTimingInfo(
417 LoadTimingInfo* load_timing_info) const {
418 if (!stream_ || !stream_->GetLoadTimingInfo(load_timing_info))
419 return false;
421 load_timing_info->proxy_resolve_start =
422 proxy_info_.proxy_resolve_start_time();
423 load_timing_info->proxy_resolve_end = proxy_info_.proxy_resolve_end_time();
424 load_timing_info->send_start = send_start_time_;
425 load_timing_info->send_end = send_end_time_;
426 return true;
429 void HttpNetworkTransaction::SetPriority(RequestPriority priority) {
430 priority_ = priority;
431 if (stream_request_)
432 stream_request_->SetPriority(priority);
433 if (stream_)
434 stream_->SetPriority(priority);
437 void HttpNetworkTransaction::SetWebSocketHandshakeStreamCreateHelper(
438 WebSocketHandshakeStreamBase::CreateHelper* create_helper) {
439 websocket_handshake_stream_base_create_helper_ = create_helper;
442 void HttpNetworkTransaction::SetBeforeNetworkStartCallback(
443 const BeforeNetworkStartCallback& callback) {
444 before_network_start_callback_ = callback;
447 void HttpNetworkTransaction::SetBeforeProxyHeadersSentCallback(
448 const BeforeProxyHeadersSentCallback& callback) {
449 before_proxy_headers_sent_callback_ = callback;
452 int HttpNetworkTransaction::ResumeNetworkStart() {
453 DCHECK_EQ(next_state_, STATE_CREATE_STREAM);
454 return DoLoop(OK);
457 void HttpNetworkTransaction::OnStreamReady(const SSLConfig& used_ssl_config,
458 const ProxyInfo& used_proxy_info,
459 HttpStream* stream) {
460 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
461 DCHECK(stream_request_.get());
463 if (stream_)
464 total_received_bytes_ += stream_->GetTotalReceivedBytes();
465 stream_.reset(stream);
466 server_ssl_config_ = used_ssl_config;
467 proxy_info_ = used_proxy_info;
468 response_.was_npn_negotiated = stream_request_->was_npn_negotiated();
469 response_.npn_negotiated_protocol = SSLClientSocket::NextProtoToString(
470 stream_request_->protocol_negotiated());
471 response_.was_fetched_via_spdy = stream_request_->using_spdy();
472 response_.was_fetched_via_proxy = !proxy_info_.is_direct();
473 if (response_.was_fetched_via_proxy && !proxy_info_.is_empty())
474 response_.proxy_server = proxy_info_.proxy_server().host_port_pair();
475 OnIOComplete(OK);
478 void HttpNetworkTransaction::OnWebSocketHandshakeStreamReady(
479 const SSLConfig& used_ssl_config,
480 const ProxyInfo& used_proxy_info,
481 WebSocketHandshakeStreamBase* stream) {
482 OnStreamReady(used_ssl_config, used_proxy_info, stream);
485 void HttpNetworkTransaction::OnStreamFailed(int result,
486 const SSLConfig& used_ssl_config) {
487 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
488 DCHECK_NE(OK, result);
489 DCHECK(stream_request_.get());
490 DCHECK(!stream_.get());
491 server_ssl_config_ = used_ssl_config;
493 OnIOComplete(result);
496 void HttpNetworkTransaction::OnCertificateError(
497 int result,
498 const SSLConfig& used_ssl_config,
499 const SSLInfo& ssl_info) {
500 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
501 DCHECK_NE(OK, result);
502 DCHECK(stream_request_.get());
503 DCHECK(!stream_.get());
505 response_.ssl_info = ssl_info;
506 server_ssl_config_ = used_ssl_config;
508 // TODO(mbelshe): For now, we're going to pass the error through, and that
509 // will close the stream_request in all cases. This means that we're always
510 // going to restart an entire STATE_CREATE_STREAM, even if the connection is
511 // good and the user chooses to ignore the error. This is not ideal, but not
512 // the end of the world either.
514 OnIOComplete(result);
517 void HttpNetworkTransaction::OnNeedsProxyAuth(
518 const HttpResponseInfo& proxy_response,
519 const SSLConfig& used_ssl_config,
520 const ProxyInfo& used_proxy_info,
521 HttpAuthController* auth_controller) {
522 DCHECK(stream_request_.get());
523 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
525 establishing_tunnel_ = true;
526 response_.headers = proxy_response.headers;
527 response_.auth_challenge = proxy_response.auth_challenge;
528 headers_valid_ = true;
529 server_ssl_config_ = used_ssl_config;
530 proxy_info_ = used_proxy_info;
532 auth_controllers_[HttpAuth::AUTH_PROXY] = auth_controller;
533 pending_auth_target_ = HttpAuth::AUTH_PROXY;
535 DoCallback(OK);
538 void HttpNetworkTransaction::OnNeedsClientAuth(
539 const SSLConfig& used_ssl_config,
540 SSLCertRequestInfo* cert_info) {
541 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
543 server_ssl_config_ = used_ssl_config;
544 response_.cert_request_info = cert_info;
545 OnIOComplete(ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
548 void HttpNetworkTransaction::OnHttpsProxyTunnelResponse(
549 const HttpResponseInfo& response_info,
550 const SSLConfig& used_ssl_config,
551 const ProxyInfo& used_proxy_info,
552 HttpStream* stream) {
553 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE, next_state_);
555 headers_valid_ = true;
556 response_ = response_info;
557 server_ssl_config_ = used_ssl_config;
558 proxy_info_ = used_proxy_info;
559 if (stream_)
560 total_received_bytes_ += stream_->GetTotalReceivedBytes();
561 stream_.reset(stream);
562 stream_request_.reset(); // we're done with the stream request
563 OnIOComplete(ERR_HTTPS_PROXY_TUNNEL_RESPONSE);
566 bool HttpNetworkTransaction::is_https_request() const {
567 return request_->url.SchemeIs("https");
570 void HttpNetworkTransaction::DoCallback(int rv) {
571 DCHECK_NE(rv, ERR_IO_PENDING);
572 DCHECK(!callback_.is_null());
574 // Since Run may result in Read being called, clear user_callback_ up front.
575 CompletionCallback c = callback_;
576 callback_.Reset();
577 c.Run(rv);
580 void HttpNetworkTransaction::OnIOComplete(int result) {
581 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424359 is fixed.
582 tracked_objects::ScopedTracker tracking_profile1(
583 FROM_HERE_WITH_EXPLICIT_FUNCTION(
584 "424359 HttpNetworkTransaction::OnIOComplete 1"));
586 int rv = DoLoop(result);
588 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424359 is fixed.
589 tracked_objects::ScopedTracker tracking_profile2(
590 FROM_HERE_WITH_EXPLICIT_FUNCTION(
591 "424359 HttpNetworkTransaction::OnIOComplete 2"));
593 if (rv != ERR_IO_PENDING)
594 DoCallback(rv);
597 int HttpNetworkTransaction::DoLoop(int result) {
598 DCHECK(next_state_ != STATE_NONE);
600 int rv = result;
601 do {
602 State state = next_state_;
603 next_state_ = STATE_NONE;
604 switch (state) {
605 case STATE_NOTIFY_BEFORE_CREATE_STREAM:
606 DCHECK_EQ(OK, rv);
607 rv = DoNotifyBeforeCreateStream();
608 break;
609 case STATE_CREATE_STREAM:
610 DCHECK_EQ(OK, rv);
611 rv = DoCreateStream();
612 break;
613 case STATE_CREATE_STREAM_COMPLETE:
614 rv = DoCreateStreamComplete(rv);
615 break;
616 case STATE_INIT_STREAM:
617 DCHECK_EQ(OK, rv);
618 rv = DoInitStream();
619 break;
620 case STATE_INIT_STREAM_COMPLETE:
621 rv = DoInitStreamComplete(rv);
622 break;
623 case STATE_GENERATE_PROXY_AUTH_TOKEN:
624 DCHECK_EQ(OK, rv);
625 rv = DoGenerateProxyAuthToken();
626 break;
627 case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
628 rv = DoGenerateProxyAuthTokenComplete(rv);
629 break;
630 case STATE_GENERATE_SERVER_AUTH_TOKEN:
631 DCHECK_EQ(OK, rv);
632 rv = DoGenerateServerAuthToken();
633 break;
634 case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE:
635 rv = DoGenerateServerAuthTokenComplete(rv);
636 break;
637 case STATE_INIT_REQUEST_BODY:
638 DCHECK_EQ(OK, rv);
639 rv = DoInitRequestBody();
640 break;
641 case STATE_INIT_REQUEST_BODY_COMPLETE:
642 rv = DoInitRequestBodyComplete(rv);
643 break;
644 case STATE_BUILD_REQUEST:
645 DCHECK_EQ(OK, rv);
646 net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST);
647 rv = DoBuildRequest();
648 break;
649 case STATE_BUILD_REQUEST_COMPLETE:
650 rv = DoBuildRequestComplete(rv);
651 break;
652 case STATE_SEND_REQUEST:
653 DCHECK_EQ(OK, rv);
654 rv = DoSendRequest();
655 break;
656 case STATE_SEND_REQUEST_COMPLETE:
657 rv = DoSendRequestComplete(rv);
658 net_log_.EndEventWithNetErrorCode(
659 NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST, rv);
660 break;
661 case STATE_READ_HEADERS:
662 DCHECK_EQ(OK, rv);
663 net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS);
664 rv = DoReadHeaders();
665 break;
666 case STATE_READ_HEADERS_COMPLETE:
667 rv = DoReadHeadersComplete(rv);
668 net_log_.EndEventWithNetErrorCode(
669 NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS, rv);
670 break;
671 case STATE_READ_BODY:
672 DCHECK_EQ(OK, rv);
673 net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_BODY);
674 rv = DoReadBody();
675 break;
676 case STATE_READ_BODY_COMPLETE:
677 rv = DoReadBodyComplete(rv);
678 net_log_.EndEventWithNetErrorCode(
679 NetLog::TYPE_HTTP_TRANSACTION_READ_BODY, rv);
680 break;
681 case STATE_DRAIN_BODY_FOR_AUTH_RESTART:
682 DCHECK_EQ(OK, rv);
683 net_log_.BeginEvent(
684 NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART);
685 rv = DoDrainBodyForAuthRestart();
686 break;
687 case STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE:
688 rv = DoDrainBodyForAuthRestartComplete(rv);
689 net_log_.EndEventWithNetErrorCode(
690 NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART, rv);
691 break;
692 default:
693 NOTREACHED() << "bad state";
694 rv = ERR_FAILED;
695 break;
697 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
699 return rv;
702 int HttpNetworkTransaction::DoNotifyBeforeCreateStream() {
703 next_state_ = STATE_CREATE_STREAM;
704 bool defer = false;
705 if (!before_network_start_callback_.is_null())
706 before_network_start_callback_.Run(&defer);
707 if (!defer)
708 return OK;
709 return ERR_IO_PENDING;
712 int HttpNetworkTransaction::DoCreateStream() {
713 next_state_ = STATE_CREATE_STREAM_COMPLETE;
714 if (ForWebSocketHandshake()) {
715 stream_request_.reset(
716 session_->http_stream_factory_for_websocket()
717 ->RequestWebSocketHandshakeStream(
718 *request_,
719 priority_,
720 server_ssl_config_,
721 proxy_ssl_config_,
722 this,
723 websocket_handshake_stream_base_create_helper_,
724 net_log_));
725 } else {
726 stream_request_.reset(
727 session_->http_stream_factory()->RequestStream(
728 *request_,
729 priority_,
730 server_ssl_config_,
731 proxy_ssl_config_,
732 this,
733 net_log_));
735 DCHECK(stream_request_.get());
736 return ERR_IO_PENDING;
739 int HttpNetworkTransaction::DoCreateStreamComplete(int result) {
740 if (result == OK) {
741 next_state_ = STATE_INIT_STREAM;
742 DCHECK(stream_.get());
743 } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
744 result = HandleCertificateRequest(result);
745 } else if (result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
746 // Return OK and let the caller read the proxy's error page
747 next_state_ = STATE_NONE;
748 return OK;
751 // Handle possible handshake errors that may have occurred if the stream
752 // used SSL for one or more of the layers.
753 result = HandleSSLHandshakeError(result);
755 // At this point we are done with the stream_request_.
756 stream_request_.reset();
757 return result;
760 int HttpNetworkTransaction::DoInitStream() {
761 DCHECK(stream_.get());
762 next_state_ = STATE_INIT_STREAM_COMPLETE;
763 return stream_->InitializeStream(request_, priority_, net_log_, io_callback_);
766 int HttpNetworkTransaction::DoInitStreamComplete(int result) {
767 if (result == OK) {
768 next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
769 } else {
770 if (result < 0)
771 result = HandleIOError(result);
773 // The stream initialization failed, so this stream will never be useful.
774 if (stream_)
775 total_received_bytes_ += stream_->GetTotalReceivedBytes();
776 stream_.reset();
779 return result;
782 int HttpNetworkTransaction::DoGenerateProxyAuthToken() {
783 next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE;
784 if (!ShouldApplyProxyAuth())
785 return OK;
786 HttpAuth::Target target = HttpAuth::AUTH_PROXY;
787 if (!auth_controllers_[target].get())
788 auth_controllers_[target] =
789 new HttpAuthController(target,
790 AuthURL(target),
791 session_->http_auth_cache(),
792 session_->http_auth_handler_factory());
793 return auth_controllers_[target]->MaybeGenerateAuthToken(request_,
794 io_callback_,
795 net_log_);
798 int HttpNetworkTransaction::DoGenerateProxyAuthTokenComplete(int rv) {
799 DCHECK_NE(ERR_IO_PENDING, rv);
800 if (rv == OK)
801 next_state_ = STATE_GENERATE_SERVER_AUTH_TOKEN;
802 return rv;
805 int HttpNetworkTransaction::DoGenerateServerAuthToken() {
806 next_state_ = STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE;
807 HttpAuth::Target target = HttpAuth::AUTH_SERVER;
808 if (!auth_controllers_[target].get()) {
809 auth_controllers_[target] =
810 new HttpAuthController(target,
811 AuthURL(target),
812 session_->http_auth_cache(),
813 session_->http_auth_handler_factory());
814 if (request_->load_flags & LOAD_DO_NOT_USE_EMBEDDED_IDENTITY)
815 auth_controllers_[target]->DisableEmbeddedIdentity();
817 if (!ShouldApplyServerAuth())
818 return OK;
819 return auth_controllers_[target]->MaybeGenerateAuthToken(request_,
820 io_callback_,
821 net_log_);
824 int HttpNetworkTransaction::DoGenerateServerAuthTokenComplete(int rv) {
825 DCHECK_NE(ERR_IO_PENDING, rv);
826 if (rv == OK)
827 next_state_ = STATE_INIT_REQUEST_BODY;
828 return rv;
831 void HttpNetworkTransaction::BuildRequestHeaders(bool using_proxy) {
832 request_headers_.SetHeader(HttpRequestHeaders::kHost,
833 GetHostAndOptionalPort(request_->url));
835 // For compat with HTTP/1.0 servers and proxies:
836 if (using_proxy) {
837 request_headers_.SetHeader(HttpRequestHeaders::kProxyConnection,
838 "keep-alive");
839 } else {
840 request_headers_.SetHeader(HttpRequestHeaders::kConnection, "keep-alive");
843 // Add a content length header?
844 if (request_->upload_data_stream) {
845 if (request_->upload_data_stream->is_chunked()) {
846 request_headers_.SetHeader(
847 HttpRequestHeaders::kTransferEncoding, "chunked");
848 } else {
849 request_headers_.SetHeader(
850 HttpRequestHeaders::kContentLength,
851 base::Uint64ToString(request_->upload_data_stream->size()));
853 } else if (request_->method == "POST" || request_->method == "PUT" ||
854 request_->method == "HEAD") {
855 // An empty POST/PUT request still needs a content length. As for HEAD,
856 // IE and Safari also add a content length header. Presumably it is to
857 // support sending a HEAD request to an URL that only expects to be sent a
858 // POST or some other method that normally would have a message body.
859 request_headers_.SetHeader(HttpRequestHeaders::kContentLength, "0");
862 // Honor load flags that impact proxy caches.
863 if (request_->load_flags & LOAD_BYPASS_CACHE) {
864 request_headers_.SetHeader(HttpRequestHeaders::kPragma, "no-cache");
865 request_headers_.SetHeader(HttpRequestHeaders::kCacheControl, "no-cache");
866 } else if (request_->load_flags & LOAD_VALIDATE_CACHE) {
867 request_headers_.SetHeader(HttpRequestHeaders::kCacheControl, "max-age=0");
870 if (ShouldApplyProxyAuth() && HaveAuth(HttpAuth::AUTH_PROXY))
871 auth_controllers_[HttpAuth::AUTH_PROXY]->AddAuthorizationHeader(
872 &request_headers_);
873 if (ShouldApplyServerAuth() && HaveAuth(HttpAuth::AUTH_SERVER))
874 auth_controllers_[HttpAuth::AUTH_SERVER]->AddAuthorizationHeader(
875 &request_headers_);
877 request_headers_.MergeFrom(request_->extra_headers);
879 if (using_proxy && !before_proxy_headers_sent_callback_.is_null())
880 before_proxy_headers_sent_callback_.Run(proxy_info_, &request_headers_);
882 response_.did_use_http_auth =
883 request_headers_.HasHeader(HttpRequestHeaders::kAuthorization) ||
884 request_headers_.HasHeader(HttpRequestHeaders::kProxyAuthorization);
887 int HttpNetworkTransaction::DoInitRequestBody() {
888 next_state_ = STATE_INIT_REQUEST_BODY_COMPLETE;
889 int rv = OK;
890 if (request_->upload_data_stream)
891 rv = request_->upload_data_stream->Init(io_callback_);
892 return rv;
895 int HttpNetworkTransaction::DoInitRequestBodyComplete(int result) {
896 if (result == OK)
897 next_state_ = STATE_BUILD_REQUEST;
898 return result;
901 int HttpNetworkTransaction::DoBuildRequest() {
902 next_state_ = STATE_BUILD_REQUEST_COMPLETE;
903 headers_valid_ = false;
905 // This is constructed lazily (instead of within our Start method), so that
906 // we have proxy info available.
907 if (request_headers_.IsEmpty()) {
908 bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
909 !is_https_request();
910 BuildRequestHeaders(using_proxy);
913 return OK;
916 int HttpNetworkTransaction::DoBuildRequestComplete(int result) {
917 if (result == OK)
918 next_state_ = STATE_SEND_REQUEST;
919 return result;
922 int HttpNetworkTransaction::DoSendRequest() {
923 send_start_time_ = base::TimeTicks::Now();
924 next_state_ = STATE_SEND_REQUEST_COMPLETE;
926 return stream_->SendRequest(request_headers_, &response_, io_callback_);
929 int HttpNetworkTransaction::DoSendRequestComplete(int result) {
930 send_end_time_ = base::TimeTicks::Now();
931 if (result < 0)
932 return HandleIOError(result);
933 response_.network_accessed = true;
934 next_state_ = STATE_READ_HEADERS;
935 return OK;
938 int HttpNetworkTransaction::DoReadHeaders() {
939 next_state_ = STATE_READ_HEADERS_COMPLETE;
940 return stream_->ReadResponseHeaders(io_callback_);
943 int HttpNetworkTransaction::DoReadHeadersComplete(int result) {
944 // We can get a certificate error or ERR_SSL_CLIENT_AUTH_CERT_NEEDED here
945 // due to SSL renegotiation.
946 if (IsCertificateError(result)) {
947 // We don't handle a certificate error during SSL renegotiation, so we
948 // have to return an error that's not in the certificate error range
949 // (-2xx).
950 LOG(ERROR) << "Got a server certificate with error " << result
951 << " during SSL renegotiation";
952 result = ERR_CERT_ERROR_IN_SSL_RENEGOTIATION;
953 } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
954 // TODO(wtc): Need a test case for this code path!
955 DCHECK(stream_.get());
956 DCHECK(is_https_request());
957 response_.cert_request_info = new SSLCertRequestInfo;
958 stream_->GetSSLCertRequestInfo(response_.cert_request_info.get());
959 result = HandleCertificateRequest(result);
960 if (result == OK)
961 return result;
964 // ERR_CONNECTION_CLOSED is treated differently at this point; if partial
965 // response headers were received, we do the best we can to make sense of it
966 // and send it back up the stack.
968 // TODO(davidben): Consider moving this to HttpBasicStream, It's a little
969 // bizarre for SPDY. Assuming this logic is useful at all.
970 // TODO(davidben): Bubble the error code up so we do not cache?
971 if (result == ERR_CONNECTION_CLOSED && response_.headers.get())
972 result = OK;
974 if (result < 0)
975 return HandleIOError(result);
977 DCHECK(response_.headers.get());
979 // On a 408 response from the server ("Request Timeout") on a stale socket,
980 // retry the request.
981 // Headers can be NULL because of http://crbug.com/384554.
982 if (response_.headers.get() && response_.headers->response_code() == 408 &&
983 stream_->IsConnectionReused()) {
984 net_log_.AddEventWithNetErrorCode(
985 NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR,
986 response_.headers->response_code());
987 // This will close the socket - it would be weird to try and reuse it, even
988 // if the server doesn't actually close it.
989 ResetConnectionAndRequestForResend();
990 return OK;
993 // Like Net.HttpResponseCode, but only for MAIN_FRAME loads.
994 if (request_->load_flags & LOAD_MAIN_FRAME) {
995 const int response_code = response_.headers->response_code();
996 UMA_HISTOGRAM_ENUMERATION(
997 "Net.HttpResponseCode_Nxx_MainFrame", response_code/100, 10);
1000 net_log_.AddEvent(
1001 NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS,
1002 base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers));
1004 if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0)) {
1005 // HTTP/0.9 doesn't support the PUT method, so lack of response headers
1006 // indicates a buggy server. See:
1007 // https://bugzilla.mozilla.org/show_bug.cgi?id=193921
1008 if (request_->method == "PUT")
1009 return ERR_METHOD_NOT_SUPPORTED;
1012 // Check for an intermediate 100 Continue response. An origin server is
1013 // allowed to send this response even if we didn't ask for it, so we just
1014 // need to skip over it.
1015 // We treat any other 1xx in this same way (although in practice getting
1016 // a 1xx that isn't a 100 is rare).
1017 // Unless this is a WebSocket request, in which case we pass it on up.
1018 if (response_.headers->response_code() / 100 == 1 &&
1019 !ForWebSocketHandshake()) {
1020 response_.headers = new HttpResponseHeaders(std::string());
1021 next_state_ = STATE_READ_HEADERS;
1022 return OK;
1025 ProcessAlternateProtocol(session_, *response_.headers.get(),
1026 HostPortPair::FromURL(request_->url));
1028 int rv = HandleAuthChallenge();
1029 if (rv != OK)
1030 return rv;
1032 if (is_https_request())
1033 stream_->GetSSLInfo(&response_.ssl_info);
1035 headers_valid_ = true;
1037 if (session_->huffman_aggregator()) {
1038 session_->huffman_aggregator()->AggregateTransactionCharacterCounts(
1039 *request_,
1040 request_headers_,
1041 proxy_info_.proxy_server(),
1042 *response_.headers.get());
1044 return OK;
1047 int HttpNetworkTransaction::DoReadBody() {
1048 DCHECK(read_buf_.get());
1049 DCHECK_GT(read_buf_len_, 0);
1050 DCHECK(stream_ != NULL);
1052 next_state_ = STATE_READ_BODY_COMPLETE;
1053 return stream_->ReadResponseBody(
1054 read_buf_.get(), read_buf_len_, io_callback_);
1057 int HttpNetworkTransaction::DoReadBodyComplete(int result) {
1058 // We are done with the Read call.
1059 bool done = false;
1060 if (result <= 0) {
1061 DCHECK_NE(ERR_IO_PENDING, result);
1062 done = true;
1065 bool keep_alive = false;
1066 if (stream_->IsResponseBodyComplete()) {
1067 // Note: Just because IsResponseBodyComplete is true, we're not
1068 // necessarily "done". We're only "done" when it is the last
1069 // read on this HttpNetworkTransaction, which will be signified
1070 // by a zero-length read.
1071 // TODO(mbelshe): The keepalive property is really a property of
1072 // the stream. No need to compute it here just to pass back
1073 // to the stream's Close function.
1074 // TODO(rtenneti): CanFindEndOfResponse should return false if there are no
1075 // ResponseHeaders.
1076 if (stream_->CanFindEndOfResponse()) {
1077 HttpResponseHeaders* headers = GetResponseHeaders();
1078 if (headers)
1079 keep_alive = headers->IsKeepAlive();
1083 // Clean up connection if we are done.
1084 if (done) {
1085 stream_->Close(!keep_alive);
1086 // Note: we don't reset the stream here. We've closed it, but we still
1087 // need it around so that callers can call methods such as
1088 // GetUploadProgress() and have them be meaningful.
1089 // TODO(mbelshe): This means we closed the stream here, and we close it
1090 // again in ~HttpNetworkTransaction. Clean that up.
1092 // The next Read call will return 0 (EOF).
1095 // Clear these to avoid leaving around old state.
1096 read_buf_ = NULL;
1097 read_buf_len_ = 0;
1099 return result;
1102 int HttpNetworkTransaction::DoDrainBodyForAuthRestart() {
1103 // This method differs from DoReadBody only in the next_state_. So we just
1104 // call DoReadBody and override the next_state_. Perhaps there is a more
1105 // elegant way for these two methods to share code.
1106 int rv = DoReadBody();
1107 DCHECK(next_state_ == STATE_READ_BODY_COMPLETE);
1108 next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE;
1109 return rv;
1112 // TODO(wtc): This method and the DoReadBodyComplete method are almost
1113 // the same. Figure out a good way for these two methods to share code.
1114 int HttpNetworkTransaction::DoDrainBodyForAuthRestartComplete(int result) {
1115 // keep_alive defaults to true because the very reason we're draining the
1116 // response body is to reuse the connection for auth restart.
1117 bool done = false, keep_alive = true;
1118 if (result < 0) {
1119 // Error or closed connection while reading the socket.
1120 done = true;
1121 keep_alive = false;
1122 } else if (stream_->IsResponseBodyComplete()) {
1123 done = true;
1126 if (done) {
1127 DidDrainBodyForAuthRestart(keep_alive);
1128 } else {
1129 // Keep draining.
1130 next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
1133 return OK;
1136 int HttpNetworkTransaction::HandleCertificateRequest(int error) {
1137 // There are two paths through which the server can request a certificate
1138 // from us. The first is during the initial handshake, the second is
1139 // during SSL renegotiation.
1141 // In both cases, we want to close the connection before proceeding.
1142 // We do this for two reasons:
1143 // First, we don't want to keep the connection to the server hung for a
1144 // long time while the user selects a certificate.
1145 // Second, even if we did keep the connection open, NSS has a bug where
1146 // restarting the handshake for ClientAuth is currently broken.
1147 DCHECK_EQ(error, ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
1149 if (stream_.get()) {
1150 // Since we already have a stream, we're being called as part of SSL
1151 // renegotiation.
1152 DCHECK(!stream_request_.get());
1153 total_received_bytes_ += stream_->GetTotalReceivedBytes();
1154 stream_->Close(true);
1155 stream_.reset();
1158 // The server is asking for a client certificate during the initial
1159 // handshake.
1160 stream_request_.reset();
1162 // If the user selected one of the certificates in client_certs or declined
1163 // to provide one for this server before, use the past decision
1164 // automatically.
1165 scoped_refptr<X509Certificate> client_cert;
1166 bool found_cached_cert = session_->ssl_client_auth_cache()->Lookup(
1167 response_.cert_request_info->host_and_port, &client_cert);
1168 if (!found_cached_cert)
1169 return error;
1171 // Check that the certificate selected is still a certificate the server
1172 // is likely to accept, based on the criteria supplied in the
1173 // CertificateRequest message.
1174 if (client_cert.get()) {
1175 const std::vector<std::string>& cert_authorities =
1176 response_.cert_request_info->cert_authorities;
1178 bool cert_still_valid = cert_authorities.empty() ||
1179 client_cert->IsIssuedByEncoded(cert_authorities);
1180 if (!cert_still_valid)
1181 return error;
1184 // TODO(davidben): Add a unit test which covers this path; we need to be
1185 // able to send a legitimate certificate and also bypass/clear the
1186 // SSL session cache.
1187 SSLConfig* ssl_config = response_.cert_request_info->is_proxy ?
1188 &proxy_ssl_config_ : &server_ssl_config_;
1189 ssl_config->send_client_cert = true;
1190 ssl_config->client_cert = client_cert;
1191 next_state_ = STATE_CREATE_STREAM;
1192 // Reset the other member variables.
1193 // Note: this is necessary only with SSL renegotiation.
1194 ResetStateForRestart();
1195 return OK;
1198 void HttpNetworkTransaction::HandleClientAuthError(int error) {
1199 if (server_ssl_config_.send_client_cert &&
1200 (error == ERR_SSL_PROTOCOL_ERROR || IsClientCertificateError(error))) {
1201 session_->ssl_client_auth_cache()->Remove(
1202 HostPortPair::FromURL(request_->url));
1206 // TODO(rch): This does not correctly handle errors when an SSL proxy is
1207 // being used, as all of the errors are handled as if they were generated
1208 // by the endpoint host, request_->url, rather than considering if they were
1209 // generated by the SSL proxy. http://crbug.com/69329
1210 int HttpNetworkTransaction::HandleSSLHandshakeError(int error) {
1211 DCHECK(request_);
1212 HandleClientAuthError(error);
1214 bool should_fallback = false;
1215 uint16 version_max = server_ssl_config_.version_max;
1217 switch (error) {
1218 case ERR_CONNECTION_CLOSED:
1219 case ERR_SSL_PROTOCOL_ERROR:
1220 case ERR_SSL_VERSION_OR_CIPHER_MISMATCH:
1221 if (version_max >= SSL_PROTOCOL_VERSION_TLS1 &&
1222 version_max > server_ssl_config_.version_min) {
1223 // This could be a TLS-intolerant server or a server that chose a
1224 // cipher suite defined only for higher protocol versions (such as
1225 // an SSL 3.0 server that chose a TLS-only cipher suite). Fall
1226 // back to the next lower version and retry.
1227 // NOTE: if the SSLClientSocket class doesn't support TLS 1.1,
1228 // specifying TLS 1.1 in version_max will result in a TLS 1.0
1229 // handshake, so falling back from TLS 1.1 to TLS 1.0 will simply
1230 // repeat the TLS 1.0 handshake. To avoid this problem, the default
1231 // version_max should match the maximum protocol version supported
1232 // by the SSLClientSocket class.
1233 version_max--;
1235 // Fallback to the lower SSL version.
1236 // While SSL 3.0 fallback should be eliminated because of security
1237 // reasons, there is a high risk of breaking the servers if this is
1238 // done in general.
1239 should_fallback = true;
1241 break;
1242 case ERR_CONNECTION_RESET:
1243 if (version_max >= SSL_PROTOCOL_VERSION_TLS1_1 &&
1244 version_max > server_ssl_config_.version_min) {
1245 // Some network devices that inspect application-layer packets seem to
1246 // inject TCP reset packets to break the connections when they see TLS
1247 // 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
1249 // Only allow ERR_CONNECTION_RESET to trigger a fallback from TLS 1.1 or
1250 // 1.2. We don't lose much in this fallback because the explicit IV for
1251 // CBC mode in TLS 1.1 is approximated by record splitting in TLS
1252 // 1.0. The fallback will be more painful for TLS 1.2 when we have GCM
1253 // support.
1255 // ERR_CONNECTION_RESET is a common network error, so we don't want it
1256 // to trigger a version fallback in general, especially the TLS 1.0 ->
1257 // SSL 3.0 fallback, which would drop TLS extensions.
1258 version_max--;
1259 should_fallback = true;
1261 break;
1262 case ERR_SSL_BAD_RECORD_MAC_ALERT:
1263 if (version_max >= SSL_PROTOCOL_VERSION_TLS1_1 &&
1264 version_max > server_ssl_config_.version_min) {
1265 // Some broken SSL devices negotiate TLS 1.0 when sent a TLS 1.1 or
1266 // 1.2 ClientHello, but then return a bad_record_mac alert. See
1267 // crbug.com/260358. In order to make the fallback as minimal as
1268 // possible, this fallback is only triggered for >= TLS 1.1.
1269 version_max--;
1270 should_fallback = true;
1272 break;
1273 case ERR_SSL_INAPPROPRIATE_FALLBACK:
1274 // The server told us that we should not have fallen back. A buggy server
1275 // could trigger ERR_SSL_INAPPROPRIATE_FALLBACK with the initial
1276 // connection. |fallback_error_code_| is initialised to
1277 // ERR_SSL_INAPPROPRIATE_FALLBACK to catch this case.
1278 error = fallback_error_code_;
1279 break;
1282 if (should_fallback) {
1283 net_log_.AddEvent(
1284 NetLog::TYPE_SSL_VERSION_FALLBACK,
1285 base::Bind(&NetLogSSLVersionFallbackCallback,
1286 &request_->url, error, server_ssl_config_.version_max,
1287 version_max));
1288 fallback_error_code_ = error;
1289 server_ssl_config_.version_max = version_max;
1290 server_ssl_config_.version_fallback = true;
1291 ResetConnectionAndRequestForResend();
1292 error = OK;
1295 return error;
1298 // This method determines whether it is safe to resend the request after an
1299 // IO error. It can only be called in response to request header or body
1300 // write errors or response header read errors. It should not be used in
1301 // other cases, such as a Connect error.
1302 int HttpNetworkTransaction::HandleIOError(int error) {
1303 // Because the peer may request renegotiation with client authentication at
1304 // any time, check and handle client authentication errors.
1305 HandleClientAuthError(error);
1307 switch (error) {
1308 // If we try to reuse a connection that the server is in the process of
1309 // closing, we may end up successfully writing out our request (or a
1310 // portion of our request) only to find a connection error when we try to
1311 // read from (or finish writing to) the socket.
1312 case ERR_CONNECTION_RESET:
1313 case ERR_CONNECTION_CLOSED:
1314 case ERR_CONNECTION_ABORTED:
1315 // There can be a race between the socket pool checking checking whether a
1316 // socket is still connected, receiving the FIN, and sending/reading data
1317 // on a reused socket. If we receive the FIN between the connectedness
1318 // check and writing/reading from the socket, we may first learn the socket
1319 // is disconnected when we get a ERR_SOCKET_NOT_CONNECTED. This will most
1320 // likely happen when trying to retrieve its IP address.
1321 // See http://crbug.com/105824 for more details.
1322 case ERR_SOCKET_NOT_CONNECTED:
1323 // If a socket is closed on its initial request, HttpStreamParser returns
1324 // ERR_EMPTY_RESPONSE. This may still be close/reuse race if the socket was
1325 // preconnected but failed to be used before the server timed it out.
1326 case ERR_EMPTY_RESPONSE:
1327 if (ShouldResendRequest()) {
1328 net_log_.AddEventWithNetErrorCode(
1329 NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
1330 ResetConnectionAndRequestForResend();
1331 error = OK;
1333 break;
1334 case ERR_SPDY_PING_FAILED:
1335 case ERR_SPDY_SERVER_REFUSED_STREAM:
1336 case ERR_QUIC_HANDSHAKE_FAILED:
1337 net_log_.AddEventWithNetErrorCode(
1338 NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR, error);
1339 ResetConnectionAndRequestForResend();
1340 error = OK;
1341 break;
1343 return error;
1346 void HttpNetworkTransaction::ResetStateForRestart() {
1347 ResetStateForAuthRestart();
1348 if (stream_)
1349 total_received_bytes_ += stream_->GetTotalReceivedBytes();
1350 stream_.reset();
1353 void HttpNetworkTransaction::ResetStateForAuthRestart() {
1354 send_start_time_ = base::TimeTicks();
1355 send_end_time_ = base::TimeTicks();
1357 pending_auth_target_ = HttpAuth::AUTH_NONE;
1358 read_buf_ = NULL;
1359 read_buf_len_ = 0;
1360 headers_valid_ = false;
1361 request_headers_.Clear();
1362 response_ = HttpResponseInfo();
1363 establishing_tunnel_ = false;
1366 HttpResponseHeaders* HttpNetworkTransaction::GetResponseHeaders() const {
1367 return response_.headers.get();
1370 bool HttpNetworkTransaction::ShouldResendRequest() const {
1371 bool connection_is_proven = stream_->IsConnectionReused();
1372 bool has_received_headers = GetResponseHeaders() != NULL;
1374 // NOTE: we resend a request only if we reused a keep-alive connection.
1375 // This automatically prevents an infinite resend loop because we'll run
1376 // out of the cached keep-alive connections eventually.
1377 if (connection_is_proven && !has_received_headers)
1378 return true;
1379 return false;
1382 void HttpNetworkTransaction::ResetConnectionAndRequestForResend() {
1383 if (stream_.get()) {
1384 stream_->Close(true);
1385 stream_.reset();
1388 // We need to clear request_headers_ because it contains the real request
1389 // headers, but we may need to resend the CONNECT request first to recreate
1390 // the SSL tunnel.
1391 request_headers_.Clear();
1392 next_state_ = STATE_CREATE_STREAM; // Resend the request.
1395 bool HttpNetworkTransaction::ShouldApplyProxyAuth() const {
1396 return !is_https_request() &&
1397 (proxy_info_.is_https() || proxy_info_.is_http());
1400 bool HttpNetworkTransaction::ShouldApplyServerAuth() const {
1401 return !(request_->load_flags & LOAD_DO_NOT_SEND_AUTH_DATA);
1404 int HttpNetworkTransaction::HandleAuthChallenge() {
1405 scoped_refptr<HttpResponseHeaders> headers(GetResponseHeaders());
1406 DCHECK(headers.get());
1408 int status = headers->response_code();
1409 if (status != HTTP_UNAUTHORIZED &&
1410 status != HTTP_PROXY_AUTHENTICATION_REQUIRED)
1411 return OK;
1412 HttpAuth::Target target = status == HTTP_PROXY_AUTHENTICATION_REQUIRED ?
1413 HttpAuth::AUTH_PROXY : HttpAuth::AUTH_SERVER;
1414 if (target == HttpAuth::AUTH_PROXY && proxy_info_.is_direct())
1415 return ERR_UNEXPECTED_PROXY_AUTH;
1417 // This case can trigger when an HTTPS server responds with a "Proxy
1418 // authentication required" status code through a non-authenticating
1419 // proxy.
1420 if (!auth_controllers_[target].get())
1421 return ERR_UNEXPECTED_PROXY_AUTH;
1423 int rv = auth_controllers_[target]->HandleAuthChallenge(
1424 headers, (request_->load_flags & LOAD_DO_NOT_SEND_AUTH_DATA) != 0, false,
1425 net_log_);
1426 if (auth_controllers_[target]->HaveAuthHandler())
1427 pending_auth_target_ = target;
1429 scoped_refptr<AuthChallengeInfo> auth_info =
1430 auth_controllers_[target]->auth_info();
1431 if (auth_info.get())
1432 response_.auth_challenge = auth_info;
1434 return rv;
1437 bool HttpNetworkTransaction::HaveAuth(HttpAuth::Target target) const {
1438 return auth_controllers_[target].get() &&
1439 auth_controllers_[target]->HaveAuth();
1442 GURL HttpNetworkTransaction::AuthURL(HttpAuth::Target target) const {
1443 switch (target) {
1444 case HttpAuth::AUTH_PROXY: {
1445 if (!proxy_info_.proxy_server().is_valid() ||
1446 proxy_info_.proxy_server().is_direct()) {
1447 return GURL(); // There is no proxy server.
1449 const char* scheme = proxy_info_.is_https() ? "https://" : "http://";
1450 return GURL(scheme +
1451 proxy_info_.proxy_server().host_port_pair().ToString());
1453 case HttpAuth::AUTH_SERVER:
1454 if (ForWebSocketHandshake()) {
1455 const GURL& url = request_->url;
1456 url::Replacements<char> ws_to_http;
1457 if (url.SchemeIs("ws")) {
1458 ws_to_http.SetScheme("http", url::Component(0, 4));
1459 } else {
1460 DCHECK(url.SchemeIs("wss"));
1461 ws_to_http.SetScheme("https", url::Component(0, 5));
1463 return url.ReplaceComponents(ws_to_http);
1465 return request_->url;
1466 default:
1467 return GURL();
1471 bool HttpNetworkTransaction::ForWebSocketHandshake() const {
1472 return websocket_handshake_stream_base_create_helper_ &&
1473 request_->url.SchemeIsWSOrWSS();
1476 #define STATE_CASE(s) \
1477 case s: \
1478 description = base::StringPrintf("%s (0x%08X)", #s, s); \
1479 break
1481 std::string HttpNetworkTransaction::DescribeState(State state) {
1482 std::string description;
1483 switch (state) {
1484 STATE_CASE(STATE_NOTIFY_BEFORE_CREATE_STREAM);
1485 STATE_CASE(STATE_CREATE_STREAM);
1486 STATE_CASE(STATE_CREATE_STREAM_COMPLETE);
1487 STATE_CASE(STATE_INIT_REQUEST_BODY);
1488 STATE_CASE(STATE_INIT_REQUEST_BODY_COMPLETE);
1489 STATE_CASE(STATE_BUILD_REQUEST);
1490 STATE_CASE(STATE_BUILD_REQUEST_COMPLETE);
1491 STATE_CASE(STATE_SEND_REQUEST);
1492 STATE_CASE(STATE_SEND_REQUEST_COMPLETE);
1493 STATE_CASE(STATE_READ_HEADERS);
1494 STATE_CASE(STATE_READ_HEADERS_COMPLETE);
1495 STATE_CASE(STATE_READ_BODY);
1496 STATE_CASE(STATE_READ_BODY_COMPLETE);
1497 STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART);
1498 STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE);
1499 STATE_CASE(STATE_NONE);
1500 default:
1501 description = base::StringPrintf("Unknown state 0x%08X (%u)", state,
1502 state);
1503 break;
1505 return description;
1508 #undef STATE_CASE
1510 } // namespace net