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"
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/compiler_specific.h"
13 #include "base/format_macros.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/metrics/field_trial.h"
16 #include "base/metrics/histogram.h"
17 #include "base/metrics/stats_counters.h"
18 #include "base/stl_util.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/time/time.h"
23 #include "base/values.h"
24 #include "build/build_config.h"
25 #include "net/base/auth.h"
26 #include "net/base/host_port_pair.h"
27 #include "net/base/io_buffer.h"
28 #include "net/base/load_flags.h"
29 #include "net/base/load_timing_info.h"
30 #include "net/base/net_errors.h"
31 #include "net/base/net_util.h"
32 #include "net/base/upload_data_stream.h"
33 #include "net/http/http_auth.h"
34 #include "net/http/http_auth_handler.h"
35 #include "net/http/http_auth_handler_factory.h"
36 #include "net/http/http_basic_stream.h"
37 #include "net/http/http_chunked_decoder.h"
38 #include "net/http/http_network_session.h"
39 #include "net/http/http_proxy_client_socket.h"
40 #include "net/http/http_proxy_client_socket_pool.h"
41 #include "net/http/http_request_headers.h"
42 #include "net/http/http_request_info.h"
43 #include "net/http/http_response_headers.h"
44 #include "net/http/http_response_info.h"
45 #include "net/http/http_server_properties.h"
46 #include "net/http/http_status_code.h"
47 #include "net/http/http_stream_base.h"
48 #include "net/http/http_stream_factory.h"
49 #include "net/http/http_util.h"
50 #include "net/http/transport_security_state.h"
51 #include "net/http/url_security_manager.h"
52 #include "net/socket/client_socket_factory.h"
53 #include "net/socket/socks_client_socket_pool.h"
54 #include "net/socket/ssl_client_socket.h"
55 #include "net/socket/ssl_client_socket_pool.h"
56 #include "net/socket/transport_client_socket_pool.h"
57 #include "net/spdy/hpack_huffman_aggregator.h"
58 #include "net/spdy/spdy_http_stream.h"
59 #include "net/spdy/spdy_session.h"
60 #include "net/spdy/spdy_session_pool.h"
61 #include "net/ssl/ssl_cert_request_info.h"
62 #include "net/ssl/ssl_connection_status_flags.h"
64 #include "url/url_canon.h"
66 #if defined(SPDY_PROXY_AUTH_ORIGIN)
68 #include "net/proxy/proxy_server.h"
73 using base::TimeDelta
;
79 void ProcessAlternateProtocol(
80 HttpNetworkSession
* session
,
81 const HttpResponseHeaders
& headers
,
82 const HostPortPair
& http_host_port_pair
) {
83 if (!headers
.HasHeader(kAlternateProtocolHeader
))
86 std::vector
<std::string
> alternate_protocol_values
;
88 std::string alternate_protocol_str
;
89 while (headers
.EnumerateHeader(&iter
, kAlternateProtocolHeader
,
90 &alternate_protocol_str
)) {
91 alternate_protocol_values
.push_back(alternate_protocol_str
);
94 session
->http_stream_factory()->ProcessAlternateProtocol(
95 session
->http_server_properties(),
96 alternate_protocol_values
,
101 // Returns true if |error| is a client certificate authentication error.
102 bool IsClientCertificateError(int error
) {
104 case ERR_BAD_SSL_CLIENT_AUTH_CERT
:
105 case ERR_SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED
:
106 case ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
:
107 case ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
:
114 base::Value
* NetLogSSLVersionFallbackCallback(
117 uint16 version_before
,
118 uint16 version_after
,
119 NetLog::LogLevel
/* log_level */) {
120 base::DictionaryValue
* dict
= new base::DictionaryValue();
121 dict
->SetString("host_and_port", GetHostAndPort(*url
));
122 dict
->SetInteger("net_error", net_error
);
123 dict
->SetInteger("version_before", version_before
);
124 dict
->SetInteger("version_after", version_after
);
130 //-----------------------------------------------------------------------------
132 HttpNetworkTransaction::HttpNetworkTransaction(RequestPriority priority
,
133 HttpNetworkSession
* session
)
134 : pending_auth_target_(HttpAuth::AUTH_NONE
),
135 io_callback_(base::Bind(&HttpNetworkTransaction::OnIOComplete
,
136 base::Unretained(this))),
140 headers_valid_(false),
141 logged_response_time_(false),
142 fallback_error_code_(ERR_SSL_INAPPROPRIATE_FALLBACK
),
145 total_received_bytes_(0),
146 next_state_(STATE_NONE
),
147 establishing_tunnel_(false),
148 websocket_handshake_stream_base_create_helper_(NULL
) {
149 session
->ssl_config_service()->GetSSLConfig(&server_ssl_config_
);
150 session
->GetNextProtos(&server_ssl_config_
.next_protos
);
151 proxy_ssl_config_
= server_ssl_config_
;
154 HttpNetworkTransaction::~HttpNetworkTransaction() {
156 HttpResponseHeaders
* headers
= GetResponseHeaders();
157 // TODO(mbelshe): The stream_ should be able to compute whether or not the
158 // stream should be kept alive. No reason to compute here
160 bool try_to_keep_alive
=
161 next_state_
== STATE_NONE
&&
162 stream_
->CanFindEndOfResponse() &&
163 (!headers
|| headers
->IsKeepAlive());
164 if (!try_to_keep_alive
) {
165 stream_
->Close(true /* not reusable */);
167 if (stream_
->IsResponseBodyComplete()) {
168 // If the response body is complete, we can just reuse the socket.
169 stream_
->Close(false /* reusable */);
170 } else if (stream_
->IsSpdyHttpStream()) {
171 // Doesn't really matter for SpdyHttpStream. Just close it.
172 stream_
->Close(true /* not reusable */);
174 // Otherwise, we try to drain the response body.
175 HttpStreamBase
* stream
= stream_
.release();
176 stream
->Drain(session_
);
181 if (request_
&& request_
->upload_data_stream
)
182 request_
->upload_data_stream
->Reset(); // Invalidate pending callbacks.
185 int HttpNetworkTransaction::Start(const HttpRequestInfo
* request_info
,
186 const CompletionCallback
& callback
,
187 const BoundNetLog
& net_log
) {
188 SIMPLE_STATS_COUNTER("HttpNetworkTransaction.Count");
191 request_
= request_info
;
192 start_time_
= base::Time::Now();
194 if (request_
->load_flags
& LOAD_DISABLE_CERT_REVOCATION_CHECKING
) {
195 server_ssl_config_
.rev_checking_enabled
= false;
196 proxy_ssl_config_
.rev_checking_enabled
= false;
199 // Channel ID is disabled if privacy mode is enabled for this request.
200 if (request_
->privacy_mode
== PRIVACY_MODE_ENABLED
)
201 server_ssl_config_
.channel_id_enabled
= false;
203 next_state_
= STATE_NOTIFY_BEFORE_CREATE_STREAM
;
205 if (rv
== ERR_IO_PENDING
)
206 callback_
= callback
;
210 int HttpNetworkTransaction::RestartIgnoringLastError(
211 const CompletionCallback
& callback
) {
212 DCHECK(!stream_
.get());
213 DCHECK(!stream_request_
.get());
214 DCHECK_EQ(STATE_NONE
, next_state_
);
216 next_state_
= STATE_CREATE_STREAM
;
219 if (rv
== ERR_IO_PENDING
)
220 callback_
= callback
;
224 int HttpNetworkTransaction::RestartWithCertificate(
225 X509Certificate
* client_cert
, const CompletionCallback
& callback
) {
226 // In HandleCertificateRequest(), we always tear down existing stream
227 // requests to force a new connection. So we shouldn't have one here.
228 DCHECK(!stream_request_
.get());
229 DCHECK(!stream_
.get());
230 DCHECK_EQ(STATE_NONE
, next_state_
);
232 SSLConfig
* ssl_config
= response_
.cert_request_info
->is_proxy
?
233 &proxy_ssl_config_
: &server_ssl_config_
;
234 ssl_config
->send_client_cert
= true;
235 ssl_config
->client_cert
= client_cert
;
236 session_
->ssl_client_auth_cache()->Add(
237 response_
.cert_request_info
->host_and_port
, client_cert
);
238 // Reset the other member variables.
239 // Note: this is necessary only with SSL renegotiation.
240 ResetStateForRestart();
241 next_state_
= STATE_CREATE_STREAM
;
243 if (rv
== ERR_IO_PENDING
)
244 callback_
= callback
;
248 int HttpNetworkTransaction::RestartWithAuth(
249 const AuthCredentials
& credentials
, const CompletionCallback
& callback
) {
250 HttpAuth::Target target
= pending_auth_target_
;
251 if (target
== HttpAuth::AUTH_NONE
) {
253 return ERR_UNEXPECTED
;
255 pending_auth_target_
= HttpAuth::AUTH_NONE
;
257 auth_controllers_
[target
]->ResetAuth(credentials
);
259 DCHECK(callback_
.is_null());
262 if (target
== HttpAuth::AUTH_PROXY
&& establishing_tunnel_
) {
263 // In this case, we've gathered credentials for use with proxy
264 // authentication of a tunnel.
265 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
266 DCHECK(stream_request_
!= NULL
);
267 auth_controllers_
[target
] = NULL
;
268 ResetStateForRestart();
269 rv
= stream_request_
->RestartTunnelWithProxyAuth(credentials
);
271 // In this case, we've gathered credentials for the server or the proxy
272 // but it is not during the tunneling phase.
273 DCHECK(stream_request_
== NULL
);
274 PrepareForAuthRestart(target
);
278 if (rv
== ERR_IO_PENDING
)
279 callback_
= callback
;
283 void HttpNetworkTransaction::PrepareForAuthRestart(HttpAuth::Target target
) {
284 DCHECK(HaveAuth(target
));
285 DCHECK(!stream_request_
.get());
287 bool keep_alive
= false;
288 // Even if the server says the connection is keep-alive, we have to be
289 // able to find the end of each response in order to reuse the connection.
290 if (GetResponseHeaders()->IsKeepAlive() &&
291 stream_
->CanFindEndOfResponse()) {
292 // If the response body hasn't been completely read, we need to drain
294 if (!stream_
->IsResponseBodyComplete()) {
295 next_state_
= STATE_DRAIN_BODY_FOR_AUTH_RESTART
;
296 read_buf_
= new IOBuffer(kDrainBodyBufferSize
); // A bit bucket.
297 read_buf_len_
= kDrainBodyBufferSize
;
303 // We don't need to drain the response body, so we act as if we had drained
304 // the response body.
305 DidDrainBodyForAuthRestart(keep_alive
);
308 void HttpNetworkTransaction::DidDrainBodyForAuthRestart(bool keep_alive
) {
309 DCHECK(!stream_request_
.get());
312 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
313 HttpStream
* new_stream
= NULL
;
314 if (keep_alive
&& stream_
->IsConnectionReusable()) {
315 // We should call connection_->set_idle_time(), but this doesn't occur
316 // often enough to be worth the trouble.
317 stream_
->SetConnectionReused();
319 static_cast<HttpStream
*>(stream_
.get())->RenewStreamForAuth();
323 // Close the stream and mark it as not_reusable. Even in the
324 // keep_alive case, we've determined that the stream_ is not
325 // reusable if new_stream is NULL.
326 stream_
->Close(true);
327 next_state_
= STATE_CREATE_STREAM
;
329 // Renewed streams shouldn't carry over received bytes.
330 DCHECK_EQ(0, new_stream
->GetTotalReceivedBytes());
331 next_state_
= STATE_INIT_STREAM
;
333 stream_
.reset(new_stream
);
336 // Reset the other member variables.
337 ResetStateForAuthRestart();
340 bool HttpNetworkTransaction::IsReadyToRestartForAuth() {
341 return pending_auth_target_
!= HttpAuth::AUTH_NONE
&&
342 HaveAuth(pending_auth_target_
);
345 int HttpNetworkTransaction::Read(IOBuffer
* buf
, int buf_len
,
346 const CompletionCallback
& callback
) {
348 DCHECK_LT(0, buf_len
);
350 State next_state
= STATE_NONE
;
352 scoped_refptr
<HttpResponseHeaders
> headers(GetResponseHeaders());
353 if (headers_valid_
&& headers
.get() && stream_request_
.get()) {
354 // We're trying to read the body of the response but we're still trying
355 // to establish an SSL tunnel through an HTTP proxy. We can't read these
356 // bytes when establishing a tunnel because they might be controlled by
357 // an active network attacker. We don't worry about this for HTTP
358 // because an active network attacker can already control HTTP sessions.
359 // We reach this case when the user cancels a 407 proxy auth prompt. We
360 // also don't worry about this for an HTTPS Proxy, because the
361 // communication with the proxy is secure.
362 // See http://crbug.com/8473.
363 DCHECK(proxy_info_
.is_http() || proxy_info_
.is_https());
364 DCHECK_EQ(headers
->response_code(), HTTP_PROXY_AUTHENTICATION_REQUIRED
);
365 LOG(WARNING
) << "Blocked proxy response with status "
366 << headers
->response_code() << " to CONNECT request for "
367 << GetHostAndPort(request_
->url
) << ".";
368 return ERR_TUNNEL_CONNECTION_FAILED
;
371 // Are we using SPDY or HTTP?
372 next_state
= STATE_READ_BODY
;
375 read_buf_len_
= buf_len
;
377 next_state_
= next_state
;
379 if (rv
== ERR_IO_PENDING
)
380 callback_
= callback
;
384 void HttpNetworkTransaction::StopCaching() {}
386 bool HttpNetworkTransaction::GetFullRequestHeaders(
387 HttpRequestHeaders
* headers
) const {
388 // TODO(ttuttle): Make sure we've populated request_headers_.
389 *headers
= request_headers_
;
393 int64
HttpNetworkTransaction::GetTotalReceivedBytes() const {
394 int64 total_received_bytes
= total_received_bytes_
;
396 total_received_bytes
+= stream_
->GetTotalReceivedBytes();
397 return total_received_bytes
;
400 void HttpNetworkTransaction::DoneReading() {}
402 const HttpResponseInfo
* HttpNetworkTransaction::GetResponseInfo() const {
403 return ((headers_valid_
&& response_
.headers
.get()) ||
404 response_
.ssl_info
.cert
.get() || response_
.cert_request_info
.get())
409 LoadState
HttpNetworkTransaction::GetLoadState() const {
410 // TODO(wtc): Define a new LoadState value for the
411 // STATE_INIT_CONNECTION_COMPLETE state, which delays the HTTP request.
412 switch (next_state_
) {
413 case STATE_CREATE_STREAM
:
414 return LOAD_STATE_WAITING_FOR_DELEGATE
;
415 case STATE_CREATE_STREAM_COMPLETE
:
416 return stream_request_
->GetLoadState();
417 case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
:
418 case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE
:
419 case STATE_SEND_REQUEST_COMPLETE
:
420 return LOAD_STATE_SENDING_REQUEST
;
421 case STATE_READ_HEADERS_COMPLETE
:
422 return LOAD_STATE_WAITING_FOR_RESPONSE
;
423 case STATE_READ_BODY_COMPLETE
:
424 return LOAD_STATE_READING_RESPONSE
;
426 return LOAD_STATE_IDLE
;
430 UploadProgress
HttpNetworkTransaction::GetUploadProgress() const {
432 return UploadProgress();
434 // TODO(bashi): This cast is temporary. Remove later.
435 return static_cast<HttpStream
*>(stream_
.get())->GetUploadProgress();
438 void HttpNetworkTransaction::SetQuicServerInfo(
439 QuicServerInfo
* quic_server_info
) {}
441 bool HttpNetworkTransaction::GetLoadTimingInfo(
442 LoadTimingInfo
* load_timing_info
) const {
443 if (!stream_
|| !stream_
->GetLoadTimingInfo(load_timing_info
))
446 load_timing_info
->proxy_resolve_start
=
447 proxy_info_
.proxy_resolve_start_time();
448 load_timing_info
->proxy_resolve_end
= proxy_info_
.proxy_resolve_end_time();
449 load_timing_info
->send_start
= send_start_time_
;
450 load_timing_info
->send_end
= send_end_time_
;
454 void HttpNetworkTransaction::SetPriority(RequestPriority priority
) {
455 priority_
= priority
;
457 stream_request_
->SetPriority(priority
);
459 stream_
->SetPriority(priority
);
462 void HttpNetworkTransaction::SetWebSocketHandshakeStreamCreateHelper(
463 WebSocketHandshakeStreamBase::CreateHelper
* create_helper
) {
464 websocket_handshake_stream_base_create_helper_
= create_helper
;
467 void HttpNetworkTransaction::SetBeforeNetworkStartCallback(
468 const BeforeNetworkStartCallback
& callback
) {
469 before_network_start_callback_
= callback
;
472 void HttpNetworkTransaction::SetBeforeProxyHeadersSentCallback(
473 const BeforeProxyHeadersSentCallback
& callback
) {
474 before_proxy_headers_sent_callback_
= callback
;
477 int HttpNetworkTransaction::ResumeNetworkStart() {
478 DCHECK_EQ(next_state_
, STATE_CREATE_STREAM
);
482 void HttpNetworkTransaction::OnStreamReady(const SSLConfig
& used_ssl_config
,
483 const ProxyInfo
& used_proxy_info
,
484 HttpStreamBase
* stream
) {
485 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
486 DCHECK(stream_request_
.get());
489 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
490 stream_
.reset(stream
);
491 server_ssl_config_
= used_ssl_config
;
492 proxy_info_
= used_proxy_info
;
493 response_
.was_npn_negotiated
= stream_request_
->was_npn_negotiated();
494 response_
.npn_negotiated_protocol
= SSLClientSocket::NextProtoToString(
495 stream_request_
->protocol_negotiated());
496 response_
.was_fetched_via_spdy
= stream_request_
->using_spdy();
497 response_
.was_fetched_via_proxy
= !proxy_info_
.is_direct();
498 if (response_
.was_fetched_via_proxy
&& !proxy_info_
.is_empty())
499 response_
.proxy_server
= proxy_info_
.proxy_server().host_port_pair();
503 void HttpNetworkTransaction::OnWebSocketHandshakeStreamReady(
504 const SSLConfig
& used_ssl_config
,
505 const ProxyInfo
& used_proxy_info
,
506 WebSocketHandshakeStreamBase
* stream
) {
507 OnStreamReady(used_ssl_config
, used_proxy_info
, stream
);
510 void HttpNetworkTransaction::OnStreamFailed(int result
,
511 const SSLConfig
& used_ssl_config
) {
512 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
513 DCHECK_NE(OK
, result
);
514 DCHECK(stream_request_
.get());
515 DCHECK(!stream_
.get());
516 server_ssl_config_
= used_ssl_config
;
518 OnIOComplete(result
);
521 void HttpNetworkTransaction::OnCertificateError(
523 const SSLConfig
& used_ssl_config
,
524 const SSLInfo
& ssl_info
) {
525 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
526 DCHECK_NE(OK
, result
);
527 DCHECK(stream_request_
.get());
528 DCHECK(!stream_
.get());
530 response_
.ssl_info
= ssl_info
;
531 server_ssl_config_
= used_ssl_config
;
533 // TODO(mbelshe): For now, we're going to pass the error through, and that
534 // will close the stream_request in all cases. This means that we're always
535 // going to restart an entire STATE_CREATE_STREAM, even if the connection is
536 // good and the user chooses to ignore the error. This is not ideal, but not
537 // the end of the world either.
539 OnIOComplete(result
);
542 void HttpNetworkTransaction::OnNeedsProxyAuth(
543 const HttpResponseInfo
& proxy_response
,
544 const SSLConfig
& used_ssl_config
,
545 const ProxyInfo
& used_proxy_info
,
546 HttpAuthController
* auth_controller
) {
547 DCHECK(stream_request_
.get());
548 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
550 establishing_tunnel_
= true;
551 response_
.headers
= proxy_response
.headers
;
552 response_
.auth_challenge
= proxy_response
.auth_challenge
;
553 headers_valid_
= true;
554 server_ssl_config_
= used_ssl_config
;
555 proxy_info_
= used_proxy_info
;
557 auth_controllers_
[HttpAuth::AUTH_PROXY
] = auth_controller
;
558 pending_auth_target_
= HttpAuth::AUTH_PROXY
;
563 void HttpNetworkTransaction::OnNeedsClientAuth(
564 const SSLConfig
& used_ssl_config
,
565 SSLCertRequestInfo
* cert_info
) {
566 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
568 server_ssl_config_
= used_ssl_config
;
569 response_
.cert_request_info
= cert_info
;
570 OnIOComplete(ERR_SSL_CLIENT_AUTH_CERT_NEEDED
);
573 void HttpNetworkTransaction::OnHttpsProxyTunnelResponse(
574 const HttpResponseInfo
& response_info
,
575 const SSLConfig
& used_ssl_config
,
576 const ProxyInfo
& used_proxy_info
,
577 HttpStreamBase
* stream
) {
578 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
580 headers_valid_
= true;
581 response_
= response_info
;
582 server_ssl_config_
= used_ssl_config
;
583 proxy_info_
= used_proxy_info
;
585 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
586 stream_
.reset(stream
);
587 stream_request_
.reset(); // we're done with the stream request
588 OnIOComplete(ERR_HTTPS_PROXY_TUNNEL_RESPONSE
);
591 bool HttpNetworkTransaction::is_https_request() const {
592 return request_
->url
.SchemeIs("https");
595 void HttpNetworkTransaction::DoCallback(int rv
) {
596 DCHECK_NE(rv
, ERR_IO_PENDING
);
597 DCHECK(!callback_
.is_null());
599 // Since Run may result in Read being called, clear user_callback_ up front.
600 CompletionCallback c
= callback_
;
605 void HttpNetworkTransaction::OnIOComplete(int result
) {
606 int rv
= DoLoop(result
);
607 if (rv
!= ERR_IO_PENDING
)
611 int HttpNetworkTransaction::DoLoop(int result
) {
612 DCHECK(next_state_
!= STATE_NONE
);
616 State state
= next_state_
;
617 next_state_
= STATE_NONE
;
619 case STATE_NOTIFY_BEFORE_CREATE_STREAM
:
621 rv
= DoNotifyBeforeCreateStream();
623 case STATE_CREATE_STREAM
:
625 rv
= DoCreateStream();
627 case STATE_CREATE_STREAM_COMPLETE
:
628 rv
= DoCreateStreamComplete(rv
);
630 case STATE_INIT_STREAM
:
634 case STATE_INIT_STREAM_COMPLETE
:
635 rv
= DoInitStreamComplete(rv
);
637 case STATE_GENERATE_PROXY_AUTH_TOKEN
:
639 rv
= DoGenerateProxyAuthToken();
641 case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
:
642 rv
= DoGenerateProxyAuthTokenComplete(rv
);
644 case STATE_GENERATE_SERVER_AUTH_TOKEN
:
646 rv
= DoGenerateServerAuthToken();
648 case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE
:
649 rv
= DoGenerateServerAuthTokenComplete(rv
);
651 case STATE_INIT_REQUEST_BODY
:
653 rv
= DoInitRequestBody();
655 case STATE_INIT_REQUEST_BODY_COMPLETE
:
656 rv
= DoInitRequestBodyComplete(rv
);
658 case STATE_BUILD_REQUEST
:
660 net_log_
.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST
);
661 rv
= DoBuildRequest();
663 case STATE_BUILD_REQUEST_COMPLETE
:
664 rv
= DoBuildRequestComplete(rv
);
666 case STATE_SEND_REQUEST
:
668 rv
= DoSendRequest();
670 case STATE_SEND_REQUEST_COMPLETE
:
671 rv
= DoSendRequestComplete(rv
);
672 net_log_
.EndEventWithNetErrorCode(
673 NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST
, rv
);
675 case STATE_READ_HEADERS
:
677 net_log_
.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS
);
678 rv
= DoReadHeaders();
680 case STATE_READ_HEADERS_COMPLETE
:
681 rv
= DoReadHeadersComplete(rv
);
682 net_log_
.EndEventWithNetErrorCode(
683 NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS
, rv
);
685 case STATE_READ_BODY
:
687 net_log_
.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_BODY
);
690 case STATE_READ_BODY_COMPLETE
:
691 rv
= DoReadBodyComplete(rv
);
692 net_log_
.EndEventWithNetErrorCode(
693 NetLog::TYPE_HTTP_TRANSACTION_READ_BODY
, rv
);
695 case STATE_DRAIN_BODY_FOR_AUTH_RESTART
:
698 NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART
);
699 rv
= DoDrainBodyForAuthRestart();
701 case STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE
:
702 rv
= DoDrainBodyForAuthRestartComplete(rv
);
703 net_log_
.EndEventWithNetErrorCode(
704 NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART
, rv
);
707 NOTREACHED() << "bad state";
711 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
716 int HttpNetworkTransaction::DoNotifyBeforeCreateStream() {
717 next_state_
= STATE_CREATE_STREAM
;
719 if (!before_network_start_callback_
.is_null())
720 before_network_start_callback_
.Run(&defer
);
723 return ERR_IO_PENDING
;
726 int HttpNetworkTransaction::DoCreateStream() {
727 next_state_
= STATE_CREATE_STREAM_COMPLETE
;
728 if (ForWebSocketHandshake()) {
729 stream_request_
.reset(
730 session_
->http_stream_factory_for_websocket()
731 ->RequestWebSocketHandshakeStream(
737 websocket_handshake_stream_base_create_helper_
,
740 stream_request_
.reset(
741 session_
->http_stream_factory()->RequestStream(
749 DCHECK(stream_request_
.get());
750 return ERR_IO_PENDING
;
753 int HttpNetworkTransaction::DoCreateStreamComplete(int result
) {
755 next_state_
= STATE_INIT_STREAM
;
756 DCHECK(stream_
.get());
757 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
758 result
= HandleCertificateRequest(result
);
759 } else if (result
== ERR_HTTPS_PROXY_TUNNEL_RESPONSE
) {
760 // Return OK and let the caller read the proxy's error page
761 next_state_
= STATE_NONE
;
765 // Handle possible handshake errors that may have occurred if the stream
766 // used SSL for one or more of the layers.
767 result
= HandleSSLHandshakeError(result
);
769 // At this point we are done with the stream_request_.
770 stream_request_
.reset();
774 int HttpNetworkTransaction::DoInitStream() {
775 DCHECK(stream_
.get());
776 next_state_
= STATE_INIT_STREAM_COMPLETE
;
777 return stream_
->InitializeStream(request_
, priority_
, net_log_
, io_callback_
);
780 int HttpNetworkTransaction::DoInitStreamComplete(int result
) {
782 next_state_
= STATE_GENERATE_PROXY_AUTH_TOKEN
;
785 result
= HandleIOError(result
);
787 // The stream initialization failed, so this stream will never be useful.
789 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
796 int HttpNetworkTransaction::DoGenerateProxyAuthToken() {
797 next_state_
= STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
;
798 if (!ShouldApplyProxyAuth())
800 HttpAuth::Target target
= HttpAuth::AUTH_PROXY
;
801 if (!auth_controllers_
[target
].get())
802 auth_controllers_
[target
] =
803 new HttpAuthController(target
,
805 session_
->http_auth_cache(),
806 session_
->http_auth_handler_factory());
807 return auth_controllers_
[target
]->MaybeGenerateAuthToken(request_
,
812 int HttpNetworkTransaction::DoGenerateProxyAuthTokenComplete(int rv
) {
813 DCHECK_NE(ERR_IO_PENDING
, rv
);
815 next_state_
= STATE_GENERATE_SERVER_AUTH_TOKEN
;
819 int HttpNetworkTransaction::DoGenerateServerAuthToken() {
820 next_state_
= STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE
;
821 HttpAuth::Target target
= HttpAuth::AUTH_SERVER
;
822 if (!auth_controllers_
[target
].get()) {
823 auth_controllers_
[target
] =
824 new HttpAuthController(target
,
826 session_
->http_auth_cache(),
827 session_
->http_auth_handler_factory());
828 if (request_
->load_flags
& LOAD_DO_NOT_USE_EMBEDDED_IDENTITY
)
829 auth_controllers_
[target
]->DisableEmbeddedIdentity();
831 if (!ShouldApplyServerAuth())
833 return auth_controllers_
[target
]->MaybeGenerateAuthToken(request_
,
838 int HttpNetworkTransaction::DoGenerateServerAuthTokenComplete(int rv
) {
839 DCHECK_NE(ERR_IO_PENDING
, rv
);
841 next_state_
= STATE_INIT_REQUEST_BODY
;
845 void HttpNetworkTransaction::BuildRequestHeaders(bool using_proxy
) {
846 request_headers_
.SetHeader(HttpRequestHeaders::kHost
,
847 GetHostAndOptionalPort(request_
->url
));
849 // For compat with HTTP/1.0 servers and proxies:
851 request_headers_
.SetHeader(HttpRequestHeaders::kProxyConnection
,
854 request_headers_
.SetHeader(HttpRequestHeaders::kConnection
, "keep-alive");
857 // Add a content length header?
858 if (request_
->upload_data_stream
) {
859 if (request_
->upload_data_stream
->is_chunked()) {
860 request_headers_
.SetHeader(
861 HttpRequestHeaders::kTransferEncoding
, "chunked");
863 request_headers_
.SetHeader(
864 HttpRequestHeaders::kContentLength
,
865 base::Uint64ToString(request_
->upload_data_stream
->size()));
867 } else if (request_
->method
== "POST" || request_
->method
== "PUT" ||
868 request_
->method
== "HEAD") {
869 // An empty POST/PUT request still needs a content length. As for HEAD,
870 // IE and Safari also add a content length header. Presumably it is to
871 // support sending a HEAD request to an URL that only expects to be sent a
872 // POST or some other method that normally would have a message body.
873 request_headers_
.SetHeader(HttpRequestHeaders::kContentLength
, "0");
876 // Honor load flags that impact proxy caches.
877 if (request_
->load_flags
& LOAD_BYPASS_CACHE
) {
878 request_headers_
.SetHeader(HttpRequestHeaders::kPragma
, "no-cache");
879 request_headers_
.SetHeader(HttpRequestHeaders::kCacheControl
, "no-cache");
880 } else if (request_
->load_flags
& LOAD_VALIDATE_CACHE
) {
881 request_headers_
.SetHeader(HttpRequestHeaders::kCacheControl
, "max-age=0");
884 if (ShouldApplyProxyAuth() && HaveAuth(HttpAuth::AUTH_PROXY
))
885 auth_controllers_
[HttpAuth::AUTH_PROXY
]->AddAuthorizationHeader(
887 if (ShouldApplyServerAuth() && HaveAuth(HttpAuth::AUTH_SERVER
))
888 auth_controllers_
[HttpAuth::AUTH_SERVER
]->AddAuthorizationHeader(
891 request_headers_
.MergeFrom(request_
->extra_headers
);
893 if (using_proxy
&& !before_proxy_headers_sent_callback_
.is_null())
894 before_proxy_headers_sent_callback_
.Run(proxy_info_
, &request_headers_
);
896 response_
.did_use_http_auth
=
897 request_headers_
.HasHeader(HttpRequestHeaders::kAuthorization
) ||
898 request_headers_
.HasHeader(HttpRequestHeaders::kProxyAuthorization
);
901 int HttpNetworkTransaction::DoInitRequestBody() {
902 next_state_
= STATE_INIT_REQUEST_BODY_COMPLETE
;
904 if (request_
->upload_data_stream
)
905 rv
= request_
->upload_data_stream
->Init(io_callback_
);
909 int HttpNetworkTransaction::DoInitRequestBodyComplete(int result
) {
911 next_state_
= STATE_BUILD_REQUEST
;
915 int HttpNetworkTransaction::DoBuildRequest() {
916 next_state_
= STATE_BUILD_REQUEST_COMPLETE
;
917 headers_valid_
= false;
919 // This is constructed lazily (instead of within our Start method), so that
920 // we have proxy info available.
921 if (request_headers_
.IsEmpty()) {
922 bool using_proxy
= (proxy_info_
.is_http() || proxy_info_
.is_https()) &&
924 BuildRequestHeaders(using_proxy
);
930 int HttpNetworkTransaction::DoBuildRequestComplete(int result
) {
932 next_state_
= STATE_SEND_REQUEST
;
936 int HttpNetworkTransaction::DoSendRequest() {
937 send_start_time_
= base::TimeTicks::Now();
938 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
940 return stream_
->SendRequest(request_headers_
, &response_
, io_callback_
);
943 int HttpNetworkTransaction::DoSendRequestComplete(int result
) {
944 send_end_time_
= base::TimeTicks::Now();
946 return HandleIOError(result
);
947 response_
.network_accessed
= true;
948 next_state_
= STATE_READ_HEADERS
;
952 int HttpNetworkTransaction::DoReadHeaders() {
953 next_state_
= STATE_READ_HEADERS_COMPLETE
;
954 return stream_
->ReadResponseHeaders(io_callback_
);
957 int HttpNetworkTransaction::DoReadHeadersComplete(int result
) {
958 // We can get a certificate error or ERR_SSL_CLIENT_AUTH_CERT_NEEDED here
959 // due to SSL renegotiation.
960 if (IsCertificateError(result
)) {
961 // We don't handle a certificate error during SSL renegotiation, so we
962 // have to return an error that's not in the certificate error range
964 LOG(ERROR
) << "Got a server certificate with error " << result
965 << " during SSL renegotiation";
966 result
= ERR_CERT_ERROR_IN_SSL_RENEGOTIATION
;
967 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
968 // TODO(wtc): Need a test case for this code path!
969 DCHECK(stream_
.get());
970 DCHECK(is_https_request());
971 response_
.cert_request_info
= new SSLCertRequestInfo
;
972 stream_
->GetSSLCertRequestInfo(response_
.cert_request_info
.get());
973 result
= HandleCertificateRequest(result
);
978 if (result
== ERR_QUIC_HANDSHAKE_FAILED
) {
979 ResetConnectionAndRequestForResend();
983 // After we call RestartWithAuth a new response_time will be recorded, and
984 // we need to be cautious about incorrectly logging the duration across the
985 // authentication activity.
987 LogTransactionConnectedMetrics();
989 // ERR_CONNECTION_CLOSED is treated differently at this point; if partial
990 // response headers were received, we do the best we can to make sense of it
991 // and send it back up the stack.
993 // TODO(davidben): Consider moving this to HttpBasicStream, It's a little
994 // bizarre for SPDY. Assuming this logic is useful at all.
995 // TODO(davidben): Bubble the error code up so we do not cache?
996 if (result
== ERR_CONNECTION_CLOSED
&& response_
.headers
.get())
1000 return HandleIOError(result
);
1002 DCHECK(response_
.headers
.get());
1004 // On a 408 response from the server ("Request Timeout") on a stale socket,
1005 // retry the request.
1006 // Headers can be NULL because of http://crbug.com/384554.
1007 if (response_
.headers
.get() && response_
.headers
->response_code() == 408 &&
1008 stream_
->IsConnectionReused()) {
1009 net_log_
.AddEventWithNetErrorCode(
1010 NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR
,
1011 response_
.headers
->response_code());
1012 // This will close the socket - it would be weird to try and reuse it, even
1013 // if the server doesn't actually close it.
1014 ResetConnectionAndRequestForResend();
1018 // Like Net.HttpResponseCode, but only for MAIN_FRAME loads.
1019 if (request_
->load_flags
& LOAD_MAIN_FRAME
) {
1020 const int response_code
= response_
.headers
->response_code();
1021 UMA_HISTOGRAM_ENUMERATION(
1022 "Net.HttpResponseCode_Nxx_MainFrame", response_code
/100, 10);
1026 NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS
,
1027 base::Bind(&HttpResponseHeaders::NetLogCallback
, response_
.headers
));
1029 if (response_
.headers
->GetParsedHttpVersion() < HttpVersion(1, 0)) {
1030 // HTTP/0.9 doesn't support the PUT method, so lack of response headers
1031 // indicates a buggy server. See:
1032 // https://bugzilla.mozilla.org/show_bug.cgi?id=193921
1033 if (request_
->method
== "PUT")
1034 return ERR_METHOD_NOT_SUPPORTED
;
1037 // Check for an intermediate 100 Continue response. An origin server is
1038 // allowed to send this response even if we didn't ask for it, so we just
1039 // need to skip over it.
1040 // We treat any other 1xx in this same way (although in practice getting
1041 // a 1xx that isn't a 100 is rare).
1042 // Unless this is a WebSocket request, in which case we pass it on up.
1043 if (response_
.headers
->response_code() / 100 == 1 &&
1044 !ForWebSocketHandshake()) {
1045 response_
.headers
= new HttpResponseHeaders(std::string());
1046 next_state_
= STATE_READ_HEADERS
;
1050 HostPortPair endpoint
= HostPortPair(request_
->url
.HostNoBrackets(),
1051 request_
->url
.EffectiveIntPort());
1052 ProcessAlternateProtocol(session_
,
1053 *response_
.headers
.get(),
1056 int rv
= HandleAuthChallenge();
1060 if (is_https_request())
1061 stream_
->GetSSLInfo(&response_
.ssl_info
);
1063 headers_valid_
= true;
1065 if (session_
->huffman_aggregator()) {
1066 session_
->huffman_aggregator()->AggregateTransactionCharacterCounts(
1069 proxy_info_
.proxy_server(),
1070 *response_
.headers
);
1075 int HttpNetworkTransaction::DoReadBody() {
1076 DCHECK(read_buf_
.get());
1077 DCHECK_GT(read_buf_len_
, 0);
1078 DCHECK(stream_
!= NULL
);
1080 next_state_
= STATE_READ_BODY_COMPLETE
;
1081 return stream_
->ReadResponseBody(
1082 read_buf_
.get(), read_buf_len_
, io_callback_
);
1085 int HttpNetworkTransaction::DoReadBodyComplete(int result
) {
1086 // We are done with the Read call.
1089 DCHECK_NE(ERR_IO_PENDING
, result
);
1093 bool keep_alive
= false;
1094 if (stream_
->IsResponseBodyComplete()) {
1095 // Note: Just because IsResponseBodyComplete is true, we're not
1096 // necessarily "done". We're only "done" when it is the last
1097 // read on this HttpNetworkTransaction, which will be signified
1098 // by a zero-length read.
1099 // TODO(mbelshe): The keepalive property is really a property of
1100 // the stream. No need to compute it here just to pass back
1101 // to the stream's Close function.
1102 // TODO(rtenneti): CanFindEndOfResponse should return false if there are no
1104 if (stream_
->CanFindEndOfResponse()) {
1105 HttpResponseHeaders
* headers
= GetResponseHeaders();
1107 keep_alive
= headers
->IsKeepAlive();
1111 // Clean up connection if we are done.
1113 LogTransactionMetrics();
1114 stream_
->Close(!keep_alive
);
1115 // Note: we don't reset the stream here. We've closed it, but we still
1116 // need it around so that callers can call methods such as
1117 // GetUploadProgress() and have them be meaningful.
1118 // TODO(mbelshe): This means we closed the stream here, and we close it
1119 // again in ~HttpNetworkTransaction. Clean that up.
1121 // The next Read call will return 0 (EOF).
1124 // Clear these to avoid leaving around old state.
1131 int HttpNetworkTransaction::DoDrainBodyForAuthRestart() {
1132 // This method differs from DoReadBody only in the next_state_. So we just
1133 // call DoReadBody and override the next_state_. Perhaps there is a more
1134 // elegant way for these two methods to share code.
1135 int rv
= DoReadBody();
1136 DCHECK(next_state_
== STATE_READ_BODY_COMPLETE
);
1137 next_state_
= STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE
;
1141 // TODO(wtc): This method and the DoReadBodyComplete method are almost
1142 // the same. Figure out a good way for these two methods to share code.
1143 int HttpNetworkTransaction::DoDrainBodyForAuthRestartComplete(int result
) {
1144 // keep_alive defaults to true because the very reason we're draining the
1145 // response body is to reuse the connection for auth restart.
1146 bool done
= false, keep_alive
= true;
1148 // Error or closed connection while reading the socket.
1151 } else if (stream_
->IsResponseBodyComplete()) {
1156 DidDrainBodyForAuthRestart(keep_alive
);
1159 next_state_
= STATE_DRAIN_BODY_FOR_AUTH_RESTART
;
1165 void HttpNetworkTransaction::LogTransactionConnectedMetrics() {
1166 if (logged_response_time_
)
1169 logged_response_time_
= true;
1171 base::TimeDelta total_duration
= response_
.response_time
- start_time_
;
1173 UMA_HISTOGRAM_CUSTOM_TIMES(
1174 "Net.Transaction_Connected",
1176 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1179 bool reused_socket
= stream_
->IsConnectionReused();
1180 if (!reused_socket
) {
1181 UMA_HISTOGRAM_CUSTOM_TIMES(
1182 "Net.Transaction_Connected_New_b",
1184 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1188 // Currently, non-HIGHEST priority requests are frame or sub-frame resource
1189 // types. This will change when we also prioritize certain subresources like
1191 if (priority_
!= HIGHEST
) {
1192 UMA_HISTOGRAM_CUSTOM_TIMES(
1193 "Net.Priority_High_Latency_b",
1195 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1198 UMA_HISTOGRAM_CUSTOM_TIMES(
1199 "Net.Priority_Low_Latency_b",
1201 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMinutes(10),
1206 void HttpNetworkTransaction::LogTransactionMetrics() const {
1207 base::TimeDelta duration
= base::Time::Now() -
1208 response_
.request_time
;
1209 if (60 < duration
.InMinutes())
1212 base::TimeDelta total_duration
= base::Time::Now() - start_time_
;
1214 UMA_HISTOGRAM_CUSTOM_TIMES("Net.Transaction_Latency_b", duration
,
1215 base::TimeDelta::FromMilliseconds(1),
1216 base::TimeDelta::FromMinutes(10),
1218 UMA_HISTOGRAM_CUSTOM_TIMES("Net.Transaction_Latency_Total",
1220 base::TimeDelta::FromMilliseconds(1),
1221 base::TimeDelta::FromMinutes(10), 100);
1223 if (!stream_
->IsConnectionReused()) {
1224 UMA_HISTOGRAM_CUSTOM_TIMES(
1225 "Net.Transaction_Latency_Total_New_Connection",
1226 total_duration
, base::TimeDelta::FromMilliseconds(1),
1227 base::TimeDelta::FromMinutes(10), 100);
1231 int HttpNetworkTransaction::HandleCertificateRequest(int error
) {
1232 // There are two paths through which the server can request a certificate
1233 // from us. The first is during the initial handshake, the second is
1234 // during SSL renegotiation.
1236 // In both cases, we want to close the connection before proceeding.
1237 // We do this for two reasons:
1238 // First, we don't want to keep the connection to the server hung for a
1239 // long time while the user selects a certificate.
1240 // Second, even if we did keep the connection open, NSS has a bug where
1241 // restarting the handshake for ClientAuth is currently broken.
1242 DCHECK_EQ(error
, ERR_SSL_CLIENT_AUTH_CERT_NEEDED
);
1244 if (stream_
.get()) {
1245 // Since we already have a stream, we're being called as part of SSL
1247 DCHECK(!stream_request_
.get());
1248 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
1249 stream_
->Close(true);
1253 // The server is asking for a client certificate during the initial
1255 stream_request_
.reset();
1257 // If the user selected one of the certificates in client_certs or declined
1258 // to provide one for this server before, use the past decision
1260 scoped_refptr
<X509Certificate
> client_cert
;
1261 bool found_cached_cert
= session_
->ssl_client_auth_cache()->Lookup(
1262 response_
.cert_request_info
->host_and_port
, &client_cert
);
1263 if (!found_cached_cert
)
1266 // Check that the certificate selected is still a certificate the server
1267 // is likely to accept, based on the criteria supplied in the
1268 // CertificateRequest message.
1269 if (client_cert
.get()) {
1270 const std::vector
<std::string
>& cert_authorities
=
1271 response_
.cert_request_info
->cert_authorities
;
1273 bool cert_still_valid
= cert_authorities
.empty() ||
1274 client_cert
->IsIssuedByEncoded(cert_authorities
);
1275 if (!cert_still_valid
)
1279 // TODO(davidben): Add a unit test which covers this path; we need to be
1280 // able to send a legitimate certificate and also bypass/clear the
1281 // SSL session cache.
1282 SSLConfig
* ssl_config
= response_
.cert_request_info
->is_proxy
?
1283 &proxy_ssl_config_
: &server_ssl_config_
;
1284 ssl_config
->send_client_cert
= true;
1285 ssl_config
->client_cert
= client_cert
;
1286 next_state_
= STATE_CREATE_STREAM
;
1287 // Reset the other member variables.
1288 // Note: this is necessary only with SSL renegotiation.
1289 ResetStateForRestart();
1293 void HttpNetworkTransaction::HandleClientAuthError(int error
) {
1294 if (server_ssl_config_
.send_client_cert
&&
1295 (error
== ERR_SSL_PROTOCOL_ERROR
|| IsClientCertificateError(error
))) {
1296 session_
->ssl_client_auth_cache()->Remove(
1297 HostPortPair::FromURL(request_
->url
));
1301 // TODO(rch): This does not correctly handle errors when an SSL proxy is
1302 // being used, as all of the errors are handled as if they were generated
1303 // by the endpoint host, request_->url, rather than considering if they were
1304 // generated by the SSL proxy. http://crbug.com/69329
1305 int HttpNetworkTransaction::HandleSSLHandshakeError(int error
) {
1307 HandleClientAuthError(error
);
1309 bool should_fallback
= false;
1310 uint16 version_max
= server_ssl_config_
.version_max
;
1313 case ERR_CONNECTION_CLOSED
:
1314 case ERR_SSL_PROTOCOL_ERROR
:
1315 case ERR_SSL_VERSION_OR_CIPHER_MISMATCH
:
1316 if (version_max
>= SSL_PROTOCOL_VERSION_TLS1
&&
1317 version_max
> server_ssl_config_
.version_min
) {
1318 // This could be a TLS-intolerant server or a server that chose a
1319 // cipher suite defined only for higher protocol versions (such as
1320 // an SSL 3.0 server that chose a TLS-only cipher suite). Fall
1321 // back to the next lower version and retry.
1322 // NOTE: if the SSLClientSocket class doesn't support TLS 1.1,
1323 // specifying TLS 1.1 in version_max will result in a TLS 1.0
1324 // handshake, so falling back from TLS 1.1 to TLS 1.0 will simply
1325 // repeat the TLS 1.0 handshake. To avoid this problem, the default
1326 // version_max should match the maximum protocol version supported
1327 // by the SSLClientSocket class.
1330 // Fallback to the lower SSL version.
1331 // While SSL 3.0 fallback should be eliminated because of security
1332 // reasons, there is a high risk of breaking the servers if this is
1334 should_fallback
= true;
1337 case ERR_CONNECTION_RESET
:
1338 if (version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
&&
1339 version_max
> server_ssl_config_
.version_min
) {
1340 // Some network devices that inspect application-layer packets seem to
1341 // inject TCP reset packets to break the connections when they see TLS
1342 // 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
1344 // Only allow ERR_CONNECTION_RESET to trigger a fallback from TLS 1.1 or
1345 // 1.2. We don't lose much in this fallback because the explicit IV for
1346 // CBC mode in TLS 1.1 is approximated by record splitting in TLS
1347 // 1.0. The fallback will be more painful for TLS 1.2 when we have GCM
1350 // ERR_CONNECTION_RESET is a common network error, so we don't want it
1351 // to trigger a version fallback in general, especially the TLS 1.0 ->
1352 // SSL 3.0 fallback, which would drop TLS extensions.
1354 should_fallback
= true;
1357 case ERR_SSL_BAD_RECORD_MAC_ALERT
:
1358 if (version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
&&
1359 version_max
> server_ssl_config_
.version_min
) {
1360 // Some broken SSL devices negotiate TLS 1.0 when sent a TLS 1.1 or
1361 // 1.2 ClientHello, but then return a bad_record_mac alert. See
1362 // crbug.com/260358. In order to make the fallback as minimal as
1363 // possible, this fallback is only triggered for >= TLS 1.1.
1365 should_fallback
= true;
1368 case ERR_SSL_INAPPROPRIATE_FALLBACK
:
1369 // The server told us that we should not have fallen back. A buggy server
1370 // could trigger ERR_SSL_INAPPROPRIATE_FALLBACK with the initial
1371 // connection. |fallback_error_code_| is initialised to
1372 // ERR_SSL_INAPPROPRIATE_FALLBACK to catch this case.
1373 error
= fallback_error_code_
;
1377 if (should_fallback
) {
1379 NetLog::TYPE_SSL_VERSION_FALLBACK
,
1380 base::Bind(&NetLogSSLVersionFallbackCallback
,
1381 &request_
->url
, error
, server_ssl_config_
.version_max
,
1383 fallback_error_code_
= error
;
1384 server_ssl_config_
.version_max
= version_max
;
1385 server_ssl_config_
.version_fallback
= true;
1386 ResetConnectionAndRequestForResend();
1393 // This method determines whether it is safe to resend the request after an
1394 // IO error. It can only be called in response to request header or body
1395 // write errors or response header read errors. It should not be used in
1396 // other cases, such as a Connect error.
1397 int HttpNetworkTransaction::HandleIOError(int error
) {
1398 // Because the peer may request renegotiation with client authentication at
1399 // any time, check and handle client authentication errors.
1400 HandleClientAuthError(error
);
1403 // If we try to reuse a connection that the server is in the process of
1404 // closing, we may end up successfully writing out our request (or a
1405 // portion of our request) only to find a connection error when we try to
1406 // read from (or finish writing to) the socket.
1407 case ERR_CONNECTION_RESET
:
1408 case ERR_CONNECTION_CLOSED
:
1409 case ERR_CONNECTION_ABORTED
:
1410 // There can be a race between the socket pool checking checking whether a
1411 // socket is still connected, receiving the FIN, and sending/reading data
1412 // on a reused socket. If we receive the FIN between the connectedness
1413 // check and writing/reading from the socket, we may first learn the socket
1414 // is disconnected when we get a ERR_SOCKET_NOT_CONNECTED. This will most
1415 // likely happen when trying to retrieve its IP address.
1416 // See http://crbug.com/105824 for more details.
1417 case ERR_SOCKET_NOT_CONNECTED
:
1418 // If a socket is closed on its initial request, HttpStreamParser returns
1419 // ERR_EMPTY_RESPONSE. This may still be close/reuse race if the socket was
1420 // preconnected but failed to be used before the server timed it out.
1421 case ERR_EMPTY_RESPONSE
:
1422 if (ShouldResendRequest()) {
1423 net_log_
.AddEventWithNetErrorCode(
1424 NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR
, error
);
1425 ResetConnectionAndRequestForResend();
1429 case ERR_SPDY_PING_FAILED
:
1430 case ERR_SPDY_SERVER_REFUSED_STREAM
:
1431 case ERR_QUIC_HANDSHAKE_FAILED
:
1432 net_log_
.AddEventWithNetErrorCode(
1433 NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR
, error
);
1434 ResetConnectionAndRequestForResend();
1441 void HttpNetworkTransaction::ResetStateForRestart() {
1442 ResetStateForAuthRestart();
1444 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
1448 void HttpNetworkTransaction::ResetStateForAuthRestart() {
1449 send_start_time_
= base::TimeTicks();
1450 send_end_time_
= base::TimeTicks();
1452 pending_auth_target_
= HttpAuth::AUTH_NONE
;
1455 headers_valid_
= false;
1456 request_headers_
.Clear();
1457 response_
= HttpResponseInfo();
1458 establishing_tunnel_
= false;
1461 HttpResponseHeaders
* HttpNetworkTransaction::GetResponseHeaders() const {
1462 return response_
.headers
.get();
1465 bool HttpNetworkTransaction::ShouldResendRequest() const {
1466 bool connection_is_proven
= stream_
->IsConnectionReused();
1467 bool has_received_headers
= GetResponseHeaders() != NULL
;
1469 // NOTE: we resend a request only if we reused a keep-alive connection.
1470 // This automatically prevents an infinite resend loop because we'll run
1471 // out of the cached keep-alive connections eventually.
1472 if (connection_is_proven
&& !has_received_headers
)
1477 void HttpNetworkTransaction::ResetConnectionAndRequestForResend() {
1478 if (stream_
.get()) {
1479 stream_
->Close(true);
1483 // We need to clear request_headers_ because it contains the real request
1484 // headers, but we may need to resend the CONNECT request first to recreate
1486 request_headers_
.Clear();
1487 next_state_
= STATE_CREATE_STREAM
; // Resend the request.
1490 bool HttpNetworkTransaction::ShouldApplyProxyAuth() const {
1491 return !is_https_request() &&
1492 (proxy_info_
.is_https() || proxy_info_
.is_http());
1495 bool HttpNetworkTransaction::ShouldApplyServerAuth() const {
1496 return !(request_
->load_flags
& LOAD_DO_NOT_SEND_AUTH_DATA
);
1499 int HttpNetworkTransaction::HandleAuthChallenge() {
1500 scoped_refptr
<HttpResponseHeaders
> headers(GetResponseHeaders());
1501 DCHECK(headers
.get());
1503 int status
= headers
->response_code();
1504 if (status
!= HTTP_UNAUTHORIZED
&&
1505 status
!= HTTP_PROXY_AUTHENTICATION_REQUIRED
)
1507 HttpAuth::Target target
= status
== HTTP_PROXY_AUTHENTICATION_REQUIRED
?
1508 HttpAuth::AUTH_PROXY
: HttpAuth::AUTH_SERVER
;
1509 if (target
== HttpAuth::AUTH_PROXY
&& proxy_info_
.is_direct())
1510 return ERR_UNEXPECTED_PROXY_AUTH
;
1512 // This case can trigger when an HTTPS server responds with a "Proxy
1513 // authentication required" status code through a non-authenticating
1515 if (!auth_controllers_
[target
].get())
1516 return ERR_UNEXPECTED_PROXY_AUTH
;
1518 int rv
= auth_controllers_
[target
]->HandleAuthChallenge(
1519 headers
, (request_
->load_flags
& LOAD_DO_NOT_SEND_AUTH_DATA
) != 0, false,
1521 if (auth_controllers_
[target
]->HaveAuthHandler())
1522 pending_auth_target_
= target
;
1524 scoped_refptr
<AuthChallengeInfo
> auth_info
=
1525 auth_controllers_
[target
]->auth_info();
1526 if (auth_info
.get())
1527 response_
.auth_challenge
= auth_info
;
1532 bool HttpNetworkTransaction::HaveAuth(HttpAuth::Target target
) const {
1533 return auth_controllers_
[target
].get() &&
1534 auth_controllers_
[target
]->HaveAuth();
1537 GURL
HttpNetworkTransaction::AuthURL(HttpAuth::Target target
) const {
1539 case HttpAuth::AUTH_PROXY
: {
1540 if (!proxy_info_
.proxy_server().is_valid() ||
1541 proxy_info_
.proxy_server().is_direct()) {
1542 return GURL(); // There is no proxy server.
1544 const char* scheme
= proxy_info_
.is_https() ? "https://" : "http://";
1545 return GURL(scheme
+
1546 proxy_info_
.proxy_server().host_port_pair().ToString());
1548 case HttpAuth::AUTH_SERVER
:
1549 if (ForWebSocketHandshake()) {
1550 const GURL
& url
= request_
->url
;
1551 url::Replacements
<char> ws_to_http
;
1552 if (url
.SchemeIs("ws")) {
1553 ws_to_http
.SetScheme("http", url::Component(0, 4));
1555 DCHECK(url
.SchemeIs("wss"));
1556 ws_to_http
.SetScheme("https", url::Component(0, 5));
1558 return url
.ReplaceComponents(ws_to_http
);
1560 return request_
->url
;
1566 bool HttpNetworkTransaction::ForWebSocketHandshake() const {
1567 return websocket_handshake_stream_base_create_helper_
&&
1568 request_
->url
.SchemeIsWSOrWSS();
1571 #define STATE_CASE(s) \
1573 description = base::StringPrintf("%s (0x%08X)", #s, s); \
1576 std::string
HttpNetworkTransaction::DescribeState(State state
) {
1577 std::string description
;
1579 STATE_CASE(STATE_NOTIFY_BEFORE_CREATE_STREAM
);
1580 STATE_CASE(STATE_CREATE_STREAM
);
1581 STATE_CASE(STATE_CREATE_STREAM_COMPLETE
);
1582 STATE_CASE(STATE_INIT_REQUEST_BODY
);
1583 STATE_CASE(STATE_INIT_REQUEST_BODY_COMPLETE
);
1584 STATE_CASE(STATE_BUILD_REQUEST
);
1585 STATE_CASE(STATE_BUILD_REQUEST_COMPLETE
);
1586 STATE_CASE(STATE_SEND_REQUEST
);
1587 STATE_CASE(STATE_SEND_REQUEST_COMPLETE
);
1588 STATE_CASE(STATE_READ_HEADERS
);
1589 STATE_CASE(STATE_READ_HEADERS_COMPLETE
);
1590 STATE_CASE(STATE_READ_BODY
);
1591 STATE_CASE(STATE_READ_BODY_COMPLETE
);
1592 STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART
);
1593 STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE
);
1594 STATE_CASE(STATE_NONE
);
1596 description
= base::StringPrintf("Unknown state 0x%08X (%u)", state
,