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_macros.h"
17 #include "base/metrics/sparse_histogram.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/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"
70 void ProcessAlternativeServices(HttpNetworkSession
* session
,
71 const HttpResponseHeaders
& headers
,
72 const HostPortPair
& http_host_port_pair
) {
73 if (session
->params().use_alternative_services
&&
74 headers
.HasHeader(kAlternativeServiceHeader
)) {
75 std::string alternative_service_str
;
76 headers
.GetNormalizedHeader(kAlternativeServiceHeader
,
77 &alternative_service_str
);
78 session
->http_stream_factory()->ProcessAlternativeService(
79 session
->http_server_properties(), alternative_service_str
,
80 http_host_port_pair
, *session
);
81 // If there is an "Alt-Svc" header, then ignore "Alternate-Protocol".
85 if (!headers
.HasHeader(kAlternateProtocolHeader
))
88 std::vector
<std::string
> alternate_protocol_values
;
90 std::string alternate_protocol_str
;
91 while (headers
.EnumerateHeader(&iter
, kAlternateProtocolHeader
,
92 &alternate_protocol_str
)) {
93 base::TrimWhitespaceASCII(alternate_protocol_str
, base::TRIM_ALL
,
94 &alternate_protocol_str
);
95 if (!alternate_protocol_str
.empty()) {
96 alternate_protocol_values
.push_back(alternate_protocol_str
);
100 session
->http_stream_factory()->ProcessAlternateProtocol(
101 session
->http_server_properties(),
102 alternate_protocol_values
,
107 scoped_ptr
<base::Value
> NetLogSSLVersionFallbackCallback(
110 SSLFailureState ssl_failure_state
,
111 uint16 version_before
,
112 uint16 version_after
,
113 NetLogCaptureMode
/* capture_mode */) {
114 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
115 dict
->SetString("host_and_port", GetHostAndPort(*url
));
116 dict
->SetInteger("net_error", net_error
);
117 dict
->SetInteger("ssl_failure_state", ssl_failure_state
);
118 dict
->SetInteger("version_before", version_before
);
119 dict
->SetInteger("version_after", version_after
);
123 scoped_ptr
<base::Value
> NetLogSSLCipherFallbackCallback(
126 NetLogCaptureMode
/* capture_mode */) {
127 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
128 dict
->SetString("host_and_port", GetHostAndPort(*url
));
129 dict
->SetInteger("net_error", net_error
);
135 //-----------------------------------------------------------------------------
137 HttpNetworkTransaction::HttpNetworkTransaction(RequestPriority priority
,
138 HttpNetworkSession
* session
)
139 : pending_auth_target_(HttpAuth::AUTH_NONE
),
140 io_callback_(base::Bind(&HttpNetworkTransaction::OnIOComplete
,
141 base::Unretained(this))),
145 headers_valid_(false),
146 server_ssl_failure_state_(SSL_FAILURE_NONE
),
147 fallback_error_code_(ERR_SSL_INAPPROPRIATE_FALLBACK
),
148 fallback_failure_state_(SSL_FAILURE_NONE
),
151 total_received_bytes_(0),
152 next_state_(STATE_NONE
),
153 establishing_tunnel_(false),
154 websocket_handshake_stream_base_create_helper_(NULL
) {
155 session
->ssl_config_service()->GetSSLConfig(&server_ssl_config_
);
156 session
->GetNextProtos(&server_ssl_config_
.next_protos
);
157 proxy_ssl_config_
= server_ssl_config_
;
160 HttpNetworkTransaction::~HttpNetworkTransaction() {
162 // TODO(mbelshe): The stream_ should be able to compute whether or not the
163 // stream should be kept alive. No reason to compute here
165 if (!stream_
->CanReuseConnection() || next_state_
!= STATE_NONE
) {
166 stream_
->Close(true /* not reusable */);
167 } else if (stream_
->IsResponseBodyComplete()) {
168 // If the response body is complete, we can just reuse the socket.
169 stream_
->Close(false /* reusable */);
171 // Otherwise, we try to drain the response body.
172 HttpStream
* stream
= stream_
.release();
173 stream
->Drain(session_
);
177 if (request_
&& request_
->upload_data_stream
)
178 request_
->upload_data_stream
->Reset(); // Invalidate pending callbacks.
181 int HttpNetworkTransaction::Start(const HttpRequestInfo
* request_info
,
182 const CompletionCallback
& callback
,
183 const BoundNetLog
& net_log
) {
185 request_
= request_info
;
187 if (request_
->load_flags
& LOAD_DISABLE_CERT_REVOCATION_CHECKING
) {
188 server_ssl_config_
.rev_checking_enabled
= false;
189 proxy_ssl_config_
.rev_checking_enabled
= false;
192 if (request_
->load_flags
& LOAD_PREFETCH
)
193 response_
.unused_since_prefetch
= true;
195 // Channel ID is disabled if privacy mode is enabled for this request.
196 if (request_
->privacy_mode
== PRIVACY_MODE_ENABLED
)
197 server_ssl_config_
.channel_id_enabled
= false;
199 next_state_
= STATE_NOTIFY_BEFORE_CREATE_STREAM
;
201 if (rv
== ERR_IO_PENDING
)
202 callback_
= callback
;
206 int HttpNetworkTransaction::RestartIgnoringLastError(
207 const CompletionCallback
& callback
) {
208 DCHECK(!stream_
.get());
209 DCHECK(!stream_request_
.get());
210 DCHECK_EQ(STATE_NONE
, next_state_
);
212 next_state_
= STATE_CREATE_STREAM
;
215 if (rv
== ERR_IO_PENDING
)
216 callback_
= callback
;
220 int HttpNetworkTransaction::RestartWithCertificate(
221 X509Certificate
* client_cert
, const CompletionCallback
& callback
) {
222 // In HandleCertificateRequest(), we always tear down existing stream
223 // requests to force a new connection. So we shouldn't have one here.
224 DCHECK(!stream_request_
.get());
225 DCHECK(!stream_
.get());
226 DCHECK_EQ(STATE_NONE
, next_state_
);
228 SSLConfig
* ssl_config
= response_
.cert_request_info
->is_proxy
?
229 &proxy_ssl_config_
: &server_ssl_config_
;
230 ssl_config
->send_client_cert
= true;
231 ssl_config
->client_cert
= client_cert
;
232 session_
->ssl_client_auth_cache()->Add(
233 response_
.cert_request_info
->host_and_port
, client_cert
);
234 // Reset the other member variables.
235 // Note: this is necessary only with SSL renegotiation.
236 ResetStateForRestart();
237 next_state_
= STATE_CREATE_STREAM
;
239 if (rv
== ERR_IO_PENDING
)
240 callback_
= callback
;
244 int HttpNetworkTransaction::RestartWithAuth(
245 const AuthCredentials
& credentials
, const CompletionCallback
& callback
) {
246 HttpAuth::Target target
= pending_auth_target_
;
247 if (target
== HttpAuth::AUTH_NONE
) {
249 return ERR_UNEXPECTED
;
251 pending_auth_target_
= HttpAuth::AUTH_NONE
;
253 auth_controllers_
[target
]->ResetAuth(credentials
);
255 DCHECK(callback_
.is_null());
258 if (target
== HttpAuth::AUTH_PROXY
&& establishing_tunnel_
) {
259 // In this case, we've gathered credentials for use with proxy
260 // authentication of a tunnel.
261 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
262 DCHECK(stream_request_
!= NULL
);
263 auth_controllers_
[target
] = NULL
;
264 ResetStateForRestart();
265 rv
= stream_request_
->RestartTunnelWithProxyAuth(credentials
);
267 // In this case, we've gathered credentials for the server or the proxy
268 // but it is not during the tunneling phase.
269 DCHECK(stream_request_
== NULL
);
270 PrepareForAuthRestart(target
);
274 if (rv
== ERR_IO_PENDING
)
275 callback_
= callback
;
279 void HttpNetworkTransaction::PrepareForAuthRestart(HttpAuth::Target target
) {
280 DCHECK(HaveAuth(target
));
281 DCHECK(!stream_request_
.get());
283 bool keep_alive
= false;
284 // Even if the server says the connection is keep-alive, we have to be
285 // able to find the end of each response in order to reuse the connection.
286 if (stream_
->CanReuseConnection()) {
287 // If the response body hasn't been completely read, we need to drain
289 if (!stream_
->IsResponseBodyComplete()) {
290 next_state_
= STATE_DRAIN_BODY_FOR_AUTH_RESTART
;
291 read_buf_
= new IOBuffer(kDrainBodyBufferSize
); // A bit bucket.
292 read_buf_len_
= kDrainBodyBufferSize
;
298 // We don't need to drain the response body, so we act as if we had drained
299 // the response body.
300 DidDrainBodyForAuthRestart(keep_alive
);
303 void HttpNetworkTransaction::DidDrainBodyForAuthRestart(bool keep_alive
) {
304 DCHECK(!stream_request_
.get());
307 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
308 HttpStream
* new_stream
= NULL
;
309 if (keep_alive
&& stream_
->CanReuseConnection()) {
310 // We should call connection_->set_idle_time(), but this doesn't occur
311 // often enough to be worth the trouble.
312 stream_
->SetConnectionReused();
313 new_stream
= stream_
->RenewStreamForAuth();
317 // Close the stream and mark it as not_reusable. Even in the
318 // keep_alive case, we've determined that the stream_ is not
319 // reusable if new_stream is NULL.
320 stream_
->Close(true);
321 next_state_
= STATE_CREATE_STREAM
;
323 // Renewed streams shouldn't carry over received bytes.
324 DCHECK_EQ(0, new_stream
->GetTotalReceivedBytes());
325 next_state_
= STATE_INIT_STREAM
;
327 stream_
.reset(new_stream
);
330 // Reset the other member variables.
331 ResetStateForAuthRestart();
334 bool HttpNetworkTransaction::IsReadyToRestartForAuth() {
335 return pending_auth_target_
!= HttpAuth::AUTH_NONE
&&
336 HaveAuth(pending_auth_target_
);
339 int HttpNetworkTransaction::Read(IOBuffer
* buf
, int buf_len
,
340 const CompletionCallback
& callback
) {
342 DCHECK_LT(0, buf_len
);
344 State next_state
= STATE_NONE
;
346 scoped_refptr
<HttpResponseHeaders
> headers(GetResponseHeaders());
347 if (headers_valid_
&& headers
.get() && stream_request_
.get()) {
348 // We're trying to read the body of the response but we're still trying
349 // to establish an SSL tunnel through an HTTP proxy. We can't read these
350 // bytes when establishing a tunnel because they might be controlled by
351 // an active network attacker. We don't worry about this for HTTP
352 // because an active network attacker can already control HTTP sessions.
353 // We reach this case when the user cancels a 407 proxy auth prompt. We
354 // also don't worry about this for an HTTPS Proxy, because the
355 // communication with the proxy is secure.
356 // See http://crbug.com/8473.
357 DCHECK(proxy_info_
.is_http() || proxy_info_
.is_https());
358 DCHECK_EQ(headers
->response_code(), HTTP_PROXY_AUTHENTICATION_REQUIRED
);
359 LOG(WARNING
) << "Blocked proxy response with status "
360 << headers
->response_code() << " to CONNECT request for "
361 << GetHostAndPort(request_
->url
) << ".";
362 return ERR_TUNNEL_CONNECTION_FAILED
;
365 // Are we using SPDY or HTTP?
366 next_state
= STATE_READ_BODY
;
369 read_buf_len_
= buf_len
;
371 next_state_
= next_state
;
373 if (rv
== ERR_IO_PENDING
)
374 callback_
= callback
;
378 void HttpNetworkTransaction::StopCaching() {}
380 bool HttpNetworkTransaction::GetFullRequestHeaders(
381 HttpRequestHeaders
* headers
) const {
382 // TODO(ttuttle): Make sure we've populated request_headers_.
383 *headers
= request_headers_
;
387 int64
HttpNetworkTransaction::GetTotalReceivedBytes() const {
388 int64 total_received_bytes
= total_received_bytes_
;
390 total_received_bytes
+= stream_
->GetTotalReceivedBytes();
391 return total_received_bytes
;
394 void HttpNetworkTransaction::DoneReading() {}
396 const HttpResponseInfo
* HttpNetworkTransaction::GetResponseInfo() const {
400 LoadState
HttpNetworkTransaction::GetLoadState() const {
401 // TODO(wtc): Define a new LoadState value for the
402 // STATE_INIT_CONNECTION_COMPLETE state, which delays the HTTP request.
403 switch (next_state_
) {
404 case STATE_CREATE_STREAM
:
405 return LOAD_STATE_WAITING_FOR_DELEGATE
;
406 case STATE_CREATE_STREAM_COMPLETE
:
407 return stream_request_
->GetLoadState();
408 case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
:
409 case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE
:
410 case STATE_SEND_REQUEST_COMPLETE
:
411 return LOAD_STATE_SENDING_REQUEST
;
412 case STATE_READ_HEADERS_COMPLETE
:
413 return LOAD_STATE_WAITING_FOR_RESPONSE
;
414 case STATE_READ_BODY_COMPLETE
:
415 return LOAD_STATE_READING_RESPONSE
;
417 return LOAD_STATE_IDLE
;
421 UploadProgress
HttpNetworkTransaction::GetUploadProgress() const {
423 return UploadProgress();
425 return stream_
->GetUploadProgress();
428 void HttpNetworkTransaction::SetQuicServerInfo(
429 QuicServerInfo
* quic_server_info
) {}
431 bool HttpNetworkTransaction::GetLoadTimingInfo(
432 LoadTimingInfo
* load_timing_info
) const {
433 if (!stream_
|| !stream_
->GetLoadTimingInfo(load_timing_info
))
436 load_timing_info
->proxy_resolve_start
=
437 proxy_info_
.proxy_resolve_start_time();
438 load_timing_info
->proxy_resolve_end
= proxy_info_
.proxy_resolve_end_time();
439 load_timing_info
->send_start
= send_start_time_
;
440 load_timing_info
->send_end
= send_end_time_
;
444 void HttpNetworkTransaction::SetPriority(RequestPriority priority
) {
445 priority_
= priority
;
447 stream_request_
->SetPriority(priority
);
449 stream_
->SetPriority(priority
);
452 void HttpNetworkTransaction::SetWebSocketHandshakeStreamCreateHelper(
453 WebSocketHandshakeStreamBase::CreateHelper
* create_helper
) {
454 websocket_handshake_stream_base_create_helper_
= create_helper
;
457 void HttpNetworkTransaction::SetBeforeNetworkStartCallback(
458 const BeforeNetworkStartCallback
& callback
) {
459 before_network_start_callback_
= callback
;
462 void HttpNetworkTransaction::SetBeforeProxyHeadersSentCallback(
463 const BeforeProxyHeadersSentCallback
& callback
) {
464 before_proxy_headers_sent_callback_
= callback
;
467 int HttpNetworkTransaction::ResumeNetworkStart() {
468 DCHECK_EQ(next_state_
, STATE_CREATE_STREAM
);
472 void HttpNetworkTransaction::OnStreamReady(const SSLConfig
& used_ssl_config
,
473 const ProxyInfo
& used_proxy_info
,
474 HttpStream
* stream
) {
475 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
476 DCHECK(stream_request_
.get());
479 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
480 stream_
.reset(stream
);
481 server_ssl_config_
= used_ssl_config
;
482 proxy_info_
= used_proxy_info
;
483 response_
.was_npn_negotiated
= stream_request_
->was_npn_negotiated();
484 response_
.npn_negotiated_protocol
= SSLClientSocket::NextProtoToString(
485 stream_request_
->protocol_negotiated());
486 response_
.was_fetched_via_spdy
= stream_request_
->using_spdy();
487 response_
.was_fetched_via_proxy
= !proxy_info_
.is_direct();
488 if (response_
.was_fetched_via_proxy
&& !proxy_info_
.is_empty())
489 response_
.proxy_server
= proxy_info_
.proxy_server().host_port_pair();
493 void HttpNetworkTransaction::OnWebSocketHandshakeStreamReady(
494 const SSLConfig
& used_ssl_config
,
495 const ProxyInfo
& used_proxy_info
,
496 WebSocketHandshakeStreamBase
* stream
) {
497 OnStreamReady(used_ssl_config
, used_proxy_info
, stream
);
500 void HttpNetworkTransaction::OnStreamFailed(int result
,
501 const SSLConfig
& used_ssl_config
,
502 SSLFailureState ssl_failure_state
) {
503 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
504 DCHECK_NE(OK
, result
);
505 DCHECK(stream_request_
.get());
506 DCHECK(!stream_
.get());
507 server_ssl_config_
= used_ssl_config
;
508 server_ssl_failure_state_
= ssl_failure_state
;
510 OnIOComplete(result
);
513 void HttpNetworkTransaction::OnCertificateError(
515 const SSLConfig
& used_ssl_config
,
516 const SSLInfo
& ssl_info
) {
517 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
518 DCHECK_NE(OK
, result
);
519 DCHECK(stream_request_
.get());
520 DCHECK(!stream_
.get());
522 response_
.ssl_info
= ssl_info
;
523 server_ssl_config_
= used_ssl_config
;
525 // TODO(mbelshe): For now, we're going to pass the error through, and that
526 // will close the stream_request in all cases. This means that we're always
527 // going to restart an entire STATE_CREATE_STREAM, even if the connection is
528 // good and the user chooses to ignore the error. This is not ideal, but not
529 // the end of the world either.
531 OnIOComplete(result
);
534 void HttpNetworkTransaction::OnNeedsProxyAuth(
535 const HttpResponseInfo
& proxy_response
,
536 const SSLConfig
& used_ssl_config
,
537 const ProxyInfo
& used_proxy_info
,
538 HttpAuthController
* auth_controller
) {
539 DCHECK(stream_request_
.get());
540 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
542 establishing_tunnel_
= true;
543 response_
.headers
= proxy_response
.headers
;
544 response_
.auth_challenge
= proxy_response
.auth_challenge
;
545 headers_valid_
= true;
546 server_ssl_config_
= used_ssl_config
;
547 proxy_info_
= used_proxy_info
;
549 auth_controllers_
[HttpAuth::AUTH_PROXY
] = auth_controller
;
550 pending_auth_target_
= HttpAuth::AUTH_PROXY
;
555 void HttpNetworkTransaction::OnNeedsClientAuth(
556 const SSLConfig
& used_ssl_config
,
557 SSLCertRequestInfo
* cert_info
) {
558 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
560 server_ssl_config_
= used_ssl_config
;
561 response_
.cert_request_info
= cert_info
;
562 OnIOComplete(ERR_SSL_CLIENT_AUTH_CERT_NEEDED
);
565 void HttpNetworkTransaction::OnHttpsProxyTunnelResponse(
566 const HttpResponseInfo
& response_info
,
567 const SSLConfig
& used_ssl_config
,
568 const ProxyInfo
& used_proxy_info
,
569 HttpStream
* stream
) {
570 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
572 CopyConnectionAttemptsFromStreamRequest();
574 headers_valid_
= true;
575 response_
= response_info
;
576 server_ssl_config_
= used_ssl_config
;
577 proxy_info_
= used_proxy_info
;
579 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
580 stream_
.reset(stream
);
581 stream_request_
.reset(); // we're done with the stream request
582 OnIOComplete(ERR_HTTPS_PROXY_TUNNEL_RESPONSE
);
585 void HttpNetworkTransaction::GetConnectionAttempts(
586 ConnectionAttempts
* out
) const {
587 *out
= connection_attempts_
;
590 bool HttpNetworkTransaction::IsSecureRequest() const {
591 return request_
->url
.SchemeIsCryptographic();
594 bool HttpNetworkTransaction::UsingHttpProxyWithoutTunnel() const {
595 return (proxy_info_
.is_http() || proxy_info_
.is_https() ||
596 proxy_info_
.is_quic()) &&
597 !(request_
->url
.SchemeIs("https") || request_
->url
.SchemeIsWSOrWSS());
600 void HttpNetworkTransaction::DoCallback(int rv
) {
601 DCHECK_NE(rv
, ERR_IO_PENDING
);
602 DCHECK(!callback_
.is_null());
604 // Since Run may result in Read being called, clear user_callback_ up front.
605 CompletionCallback c
= callback_
;
610 void HttpNetworkTransaction::OnIOComplete(int result
) {
611 int rv
= DoLoop(result
);
612 if (rv
!= ERR_IO_PENDING
)
616 int HttpNetworkTransaction::DoLoop(int result
) {
617 DCHECK(next_state_
!= STATE_NONE
);
621 State state
= next_state_
;
622 next_state_
= STATE_NONE
;
624 case STATE_NOTIFY_BEFORE_CREATE_STREAM
:
626 rv
= DoNotifyBeforeCreateStream();
628 case STATE_CREATE_STREAM
:
630 rv
= DoCreateStream();
632 case STATE_CREATE_STREAM_COMPLETE
:
633 rv
= DoCreateStreamComplete(rv
);
635 case STATE_INIT_STREAM
:
639 case STATE_INIT_STREAM_COMPLETE
:
640 rv
= DoInitStreamComplete(rv
);
642 case STATE_GENERATE_PROXY_AUTH_TOKEN
:
644 rv
= DoGenerateProxyAuthToken();
646 case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
:
647 rv
= DoGenerateProxyAuthTokenComplete(rv
);
649 case STATE_GENERATE_SERVER_AUTH_TOKEN
:
651 rv
= DoGenerateServerAuthToken();
653 case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE
:
654 rv
= DoGenerateServerAuthTokenComplete(rv
);
656 case STATE_INIT_REQUEST_BODY
:
658 rv
= DoInitRequestBody();
660 case STATE_INIT_REQUEST_BODY_COMPLETE
:
661 rv
= DoInitRequestBodyComplete(rv
);
663 case STATE_BUILD_REQUEST
:
665 net_log_
.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST
);
666 rv
= DoBuildRequest();
668 case STATE_BUILD_REQUEST_COMPLETE
:
669 rv
= DoBuildRequestComplete(rv
);
671 case STATE_SEND_REQUEST
:
673 rv
= DoSendRequest();
675 case STATE_SEND_REQUEST_COMPLETE
:
676 rv
= DoSendRequestComplete(rv
);
677 net_log_
.EndEventWithNetErrorCode(
678 NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST
, rv
);
680 case STATE_READ_HEADERS
:
682 net_log_
.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS
);
683 rv
= DoReadHeaders();
685 case STATE_READ_HEADERS_COMPLETE
:
686 rv
= DoReadHeadersComplete(rv
);
687 net_log_
.EndEventWithNetErrorCode(
688 NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS
, rv
);
690 case STATE_READ_BODY
:
692 net_log_
.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_BODY
);
695 case STATE_READ_BODY_COMPLETE
:
696 rv
= DoReadBodyComplete(rv
);
697 net_log_
.EndEventWithNetErrorCode(
698 NetLog::TYPE_HTTP_TRANSACTION_READ_BODY
, rv
);
700 case STATE_DRAIN_BODY_FOR_AUTH_RESTART
:
703 NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART
);
704 rv
= DoDrainBodyForAuthRestart();
706 case STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE
:
707 rv
= DoDrainBodyForAuthRestartComplete(rv
);
708 net_log_
.EndEventWithNetErrorCode(
709 NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART
, rv
);
712 NOTREACHED() << "bad state";
716 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
721 int HttpNetworkTransaction::DoNotifyBeforeCreateStream() {
722 next_state_
= STATE_CREATE_STREAM
;
724 if (!before_network_start_callback_
.is_null())
725 before_network_start_callback_
.Run(&defer
);
728 return ERR_IO_PENDING
;
731 int HttpNetworkTransaction::DoCreateStream() {
732 // TODO(mmenke): Remove ScopedTracker below once crbug.com/424359 is fixed.
733 tracked_objects::ScopedTracker
tracking_profile(
734 FROM_HERE_WITH_EXPLICIT_FUNCTION(
735 "424359 HttpNetworkTransaction::DoCreateStream"));
737 response_
.network_accessed
= true;
739 next_state_
= STATE_CREATE_STREAM_COMPLETE
;
740 if (ForWebSocketHandshake()) {
741 stream_request_
.reset(
742 session_
->http_stream_factory_for_websocket()
743 ->RequestWebSocketHandshakeStream(
749 websocket_handshake_stream_base_create_helper_
,
752 stream_request_
.reset(
753 session_
->http_stream_factory()->RequestStream(
761 DCHECK(stream_request_
.get());
762 return ERR_IO_PENDING
;
765 int HttpNetworkTransaction::DoCreateStreamComplete(int result
) {
766 // If |result| is ERR_HTTPS_PROXY_TUNNEL_RESPONSE, then
767 // DoCreateStreamComplete is being called from OnHttpsProxyTunnelResponse,
768 // which resets the stream request first. Therefore, we have to grab the
769 // connection attempts in *that* function instead of here in that case.
770 if (result
!= ERR_HTTPS_PROXY_TUNNEL_RESPONSE
)
771 CopyConnectionAttemptsFromStreamRequest();
773 if (request_
->url
.SchemeIsCryptographic())
774 RecordSSLFallbackMetrics(result
);
777 next_state_
= STATE_INIT_STREAM
;
778 DCHECK(stream_
.get());
779 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
780 result
= HandleCertificateRequest(result
);
781 } else if (result
== ERR_HTTPS_PROXY_TUNNEL_RESPONSE
) {
782 // Return OK and let the caller read the proxy's error page
783 next_state_
= STATE_NONE
;
785 } else if (result
== ERR_HTTP_1_1_REQUIRED
||
786 result
== ERR_PROXY_HTTP_1_1_REQUIRED
) {
787 return HandleHttp11Required(result
);
790 // Handle possible handshake errors that may have occurred if the stream
791 // used SSL for one or more of the layers.
792 result
= HandleSSLHandshakeError(result
);
794 // At this point we are done with the stream_request_.
795 stream_request_
.reset();
799 int HttpNetworkTransaction::DoInitStream() {
800 DCHECK(stream_
.get());
801 next_state_
= STATE_INIT_STREAM_COMPLETE
;
802 return stream_
->InitializeStream(request_
, priority_
, net_log_
, io_callback_
);
805 int HttpNetworkTransaction::DoInitStreamComplete(int result
) {
807 next_state_
= STATE_GENERATE_PROXY_AUTH_TOKEN
;
810 result
= HandleIOError(result
);
812 // The stream initialization failed, so this stream will never be useful.
814 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
821 int HttpNetworkTransaction::DoGenerateProxyAuthToken() {
822 next_state_
= STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
;
823 if (!ShouldApplyProxyAuth())
825 HttpAuth::Target target
= HttpAuth::AUTH_PROXY
;
826 if (!auth_controllers_
[target
].get())
827 auth_controllers_
[target
] =
828 new HttpAuthController(target
,
830 session_
->http_auth_cache(),
831 session_
->http_auth_handler_factory());
832 return auth_controllers_
[target
]->MaybeGenerateAuthToken(request_
,
837 int HttpNetworkTransaction::DoGenerateProxyAuthTokenComplete(int rv
) {
838 DCHECK_NE(ERR_IO_PENDING
, rv
);
840 next_state_
= STATE_GENERATE_SERVER_AUTH_TOKEN
;
844 int HttpNetworkTransaction::DoGenerateServerAuthToken() {
845 next_state_
= STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE
;
846 HttpAuth::Target target
= HttpAuth::AUTH_SERVER
;
847 if (!auth_controllers_
[target
].get()) {
848 auth_controllers_
[target
] =
849 new HttpAuthController(target
,
851 session_
->http_auth_cache(),
852 session_
->http_auth_handler_factory());
853 if (request_
->load_flags
& LOAD_DO_NOT_USE_EMBEDDED_IDENTITY
)
854 auth_controllers_
[target
]->DisableEmbeddedIdentity();
856 if (!ShouldApplyServerAuth())
858 return auth_controllers_
[target
]->MaybeGenerateAuthToken(request_
,
863 int HttpNetworkTransaction::DoGenerateServerAuthTokenComplete(int rv
) {
864 DCHECK_NE(ERR_IO_PENDING
, rv
);
866 next_state_
= STATE_INIT_REQUEST_BODY
;
870 void HttpNetworkTransaction::BuildRequestHeaders(
871 bool using_http_proxy_without_tunnel
) {
872 request_headers_
.SetHeader(HttpRequestHeaders::kHost
,
873 GetHostAndOptionalPort(request_
->url
));
875 // For compat with HTTP/1.0 servers and proxies:
876 if (using_http_proxy_without_tunnel
) {
877 request_headers_
.SetHeader(HttpRequestHeaders::kProxyConnection
,
880 request_headers_
.SetHeader(HttpRequestHeaders::kConnection
, "keep-alive");
883 // Add a content length header?
884 if (request_
->upload_data_stream
) {
885 if (request_
->upload_data_stream
->is_chunked()) {
886 request_headers_
.SetHeader(
887 HttpRequestHeaders::kTransferEncoding
, "chunked");
889 request_headers_
.SetHeader(
890 HttpRequestHeaders::kContentLength
,
891 base::Uint64ToString(request_
->upload_data_stream
->size()));
893 } else if (request_
->method
== "POST" || request_
->method
== "PUT") {
894 // An empty POST/PUT request still needs a content length. As for HEAD,
895 // IE and Safari also add a content length header. Presumably it is to
896 // support sending a HEAD request to an URL that only expects to be sent a
897 // POST or some other method that normally would have a message body.
898 // Firefox (40.0) does not send the header, and RFC 7230 & 7231
899 // specify that it should not be sent due to undefined behavior.
900 request_headers_
.SetHeader(HttpRequestHeaders::kContentLength
, "0");
903 // Honor load flags that impact proxy caches.
904 if (request_
->load_flags
& LOAD_BYPASS_CACHE
) {
905 request_headers_
.SetHeader(HttpRequestHeaders::kPragma
, "no-cache");
906 request_headers_
.SetHeader(HttpRequestHeaders::kCacheControl
, "no-cache");
907 } else if (request_
->load_flags
& LOAD_VALIDATE_CACHE
) {
908 request_headers_
.SetHeader(HttpRequestHeaders::kCacheControl
, "max-age=0");
911 if (ShouldApplyProxyAuth() && HaveAuth(HttpAuth::AUTH_PROXY
))
912 auth_controllers_
[HttpAuth::AUTH_PROXY
]->AddAuthorizationHeader(
914 if (ShouldApplyServerAuth() && HaveAuth(HttpAuth::AUTH_SERVER
))
915 auth_controllers_
[HttpAuth::AUTH_SERVER
]->AddAuthorizationHeader(
918 request_headers_
.MergeFrom(request_
->extra_headers
);
920 if (using_http_proxy_without_tunnel
&&
921 !before_proxy_headers_sent_callback_
.is_null())
922 before_proxy_headers_sent_callback_
.Run(proxy_info_
, &request_headers_
);
924 response_
.did_use_http_auth
=
925 request_headers_
.HasHeader(HttpRequestHeaders::kAuthorization
) ||
926 request_headers_
.HasHeader(HttpRequestHeaders::kProxyAuthorization
);
929 int HttpNetworkTransaction::DoInitRequestBody() {
930 next_state_
= STATE_INIT_REQUEST_BODY_COMPLETE
;
932 if (request_
->upload_data_stream
)
933 rv
= request_
->upload_data_stream
->Init(io_callback_
);
937 int HttpNetworkTransaction::DoInitRequestBodyComplete(int result
) {
939 next_state_
= STATE_BUILD_REQUEST
;
943 int HttpNetworkTransaction::DoBuildRequest() {
944 next_state_
= STATE_BUILD_REQUEST_COMPLETE
;
945 headers_valid_
= false;
947 // This is constructed lazily (instead of within our Start method), so that
948 // we have proxy info available.
949 if (request_headers_
.IsEmpty()) {
950 bool using_http_proxy_without_tunnel
= UsingHttpProxyWithoutTunnel();
951 BuildRequestHeaders(using_http_proxy_without_tunnel
);
957 int HttpNetworkTransaction::DoBuildRequestComplete(int result
) {
959 next_state_
= STATE_SEND_REQUEST
;
963 int HttpNetworkTransaction::DoSendRequest() {
964 // TODO(mmenke): Remove ScopedTracker below once crbug.com/424359 is fixed.
965 tracked_objects::ScopedTracker
tracking_profile(
966 FROM_HERE_WITH_EXPLICIT_FUNCTION(
967 "424359 HttpNetworkTransaction::DoSendRequest"));
969 send_start_time_
= base::TimeTicks::Now();
970 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
972 return stream_
->SendRequest(request_headers_
, &response_
, io_callback_
);
975 int HttpNetworkTransaction::DoSendRequestComplete(int result
) {
976 send_end_time_
= base::TimeTicks::Now();
978 return HandleIOError(result
);
979 next_state_
= STATE_READ_HEADERS
;
983 int HttpNetworkTransaction::DoReadHeaders() {
984 next_state_
= STATE_READ_HEADERS_COMPLETE
;
985 return stream_
->ReadResponseHeaders(io_callback_
);
988 int HttpNetworkTransaction::DoReadHeadersComplete(int result
) {
989 // We can get a certificate error or ERR_SSL_CLIENT_AUTH_CERT_NEEDED here
990 // due to SSL renegotiation.
991 if (IsCertificateError(result
)) {
992 // We don't handle a certificate error during SSL renegotiation, so we
993 // have to return an error that's not in the certificate error range
995 LOG(ERROR
) << "Got a server certificate with error " << result
996 << " during SSL renegotiation";
997 result
= ERR_CERT_ERROR_IN_SSL_RENEGOTIATION
;
998 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
999 // TODO(wtc): Need a test case for this code path!
1000 DCHECK(stream_
.get());
1001 DCHECK(IsSecureRequest());
1002 response_
.cert_request_info
= new SSLCertRequestInfo
;
1003 stream_
->GetSSLCertRequestInfo(response_
.cert_request_info
.get());
1004 result
= HandleCertificateRequest(result
);
1009 if (result
== ERR_HTTP_1_1_REQUIRED
||
1010 result
== ERR_PROXY_HTTP_1_1_REQUIRED
) {
1011 return HandleHttp11Required(result
);
1014 // ERR_CONNECTION_CLOSED is treated differently at this point; if partial
1015 // response headers were received, we do the best we can to make sense of it
1016 // and send it back up the stack.
1018 // TODO(davidben): Consider moving this to HttpBasicStream, It's a little
1019 // bizarre for SPDY. Assuming this logic is useful at all.
1020 // TODO(davidben): Bubble the error code up so we do not cache?
1021 if (result
== ERR_CONNECTION_CLOSED
&& response_
.headers
.get())
1025 return HandleIOError(result
);
1027 DCHECK(response_
.headers
.get());
1029 // On a 408 response from the server ("Request Timeout") on a stale socket,
1030 // retry the request.
1031 // Headers can be NULL because of http://crbug.com/384554.
1032 if (response_
.headers
.get() && response_
.headers
->response_code() == 408 &&
1033 stream_
->IsConnectionReused()) {
1034 net_log_
.AddEventWithNetErrorCode(
1035 NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR
,
1036 response_
.headers
->response_code());
1037 // This will close the socket - it would be weird to try and reuse it, even
1038 // if the server doesn't actually close it.
1039 ResetConnectionAndRequestForResend();
1043 // Like Net.HttpResponseCode, but only for MAIN_FRAME loads.
1044 if (request_
->load_flags
& LOAD_MAIN_FRAME
) {
1045 const int response_code
= response_
.headers
->response_code();
1046 UMA_HISTOGRAM_ENUMERATION(
1047 "Net.HttpResponseCode_Nxx_MainFrame", response_code
/100, 10);
1051 NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS
,
1052 base::Bind(&HttpResponseHeaders::NetLogCallback
, response_
.headers
));
1054 if (response_
.headers
->GetParsedHttpVersion() < HttpVersion(1, 0)) {
1055 // HTTP/0.9 doesn't support the PUT method, so lack of response headers
1056 // indicates a buggy server. See:
1057 // https://bugzilla.mozilla.org/show_bug.cgi?id=193921
1058 if (request_
->method
== "PUT")
1059 return ERR_METHOD_NOT_SUPPORTED
;
1062 // Check for an intermediate 100 Continue response. An origin server is
1063 // allowed to send this response even if we didn't ask for it, so we just
1064 // need to skip over it.
1065 // We treat any other 1xx in this same way (although in practice getting
1066 // a 1xx that isn't a 100 is rare).
1067 // Unless this is a WebSocket request, in which case we pass it on up.
1068 if (response_
.headers
->response_code() / 100 == 1 &&
1069 !ForWebSocketHandshake()) {
1070 response_
.headers
= new HttpResponseHeaders(std::string());
1071 next_state_
= STATE_READ_HEADERS
;
1075 ProcessAlternativeServices(session_
, *response_
.headers
.get(),
1076 HostPortPair::FromURL(request_
->url
));
1078 int rv
= HandleAuthChallenge();
1082 if (IsSecureRequest())
1083 stream_
->GetSSLInfo(&response_
.ssl_info
);
1085 headers_valid_
= true;
1089 int HttpNetworkTransaction::DoReadBody() {
1090 DCHECK(read_buf_
.get());
1091 DCHECK_GT(read_buf_len_
, 0);
1092 DCHECK(stream_
!= NULL
);
1094 next_state_
= STATE_READ_BODY_COMPLETE
;
1095 return stream_
->ReadResponseBody(
1096 read_buf_
.get(), read_buf_len_
, io_callback_
);
1099 int HttpNetworkTransaction::DoReadBodyComplete(int result
) {
1100 // We are done with the Read call.
1103 DCHECK_NE(ERR_IO_PENDING
, result
);
1107 // Clean up connection if we are done.
1109 // Note: Just because IsResponseBodyComplete is true, we're not
1110 // necessarily "done". We're only "done" when it is the last
1111 // read on this HttpNetworkTransaction, which will be signified
1112 // by a zero-length read.
1113 // TODO(mbelshe): The keep-alive property is really a property of
1114 // the stream. No need to compute it here just to pass back
1115 // to the stream's Close function.
1117 stream_
->IsResponseBodyComplete() && stream_
->CanReuseConnection();
1119 stream_
->Close(!keep_alive
);
1120 // Note: we don't reset the stream here. We've closed it, but we still
1121 // need it around so that callers can call methods such as
1122 // GetUploadProgress() and have them be meaningful.
1123 // TODO(mbelshe): This means we closed the stream here, and we close it
1124 // again in ~HttpNetworkTransaction. Clean that up.
1126 // The next Read call will return 0 (EOF).
1129 // Clear these to avoid leaving around old state.
1136 int HttpNetworkTransaction::DoDrainBodyForAuthRestart() {
1137 // This method differs from DoReadBody only in the next_state_. So we just
1138 // call DoReadBody and override the next_state_. Perhaps there is a more
1139 // elegant way for these two methods to share code.
1140 int rv
= DoReadBody();
1141 DCHECK(next_state_
== STATE_READ_BODY_COMPLETE
);
1142 next_state_
= STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE
;
1146 // TODO(wtc): This method and the DoReadBodyComplete method are almost
1147 // the same. Figure out a good way for these two methods to share code.
1148 int HttpNetworkTransaction::DoDrainBodyForAuthRestartComplete(int result
) {
1149 // keep_alive defaults to true because the very reason we're draining the
1150 // response body is to reuse the connection for auth restart.
1151 bool done
= false, keep_alive
= true;
1153 // Error or closed connection while reading the socket.
1156 } else if (stream_
->IsResponseBodyComplete()) {
1161 DidDrainBodyForAuthRestart(keep_alive
);
1164 next_state_
= STATE_DRAIN_BODY_FOR_AUTH_RESTART
;
1170 int HttpNetworkTransaction::HandleCertificateRequest(int error
) {
1171 // There are two paths through which the server can request a certificate
1172 // from us. The first is during the initial handshake, the second is
1173 // during SSL renegotiation.
1175 // In both cases, we want to close the connection before proceeding.
1176 // We do this for two reasons:
1177 // First, we don't want to keep the connection to the server hung for a
1178 // long time while the user selects a certificate.
1179 // Second, even if we did keep the connection open, NSS has a bug where
1180 // restarting the handshake for ClientAuth is currently broken.
1181 DCHECK_EQ(error
, ERR_SSL_CLIENT_AUTH_CERT_NEEDED
);
1183 if (stream_
.get()) {
1184 // Since we already have a stream, we're being called as part of SSL
1186 DCHECK(!stream_request_
.get());
1187 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
1188 stream_
->Close(true);
1192 // The server is asking for a client certificate during the initial
1194 stream_request_
.reset();
1196 // If the user selected one of the certificates in client_certs or declined
1197 // to provide one for this server before, use the past decision
1199 scoped_refptr
<X509Certificate
> client_cert
;
1200 bool found_cached_cert
= session_
->ssl_client_auth_cache()->Lookup(
1201 response_
.cert_request_info
->host_and_port
, &client_cert
);
1202 if (!found_cached_cert
)
1205 // Check that the certificate selected is still a certificate the server
1206 // is likely to accept, based on the criteria supplied in the
1207 // CertificateRequest message.
1208 if (client_cert
.get()) {
1209 const std::vector
<std::string
>& cert_authorities
=
1210 response_
.cert_request_info
->cert_authorities
;
1212 bool cert_still_valid
= cert_authorities
.empty() ||
1213 client_cert
->IsIssuedByEncoded(cert_authorities
);
1214 if (!cert_still_valid
)
1218 // TODO(davidben): Add a unit test which covers this path; we need to be
1219 // able to send a legitimate certificate and also bypass/clear the
1220 // SSL session cache.
1221 SSLConfig
* ssl_config
= response_
.cert_request_info
->is_proxy
?
1222 &proxy_ssl_config_
: &server_ssl_config_
;
1223 ssl_config
->send_client_cert
= true;
1224 ssl_config
->client_cert
= client_cert
;
1225 next_state_
= STATE_CREATE_STREAM
;
1226 // Reset the other member variables.
1227 // Note: this is necessary only with SSL renegotiation.
1228 ResetStateForRestart();
1232 int HttpNetworkTransaction::HandleHttp11Required(int error
) {
1233 DCHECK(error
== ERR_HTTP_1_1_REQUIRED
||
1234 error
== ERR_PROXY_HTTP_1_1_REQUIRED
);
1236 if (error
== ERR_HTTP_1_1_REQUIRED
) {
1237 HttpServerProperties::ForceHTTP11(&server_ssl_config_
);
1239 HttpServerProperties::ForceHTTP11(&proxy_ssl_config_
);
1241 ResetConnectionAndRequestForResend();
1245 void HttpNetworkTransaction::HandleClientAuthError(int error
) {
1246 if (server_ssl_config_
.send_client_cert
&&
1247 (error
== ERR_SSL_PROTOCOL_ERROR
|| IsClientCertificateError(error
))) {
1248 session_
->ssl_client_auth_cache()->Remove(
1249 HostPortPair::FromURL(request_
->url
));
1253 // TODO(rch): This does not correctly handle errors when an SSL proxy is
1254 // being used, as all of the errors are handled as if they were generated
1255 // by the endpoint host, request_->url, rather than considering if they were
1256 // generated by the SSL proxy. http://crbug.com/69329
1257 int HttpNetworkTransaction::HandleSSLHandshakeError(int error
) {
1259 HandleClientAuthError(error
);
1261 // Accept deprecated cipher suites, but only on a fallback. This makes UMA
1262 // reflect servers require a deprecated cipher rather than merely prefer
1263 // it. This, however, has no security benefit until the ciphers are actually
1265 if (!server_ssl_config_
.enable_deprecated_cipher_suites
&&
1266 (error
== ERR_SSL_VERSION_OR_CIPHER_MISMATCH
||
1267 error
== ERR_CONNECTION_CLOSED
|| error
== ERR_CONNECTION_RESET
)) {
1269 NetLog::TYPE_SSL_CIPHER_FALLBACK
,
1270 base::Bind(&NetLogSSLCipherFallbackCallback
, &request_
->url
, error
));
1271 server_ssl_config_
.enable_deprecated_cipher_suites
= true;
1272 ResetConnectionAndRequestForResend();
1276 bool should_fallback
= false;
1277 uint16 version_max
= server_ssl_config_
.version_max
;
1280 case ERR_CONNECTION_CLOSED
:
1281 case ERR_SSL_PROTOCOL_ERROR
:
1282 case ERR_SSL_VERSION_OR_CIPHER_MISMATCH
:
1283 if (version_max
>= SSL_PROTOCOL_VERSION_TLS1
&&
1284 version_max
> server_ssl_config_
.version_min
) {
1285 // This could be a TLS-intolerant server or a server that chose a
1286 // cipher suite defined only for higher protocol versions (such as
1287 // an SSL 3.0 server that chose a TLS-only cipher suite). Fall
1288 // back to the next lower version and retry.
1289 // NOTE: if the SSLClientSocket class doesn't support TLS 1.1,
1290 // specifying TLS 1.1 in version_max will result in a TLS 1.0
1291 // handshake, so falling back from TLS 1.1 to TLS 1.0 will simply
1292 // repeat the TLS 1.0 handshake. To avoid this problem, the default
1293 // version_max should match the maximum protocol version supported
1294 // by the SSLClientSocket class.
1297 // Fallback to the lower SSL version.
1298 // While SSL 3.0 fallback should be eliminated because of security
1299 // reasons, there is a high risk of breaking the servers if this is
1301 should_fallback
= true;
1304 case ERR_CONNECTION_RESET
:
1305 if (version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
&&
1306 version_max
> server_ssl_config_
.version_min
) {
1307 // Some network devices that inspect application-layer packets seem to
1308 // inject TCP reset packets to break the connections when they see TLS
1309 // 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
1311 // Only allow ERR_CONNECTION_RESET to trigger a fallback from TLS 1.1 or
1312 // 1.2. We don't lose much in this fallback because the explicit IV for
1313 // CBC mode in TLS 1.1 is approximated by record splitting in TLS
1314 // 1.0. The fallback will be more painful for TLS 1.2 when we have GCM
1317 // ERR_CONNECTION_RESET is a common network error, so we don't want it
1318 // to trigger a version fallback in general, especially the TLS 1.0 ->
1319 // SSL 3.0 fallback, which would drop TLS extensions.
1321 should_fallback
= true;
1324 case ERR_SSL_BAD_RECORD_MAC_ALERT
:
1325 if (version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
&&
1326 version_max
> server_ssl_config_
.version_min
) {
1327 // Some broken SSL devices negotiate TLS 1.0 when sent a TLS 1.1 or
1328 // 1.2 ClientHello, but then return a bad_record_mac alert. See
1329 // crbug.com/260358. In order to make the fallback as minimal as
1330 // possible, this fallback is only triggered for >= TLS 1.1.
1332 should_fallback
= true;
1335 case ERR_SSL_INAPPROPRIATE_FALLBACK
:
1336 // The server told us that we should not have fallen back. A buggy server
1337 // could trigger ERR_SSL_INAPPROPRIATE_FALLBACK with the initial
1338 // connection. |fallback_error_code_| is initialised to
1339 // ERR_SSL_INAPPROPRIATE_FALLBACK to catch this case.
1340 error
= fallback_error_code_
;
1344 if (should_fallback
) {
1346 NetLog::TYPE_SSL_VERSION_FALLBACK
,
1347 base::Bind(&NetLogSSLVersionFallbackCallback
, &request_
->url
, error
,
1348 server_ssl_failure_state_
, server_ssl_config_
.version_max
,
1350 fallback_error_code_
= error
;
1351 fallback_failure_state_
= server_ssl_failure_state_
;
1352 server_ssl_config_
.version_max
= version_max
;
1353 server_ssl_config_
.version_fallback
= true;
1354 ResetConnectionAndRequestForResend();
1361 // This method determines whether it is safe to resend the request after an
1362 // IO error. It can only be called in response to request header or body
1363 // write errors or response header read errors. It should not be used in
1364 // other cases, such as a Connect error.
1365 int HttpNetworkTransaction::HandleIOError(int error
) {
1366 // Because the peer may request renegotiation with client authentication at
1367 // any time, check and handle client authentication errors.
1368 HandleClientAuthError(error
);
1371 // If we try to reuse a connection that the server is in the process of
1372 // closing, we may end up successfully writing out our request (or a
1373 // portion of our request) only to find a connection error when we try to
1374 // read from (or finish writing to) the socket.
1375 case ERR_CONNECTION_RESET
:
1376 case ERR_CONNECTION_CLOSED
:
1377 case ERR_CONNECTION_ABORTED
:
1378 // There can be a race between the socket pool checking checking whether a
1379 // socket is still connected, receiving the FIN, and sending/reading data
1380 // on a reused socket. If we receive the FIN between the connectedness
1381 // check and writing/reading from the socket, we may first learn the socket
1382 // is disconnected when we get a ERR_SOCKET_NOT_CONNECTED. This will most
1383 // likely happen when trying to retrieve its IP address.
1384 // See http://crbug.com/105824 for more details.
1385 case ERR_SOCKET_NOT_CONNECTED
:
1386 // If a socket is closed on its initial request, HttpStreamParser returns
1387 // ERR_EMPTY_RESPONSE. This may still be close/reuse race if the socket was
1388 // preconnected but failed to be used before the server timed it out.
1389 case ERR_EMPTY_RESPONSE
:
1390 if (ShouldResendRequest()) {
1391 net_log_
.AddEventWithNetErrorCode(
1392 NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR
, error
);
1393 ResetConnectionAndRequestForResend();
1397 case ERR_SPDY_PING_FAILED
:
1398 case ERR_SPDY_SERVER_REFUSED_STREAM
:
1399 case ERR_QUIC_HANDSHAKE_FAILED
:
1400 net_log_
.AddEventWithNetErrorCode(
1401 NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR
, error
);
1402 ResetConnectionAndRequestForResend();
1409 void HttpNetworkTransaction::ResetStateForRestart() {
1410 ResetStateForAuthRestart();
1412 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
1416 void HttpNetworkTransaction::ResetStateForAuthRestart() {
1417 send_start_time_
= base::TimeTicks();
1418 send_end_time_
= base::TimeTicks();
1420 pending_auth_target_
= HttpAuth::AUTH_NONE
;
1423 headers_valid_
= false;
1424 request_headers_
.Clear();
1425 response_
= HttpResponseInfo();
1426 establishing_tunnel_
= false;
1429 void HttpNetworkTransaction::RecordSSLFallbackMetrics(int result
) {
1430 if (result
!= OK
&& result
!= ERR_SSL_INAPPROPRIATE_FALLBACK
)
1433 const std::string
& host
= request_
->url
.host();
1434 bool is_google
= base::EndsWith(host
, "google.com",
1435 base::CompareCase::SENSITIVE
) &&
1436 (host
.size() == 10 || host
[host
.size() - 11] == '.');
1438 // Some fraction of successful connections use the fallback, but only due to
1439 // a spurious network failure. To estimate this fraction, compare handshakes
1440 // to Google servers which succeed against those that fail with an
1441 // inappropriate_fallback alert. Google servers are known to implement
1442 // FALLBACK_SCSV, so a spurious network failure while connecting would
1443 // trigger the fallback, successfully connect, but fail with this alert.
1444 UMA_HISTOGRAM_BOOLEAN("Net.GoogleConnectionInappropriateFallback",
1445 result
== ERR_SSL_INAPPROPRIATE_FALLBACK
);
1451 // Note: these values are used in histograms, so new values must be appended.
1452 enum FallbackVersion
{
1453 FALLBACK_NONE
= 0, // SSL version fallback did not occur.
1454 // Obsolete: FALLBACK_SSL3 = 1,
1455 FALLBACK_TLS1
= 2, // Fell back to TLS 1.0.
1456 FALLBACK_TLS1_1
= 3, // Fell back to TLS 1.1.
1460 FallbackVersion fallback
= FALLBACK_NONE
;
1461 if (server_ssl_config_
.version_fallback
) {
1462 switch (server_ssl_config_
.version_max
) {
1463 case SSL_PROTOCOL_VERSION_TLS1
:
1464 fallback
= FALLBACK_TLS1
;
1466 case SSL_PROTOCOL_VERSION_TLS1_1
:
1467 fallback
= FALLBACK_TLS1_1
;
1473 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback2", fallback
,
1476 // Google servers are known to implement TLS 1.2 and FALLBACK_SCSV, so it
1477 // should be impossible to successfully connect to them with the fallback.
1478 // This helps estimate intolerant locally-configured SSL MITMs.
1480 UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback2",
1481 fallback
, FALLBACK_MAX
);
1484 UMA_HISTOGRAM_BOOLEAN("Net.ConnectionUsedSSLDeprecatedCipherFallback2",
1485 server_ssl_config_
.enable_deprecated_cipher_suites
);
1487 if (server_ssl_config_
.version_fallback
) {
1488 // Record the error code which triggered the fallback and the state the
1489 // handshake was in.
1490 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.SSLFallbackErrorCode",
1491 -fallback_error_code_
);
1492 UMA_HISTOGRAM_ENUMERATION("Net.SSLFallbackFailureState",
1493 fallback_failure_state_
, SSL_FAILURE_MAX
);
1497 HttpResponseHeaders
* HttpNetworkTransaction::GetResponseHeaders() const {
1498 return response_
.headers
.get();
1501 bool HttpNetworkTransaction::ShouldResendRequest() const {
1502 bool connection_is_proven
= stream_
->IsConnectionReused();
1503 bool has_received_headers
= GetResponseHeaders() != NULL
;
1505 // NOTE: we resend a request only if we reused a keep-alive connection.
1506 // This automatically prevents an infinite resend loop because we'll run
1507 // out of the cached keep-alive connections eventually.
1508 if (connection_is_proven
&& !has_received_headers
)
1513 void HttpNetworkTransaction::ResetConnectionAndRequestForResend() {
1514 if (stream_
.get()) {
1515 stream_
->Close(true);
1519 // We need to clear request_headers_ because it contains the real request
1520 // headers, but we may need to resend the CONNECT request first to recreate
1522 request_headers_
.Clear();
1523 next_state_
= STATE_CREATE_STREAM
; // Resend the request.
1526 bool HttpNetworkTransaction::ShouldApplyProxyAuth() const {
1527 return UsingHttpProxyWithoutTunnel();
1530 bool HttpNetworkTransaction::ShouldApplyServerAuth() const {
1531 return !(request_
->load_flags
& LOAD_DO_NOT_SEND_AUTH_DATA
);
1534 int HttpNetworkTransaction::HandleAuthChallenge() {
1535 scoped_refptr
<HttpResponseHeaders
> headers(GetResponseHeaders());
1536 DCHECK(headers
.get());
1538 int status
= headers
->response_code();
1539 if (status
!= HTTP_UNAUTHORIZED
&&
1540 status
!= HTTP_PROXY_AUTHENTICATION_REQUIRED
)
1542 HttpAuth::Target target
= status
== HTTP_PROXY_AUTHENTICATION_REQUIRED
?
1543 HttpAuth::AUTH_PROXY
: HttpAuth::AUTH_SERVER
;
1544 if (target
== HttpAuth::AUTH_PROXY
&& proxy_info_
.is_direct())
1545 return ERR_UNEXPECTED_PROXY_AUTH
;
1547 // This case can trigger when an HTTPS server responds with a "Proxy
1548 // authentication required" status code through a non-authenticating
1550 if (!auth_controllers_
[target
].get())
1551 return ERR_UNEXPECTED_PROXY_AUTH
;
1553 int rv
= auth_controllers_
[target
]->HandleAuthChallenge(
1554 headers
, (request_
->load_flags
& LOAD_DO_NOT_SEND_AUTH_DATA
) != 0, false,
1556 if (auth_controllers_
[target
]->HaveAuthHandler())
1557 pending_auth_target_
= target
;
1559 scoped_refptr
<AuthChallengeInfo
> auth_info
=
1560 auth_controllers_
[target
]->auth_info();
1561 if (auth_info
.get())
1562 response_
.auth_challenge
= auth_info
;
1567 bool HttpNetworkTransaction::HaveAuth(HttpAuth::Target target
) const {
1568 return auth_controllers_
[target
].get() &&
1569 auth_controllers_
[target
]->HaveAuth();
1572 GURL
HttpNetworkTransaction::AuthURL(HttpAuth::Target target
) const {
1574 case HttpAuth::AUTH_PROXY
: {
1575 if (!proxy_info_
.proxy_server().is_valid() ||
1576 proxy_info_
.proxy_server().is_direct()) {
1577 return GURL(); // There is no proxy server.
1579 const char* scheme
= proxy_info_
.is_https() ? "https://" : "http://";
1580 return GURL(scheme
+
1581 proxy_info_
.proxy_server().host_port_pair().ToString());
1583 case HttpAuth::AUTH_SERVER
:
1584 if (ForWebSocketHandshake()) {
1585 const GURL
& url
= request_
->url
;
1586 url::Replacements
<char> ws_to_http
;
1587 if (url
.SchemeIs("ws")) {
1588 ws_to_http
.SetScheme("http", url::Component(0, 4));
1590 DCHECK(url
.SchemeIs("wss"));
1591 ws_to_http
.SetScheme("https", url::Component(0, 5));
1593 return url
.ReplaceComponents(ws_to_http
);
1595 return request_
->url
;
1601 bool HttpNetworkTransaction::ForWebSocketHandshake() const {
1602 return websocket_handshake_stream_base_create_helper_
&&
1603 request_
->url
.SchemeIsWSOrWSS();
1606 #define STATE_CASE(s) \
1608 description = base::StringPrintf("%s (0x%08X)", #s, s); \
1611 std::string
HttpNetworkTransaction::DescribeState(State state
) {
1612 std::string description
;
1614 STATE_CASE(STATE_NOTIFY_BEFORE_CREATE_STREAM
);
1615 STATE_CASE(STATE_CREATE_STREAM
);
1616 STATE_CASE(STATE_CREATE_STREAM_COMPLETE
);
1617 STATE_CASE(STATE_INIT_REQUEST_BODY
);
1618 STATE_CASE(STATE_INIT_REQUEST_BODY_COMPLETE
);
1619 STATE_CASE(STATE_BUILD_REQUEST
);
1620 STATE_CASE(STATE_BUILD_REQUEST_COMPLETE
);
1621 STATE_CASE(STATE_SEND_REQUEST
);
1622 STATE_CASE(STATE_SEND_REQUEST_COMPLETE
);
1623 STATE_CASE(STATE_READ_HEADERS
);
1624 STATE_CASE(STATE_READ_HEADERS_COMPLETE
);
1625 STATE_CASE(STATE_READ_BODY
);
1626 STATE_CASE(STATE_READ_BODY_COMPLETE
);
1627 STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART
);
1628 STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE
);
1629 STATE_CASE(STATE_NONE
);
1631 description
= base::StringPrintf("Unknown state 0x%08X (%u)", state
,
1640 void HttpNetworkTransaction::CopyConnectionAttemptsFromStreamRequest() {
1641 DCHECK(stream_request_
);
1643 // Since the transaction can restart with auth credentials, it may create a
1644 // stream more than once. Accumulate all of the connection attempts across
1645 // those streams by appending them to the vector:
1646 for (const auto& attempt
: stream_request_
->connection_attempts())
1647 connection_attempts_
.push_back(attempt
);