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/profiler/scoped_tracker.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.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"
70 void ProcessAlternateProtocol(
71 HttpNetworkSession
* session
,
72 const HttpResponseHeaders
& headers
,
73 const HostPortPair
& http_host_port_pair
) {
74 if (!headers
.HasHeader(kAlternateProtocolHeader
))
77 std::vector
<std::string
> alternate_protocol_values
;
79 std::string alternate_protocol_str
;
80 while (headers
.EnumerateHeader(&iter
, kAlternateProtocolHeader
,
81 &alternate_protocol_str
)) {
82 base::TrimWhitespaceASCII(alternate_protocol_str
, base::TRIM_ALL
,
83 &alternate_protocol_str
);
84 if (!alternate_protocol_str
.empty()) {
85 alternate_protocol_values
.push_back(alternate_protocol_str
);
89 session
->http_stream_factory()->ProcessAlternateProtocol(
90 session
->http_server_properties(),
91 alternate_protocol_values
,
96 base::Value
* NetLogSSLVersionFallbackCallback(
99 uint16 version_before
,
100 uint16 version_after
,
101 NetLog::LogLevel
/* log_level */) {
102 base::DictionaryValue
* dict
= new base::DictionaryValue();
103 dict
->SetString("host_and_port", GetHostAndPort(*url
));
104 dict
->SetInteger("net_error", net_error
);
105 dict
->SetInteger("version_before", version_before
);
106 dict
->SetInteger("version_after", version_after
);
112 //-----------------------------------------------------------------------------
114 HttpNetworkTransaction::HttpNetworkTransaction(RequestPriority priority
,
115 HttpNetworkSession
* session
)
116 : pending_auth_target_(HttpAuth::AUTH_NONE
),
117 io_callback_(base::Bind(&HttpNetworkTransaction::OnIOComplete
,
118 base::Unretained(this))),
122 headers_valid_(false),
123 fallback_error_code_(ERR_SSL_INAPPROPRIATE_FALLBACK
),
126 total_received_bytes_(0),
127 next_state_(STATE_NONE
),
128 establishing_tunnel_(false),
129 websocket_handshake_stream_base_create_helper_(NULL
) {
130 session
->ssl_config_service()->GetSSLConfig(&server_ssl_config_
);
131 session
->GetNextProtos(&server_ssl_config_
.next_protos
);
132 proxy_ssl_config_
= server_ssl_config_
;
135 HttpNetworkTransaction::~HttpNetworkTransaction() {
137 HttpResponseHeaders
* headers
= GetResponseHeaders();
138 // TODO(mbelshe): The stream_ should be able to compute whether or not the
139 // stream should be kept alive. No reason to compute here
141 bool try_to_keep_alive
=
142 next_state_
== STATE_NONE
&&
143 stream_
->CanFindEndOfResponse() &&
144 (!headers
|| headers
->IsKeepAlive());
145 if (!try_to_keep_alive
) {
146 stream_
->Close(true /* not reusable */);
148 if (stream_
->IsResponseBodyComplete()) {
149 // If the response body is complete, we can just reuse the socket.
150 stream_
->Close(false /* reusable */);
151 } else if (stream_
->IsSpdyHttpStream()) {
152 // Doesn't really matter for SpdyHttpStream. Just close it.
153 stream_
->Close(true /* not reusable */);
155 // Otherwise, we try to drain the response body.
156 HttpStream
* stream
= stream_
.release();
157 stream
->Drain(session_
);
162 if (request_
&& request_
->upload_data_stream
)
163 request_
->upload_data_stream
->Reset(); // Invalidate pending callbacks.
166 int HttpNetworkTransaction::Start(const HttpRequestInfo
* request_info
,
167 const CompletionCallback
& callback
,
168 const BoundNetLog
& net_log
) {
170 request_
= request_info
;
172 if (request_
->load_flags
& LOAD_DISABLE_CERT_REVOCATION_CHECKING
) {
173 server_ssl_config_
.rev_checking_enabled
= false;
174 proxy_ssl_config_
.rev_checking_enabled
= false;
177 if (request_
->load_flags
& LOAD_PREFETCH
)
178 response_
.unused_since_prefetch
= true;
180 // Channel ID is disabled if privacy mode is enabled for this request.
181 if (request_
->privacy_mode
== PRIVACY_MODE_ENABLED
)
182 server_ssl_config_
.channel_id_enabled
= false;
184 if (server_ssl_config_
.fastradio_padding_enabled
) {
185 server_ssl_config_
.fastradio_padding_eligible
=
186 session_
->ssl_config_service()->SupportsFastradioPadding(
190 next_state_
= STATE_NOTIFY_BEFORE_CREATE_STREAM
;
192 if (rv
== ERR_IO_PENDING
)
193 callback_
= callback
;
197 int HttpNetworkTransaction::RestartIgnoringLastError(
198 const CompletionCallback
& callback
) {
199 DCHECK(!stream_
.get());
200 DCHECK(!stream_request_
.get());
201 DCHECK_EQ(STATE_NONE
, next_state_
);
203 next_state_
= STATE_CREATE_STREAM
;
206 if (rv
== ERR_IO_PENDING
)
207 callback_
= callback
;
211 int HttpNetworkTransaction::RestartWithCertificate(
212 X509Certificate
* client_cert
, const CompletionCallback
& callback
) {
213 // In HandleCertificateRequest(), we always tear down existing stream
214 // requests to force a new connection. So we shouldn't have one here.
215 DCHECK(!stream_request_
.get());
216 DCHECK(!stream_
.get());
217 DCHECK_EQ(STATE_NONE
, next_state_
);
219 SSLConfig
* ssl_config
= response_
.cert_request_info
->is_proxy
?
220 &proxy_ssl_config_
: &server_ssl_config_
;
221 ssl_config
->send_client_cert
= true;
222 ssl_config
->client_cert
= client_cert
;
223 session_
->ssl_client_auth_cache()->Add(
224 response_
.cert_request_info
->host_and_port
, client_cert
);
225 // Reset the other member variables.
226 // Note: this is necessary only with SSL renegotiation.
227 ResetStateForRestart();
228 next_state_
= STATE_CREATE_STREAM
;
230 if (rv
== ERR_IO_PENDING
)
231 callback_
= callback
;
235 int HttpNetworkTransaction::RestartWithAuth(
236 const AuthCredentials
& credentials
, const CompletionCallback
& callback
) {
237 HttpAuth::Target target
= pending_auth_target_
;
238 if (target
== HttpAuth::AUTH_NONE
) {
240 return ERR_UNEXPECTED
;
242 pending_auth_target_
= HttpAuth::AUTH_NONE
;
244 auth_controllers_
[target
]->ResetAuth(credentials
);
246 DCHECK(callback_
.is_null());
249 if (target
== HttpAuth::AUTH_PROXY
&& establishing_tunnel_
) {
250 // In this case, we've gathered credentials for use with proxy
251 // authentication of a tunnel.
252 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
253 DCHECK(stream_request_
!= NULL
);
254 auth_controllers_
[target
] = NULL
;
255 ResetStateForRestart();
256 rv
= stream_request_
->RestartTunnelWithProxyAuth(credentials
);
258 // In this case, we've gathered credentials for the server or the proxy
259 // but it is not during the tunneling phase.
260 DCHECK(stream_request_
== NULL
);
261 PrepareForAuthRestart(target
);
265 if (rv
== ERR_IO_PENDING
)
266 callback_
= callback
;
270 void HttpNetworkTransaction::PrepareForAuthRestart(HttpAuth::Target target
) {
271 DCHECK(HaveAuth(target
));
272 DCHECK(!stream_request_
.get());
274 bool keep_alive
= false;
275 // Even if the server says the connection is keep-alive, we have to be
276 // able to find the end of each response in order to reuse the connection.
277 if (GetResponseHeaders()->IsKeepAlive() &&
278 stream_
->CanFindEndOfResponse()) {
279 // If the response body hasn't been completely read, we need to drain
281 if (!stream_
->IsResponseBodyComplete()) {
282 next_state_
= STATE_DRAIN_BODY_FOR_AUTH_RESTART
;
283 read_buf_
= new IOBuffer(kDrainBodyBufferSize
); // A bit bucket.
284 read_buf_len_
= kDrainBodyBufferSize
;
290 // We don't need to drain the response body, so we act as if we had drained
291 // the response body.
292 DidDrainBodyForAuthRestart(keep_alive
);
295 void HttpNetworkTransaction::DidDrainBodyForAuthRestart(bool keep_alive
) {
296 DCHECK(!stream_request_
.get());
299 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
300 HttpStream
* new_stream
= NULL
;
301 if (keep_alive
&& stream_
->IsConnectionReusable()) {
302 // We should call connection_->set_idle_time(), but this doesn't occur
303 // often enough to be worth the trouble.
304 stream_
->SetConnectionReused();
305 new_stream
= stream_
->RenewStreamForAuth();
309 // Close the stream and mark it as not_reusable. Even in the
310 // keep_alive case, we've determined that the stream_ is not
311 // reusable if new_stream is NULL.
312 stream_
->Close(true);
313 next_state_
= STATE_CREATE_STREAM
;
315 // Renewed streams shouldn't carry over received bytes.
316 DCHECK_EQ(0, new_stream
->GetTotalReceivedBytes());
317 next_state_
= STATE_INIT_STREAM
;
319 stream_
.reset(new_stream
);
322 // Reset the other member variables.
323 ResetStateForAuthRestart();
326 bool HttpNetworkTransaction::IsReadyToRestartForAuth() {
327 return pending_auth_target_
!= HttpAuth::AUTH_NONE
&&
328 HaveAuth(pending_auth_target_
);
331 int HttpNetworkTransaction::Read(IOBuffer
* buf
, int buf_len
,
332 const CompletionCallback
& callback
) {
334 DCHECK_LT(0, buf_len
);
336 State next_state
= STATE_NONE
;
338 scoped_refptr
<HttpResponseHeaders
> headers(GetResponseHeaders());
339 if (headers_valid_
&& headers
.get() && stream_request_
.get()) {
340 // We're trying to read the body of the response but we're still trying
341 // to establish an SSL tunnel through an HTTP proxy. We can't read these
342 // bytes when establishing a tunnel because they might be controlled by
343 // an active network attacker. We don't worry about this for HTTP
344 // because an active network attacker can already control HTTP sessions.
345 // We reach this case when the user cancels a 407 proxy auth prompt. We
346 // also don't worry about this for an HTTPS Proxy, because the
347 // communication with the proxy is secure.
348 // See http://crbug.com/8473.
349 DCHECK(proxy_info_
.is_http() || proxy_info_
.is_https());
350 DCHECK_EQ(headers
->response_code(), HTTP_PROXY_AUTHENTICATION_REQUIRED
);
351 LOG(WARNING
) << "Blocked proxy response with status "
352 << headers
->response_code() << " to CONNECT request for "
353 << GetHostAndPort(request_
->url
) << ".";
354 return ERR_TUNNEL_CONNECTION_FAILED
;
357 // Are we using SPDY or HTTP?
358 next_state
= STATE_READ_BODY
;
361 read_buf_len_
= buf_len
;
363 next_state_
= next_state
;
365 if (rv
== ERR_IO_PENDING
)
366 callback_
= callback
;
370 void HttpNetworkTransaction::StopCaching() {}
372 bool HttpNetworkTransaction::GetFullRequestHeaders(
373 HttpRequestHeaders
* headers
) const {
374 // TODO(ttuttle): Make sure we've populated request_headers_.
375 *headers
= request_headers_
;
379 int64
HttpNetworkTransaction::GetTotalReceivedBytes() const {
380 int64 total_received_bytes
= total_received_bytes_
;
382 total_received_bytes
+= stream_
->GetTotalReceivedBytes();
383 return total_received_bytes
;
386 void HttpNetworkTransaction::DoneReading() {}
388 const HttpResponseInfo
* HttpNetworkTransaction::GetResponseInfo() const {
389 return ((headers_valid_
&& response_
.headers
.get()) ||
390 response_
.ssl_info
.cert
.get() || response_
.cert_request_info
.get())
395 LoadState
HttpNetworkTransaction::GetLoadState() const {
396 // TODO(wtc): Define a new LoadState value for the
397 // STATE_INIT_CONNECTION_COMPLETE state, which delays the HTTP request.
398 switch (next_state_
) {
399 case STATE_CREATE_STREAM
:
400 return LOAD_STATE_WAITING_FOR_DELEGATE
;
401 case STATE_CREATE_STREAM_COMPLETE
:
402 return stream_request_
->GetLoadState();
403 case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
:
404 case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE
:
405 case STATE_SEND_REQUEST_COMPLETE
:
406 return LOAD_STATE_SENDING_REQUEST
;
407 case STATE_READ_HEADERS_COMPLETE
:
408 return LOAD_STATE_WAITING_FOR_RESPONSE
;
409 case STATE_READ_BODY_COMPLETE
:
410 return LOAD_STATE_READING_RESPONSE
;
412 return LOAD_STATE_IDLE
;
416 UploadProgress
HttpNetworkTransaction::GetUploadProgress() const {
418 return UploadProgress();
420 return stream_
->GetUploadProgress();
423 void HttpNetworkTransaction::SetQuicServerInfo(
424 QuicServerInfo
* quic_server_info
) {}
426 bool HttpNetworkTransaction::GetLoadTimingInfo(
427 LoadTimingInfo
* load_timing_info
) const {
428 if (!stream_
|| !stream_
->GetLoadTimingInfo(load_timing_info
))
431 load_timing_info
->proxy_resolve_start
=
432 proxy_info_
.proxy_resolve_start_time();
433 load_timing_info
->proxy_resolve_end
= proxy_info_
.proxy_resolve_end_time();
434 load_timing_info
->send_start
= send_start_time_
;
435 load_timing_info
->send_end
= send_end_time_
;
439 void HttpNetworkTransaction::SetPriority(RequestPriority priority
) {
440 priority_
= priority
;
442 stream_request_
->SetPriority(priority
);
444 stream_
->SetPriority(priority
);
447 void HttpNetworkTransaction::SetWebSocketHandshakeStreamCreateHelper(
448 WebSocketHandshakeStreamBase::CreateHelper
* create_helper
) {
449 websocket_handshake_stream_base_create_helper_
= create_helper
;
452 void HttpNetworkTransaction::SetBeforeNetworkStartCallback(
453 const BeforeNetworkStartCallback
& callback
) {
454 before_network_start_callback_
= callback
;
457 void HttpNetworkTransaction::SetBeforeProxyHeadersSentCallback(
458 const BeforeProxyHeadersSentCallback
& callback
) {
459 before_proxy_headers_sent_callback_
= callback
;
462 int HttpNetworkTransaction::ResumeNetworkStart() {
463 DCHECK_EQ(next_state_
, STATE_CREATE_STREAM
);
467 void HttpNetworkTransaction::OnStreamReady(const SSLConfig
& used_ssl_config
,
468 const ProxyInfo
& used_proxy_info
,
469 HttpStream
* stream
) {
470 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
471 DCHECK(stream_request_
.get());
474 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
475 stream_
.reset(stream
);
476 server_ssl_config_
= used_ssl_config
;
477 proxy_info_
= used_proxy_info
;
478 response_
.was_npn_negotiated
= stream_request_
->was_npn_negotiated();
479 response_
.npn_negotiated_protocol
= SSLClientSocket::NextProtoToString(
480 stream_request_
->protocol_negotiated());
481 response_
.was_fetched_via_spdy
= stream_request_
->using_spdy();
482 response_
.was_fetched_via_proxy
= !proxy_info_
.is_direct();
483 if (response_
.was_fetched_via_proxy
&& !proxy_info_
.is_empty())
484 response_
.proxy_server
= proxy_info_
.proxy_server().host_port_pair();
488 void HttpNetworkTransaction::OnWebSocketHandshakeStreamReady(
489 const SSLConfig
& used_ssl_config
,
490 const ProxyInfo
& used_proxy_info
,
491 WebSocketHandshakeStreamBase
* stream
) {
492 OnStreamReady(used_ssl_config
, used_proxy_info
, stream
);
495 void HttpNetworkTransaction::OnStreamFailed(int result
,
496 const SSLConfig
& used_ssl_config
) {
497 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
498 DCHECK_NE(OK
, result
);
499 DCHECK(stream_request_
.get());
500 DCHECK(!stream_
.get());
501 server_ssl_config_
= used_ssl_config
;
503 OnIOComplete(result
);
506 void HttpNetworkTransaction::OnCertificateError(
508 const SSLConfig
& used_ssl_config
,
509 const SSLInfo
& ssl_info
) {
510 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
511 DCHECK_NE(OK
, result
);
512 DCHECK(stream_request_
.get());
513 DCHECK(!stream_
.get());
515 response_
.ssl_info
= ssl_info
;
516 server_ssl_config_
= used_ssl_config
;
518 // TODO(mbelshe): For now, we're going to pass the error through, and that
519 // will close the stream_request in all cases. This means that we're always
520 // going to restart an entire STATE_CREATE_STREAM, even if the connection is
521 // good and the user chooses to ignore the error. This is not ideal, but not
522 // the end of the world either.
524 OnIOComplete(result
);
527 void HttpNetworkTransaction::OnNeedsProxyAuth(
528 const HttpResponseInfo
& proxy_response
,
529 const SSLConfig
& used_ssl_config
,
530 const ProxyInfo
& used_proxy_info
,
531 HttpAuthController
* auth_controller
) {
532 DCHECK(stream_request_
.get());
533 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
535 establishing_tunnel_
= true;
536 response_
.headers
= proxy_response
.headers
;
537 response_
.auth_challenge
= proxy_response
.auth_challenge
;
538 headers_valid_
= true;
539 server_ssl_config_
= used_ssl_config
;
540 proxy_info_
= used_proxy_info
;
542 auth_controllers_
[HttpAuth::AUTH_PROXY
] = auth_controller
;
543 pending_auth_target_
= HttpAuth::AUTH_PROXY
;
548 void HttpNetworkTransaction::OnNeedsClientAuth(
549 const SSLConfig
& used_ssl_config
,
550 SSLCertRequestInfo
* cert_info
) {
551 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
553 server_ssl_config_
= used_ssl_config
;
554 response_
.cert_request_info
= cert_info
;
555 OnIOComplete(ERR_SSL_CLIENT_AUTH_CERT_NEEDED
);
558 void HttpNetworkTransaction::OnHttpsProxyTunnelResponse(
559 const HttpResponseInfo
& response_info
,
560 const SSLConfig
& used_ssl_config
,
561 const ProxyInfo
& used_proxy_info
,
562 HttpStream
* stream
) {
563 DCHECK_EQ(STATE_CREATE_STREAM_COMPLETE
, next_state_
);
565 headers_valid_
= true;
566 response_
= response_info
;
567 server_ssl_config_
= used_ssl_config
;
568 proxy_info_
= used_proxy_info
;
570 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
571 stream_
.reset(stream
);
572 stream_request_
.reset(); // we're done with the stream request
573 OnIOComplete(ERR_HTTPS_PROXY_TUNNEL_RESPONSE
);
576 bool HttpNetworkTransaction::IsSecureRequest() const {
577 return request_
->url
.SchemeIsSecure();
580 bool HttpNetworkTransaction::UsingHttpProxyWithoutTunnel() const {
581 return (proxy_info_
.is_http() || proxy_info_
.is_https() ||
582 proxy_info_
.is_quic()) &&
583 !(request_
->url
.SchemeIs("https") || request_
->url
.SchemeIsWSOrWSS());
586 void HttpNetworkTransaction::DoCallback(int rv
) {
587 DCHECK_NE(rv
, ERR_IO_PENDING
);
588 DCHECK(!callback_
.is_null());
590 // Since Run may result in Read being called, clear user_callback_ up front.
591 CompletionCallback c
= callback_
;
596 void HttpNetworkTransaction::OnIOComplete(int result
) {
597 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424359 is fixed.
598 tracked_objects::ScopedTracker
tracking_profile1(
599 FROM_HERE_WITH_EXPLICIT_FUNCTION(
600 "424359 HttpNetworkTransaction::OnIOComplete 1"));
602 int rv
= DoLoop(result
);
604 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424359 is fixed.
605 tracked_objects::ScopedTracker
tracking_profile2(
606 FROM_HERE_WITH_EXPLICIT_FUNCTION(
607 "424359 HttpNetworkTransaction::OnIOComplete 2"));
609 if (rv
!= ERR_IO_PENDING
)
613 int HttpNetworkTransaction::DoLoop(int result
) {
614 DCHECK(next_state_
!= STATE_NONE
);
618 State state
= next_state_
;
619 next_state_
= STATE_NONE
;
621 case STATE_NOTIFY_BEFORE_CREATE_STREAM
:
623 rv
= DoNotifyBeforeCreateStream();
625 case STATE_CREATE_STREAM
:
627 rv
= DoCreateStream();
629 case STATE_CREATE_STREAM_COMPLETE
:
630 rv
= DoCreateStreamComplete(rv
);
632 case STATE_INIT_STREAM
:
636 case STATE_INIT_STREAM_COMPLETE
:
637 rv
= DoInitStreamComplete(rv
);
639 case STATE_GENERATE_PROXY_AUTH_TOKEN
:
641 rv
= DoGenerateProxyAuthToken();
643 case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
:
644 rv
= DoGenerateProxyAuthTokenComplete(rv
);
646 case STATE_GENERATE_SERVER_AUTH_TOKEN
:
648 rv
= DoGenerateServerAuthToken();
650 case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE
:
651 rv
= DoGenerateServerAuthTokenComplete(rv
);
653 case STATE_INIT_REQUEST_BODY
:
655 rv
= DoInitRequestBody();
657 case STATE_INIT_REQUEST_BODY_COMPLETE
:
658 rv
= DoInitRequestBodyComplete(rv
);
660 case STATE_BUILD_REQUEST
:
662 net_log_
.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST
);
663 rv
= DoBuildRequest();
665 case STATE_BUILD_REQUEST_COMPLETE
:
666 rv
= DoBuildRequestComplete(rv
);
668 case STATE_SEND_REQUEST
:
670 rv
= DoSendRequest();
672 case STATE_SEND_REQUEST_COMPLETE
:
673 rv
= DoSendRequestComplete(rv
);
674 net_log_
.EndEventWithNetErrorCode(
675 NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST
, rv
);
677 case STATE_READ_HEADERS
:
679 net_log_
.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS
);
680 rv
= DoReadHeaders();
682 case STATE_READ_HEADERS_COMPLETE
:
683 rv
= DoReadHeadersComplete(rv
);
684 net_log_
.EndEventWithNetErrorCode(
685 NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS
, rv
);
687 case STATE_READ_BODY
:
689 net_log_
.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_BODY
);
692 case STATE_READ_BODY_COMPLETE
:
693 rv
= DoReadBodyComplete(rv
);
694 net_log_
.EndEventWithNetErrorCode(
695 NetLog::TYPE_HTTP_TRANSACTION_READ_BODY
, rv
);
697 case STATE_DRAIN_BODY_FOR_AUTH_RESTART
:
700 NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART
);
701 rv
= DoDrainBodyForAuthRestart();
703 case STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE
:
704 rv
= DoDrainBodyForAuthRestartComplete(rv
);
705 net_log_
.EndEventWithNetErrorCode(
706 NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART
, rv
);
709 NOTREACHED() << "bad state";
713 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
718 int HttpNetworkTransaction::DoNotifyBeforeCreateStream() {
719 next_state_
= STATE_CREATE_STREAM
;
721 if (!before_network_start_callback_
.is_null())
722 before_network_start_callback_
.Run(&defer
);
725 return ERR_IO_PENDING
;
728 int HttpNetworkTransaction::DoCreateStream() {
729 next_state_
= STATE_CREATE_STREAM_COMPLETE
;
730 if (ForWebSocketHandshake()) {
731 stream_request_
.reset(
732 session_
->http_stream_factory_for_websocket()
733 ->RequestWebSocketHandshakeStream(
739 websocket_handshake_stream_base_create_helper_
,
742 stream_request_
.reset(
743 session_
->http_stream_factory()->RequestStream(
751 DCHECK(stream_request_
.get());
752 return ERR_IO_PENDING
;
755 int HttpNetworkTransaction::DoCreateStreamComplete(int result
) {
757 next_state_
= STATE_INIT_STREAM
;
758 DCHECK(stream_
.get());
759 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
760 result
= HandleCertificateRequest(result
);
761 } else if (result
== ERR_HTTPS_PROXY_TUNNEL_RESPONSE
) {
762 // Return OK and let the caller read the proxy's error page
763 next_state_
= STATE_NONE
;
765 } else if (result
== ERR_HTTP_1_1_REQUIRED
||
766 result
== ERR_PROXY_HTTP_1_1_REQUIRED
) {
767 return HandleHttp11Required(result
);
770 // Handle possible handshake errors that may have occurred if the stream
771 // used SSL for one or more of the layers.
772 result
= HandleSSLHandshakeError(result
);
774 // At this point we are done with the stream_request_.
775 stream_request_
.reset();
779 int HttpNetworkTransaction::DoInitStream() {
780 DCHECK(stream_
.get());
781 next_state_
= STATE_INIT_STREAM_COMPLETE
;
782 return stream_
->InitializeStream(request_
, priority_
, net_log_
, io_callback_
);
785 int HttpNetworkTransaction::DoInitStreamComplete(int result
) {
787 next_state_
= STATE_GENERATE_PROXY_AUTH_TOKEN
;
790 result
= HandleIOError(result
);
792 // The stream initialization failed, so this stream will never be useful.
794 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
801 int HttpNetworkTransaction::DoGenerateProxyAuthToken() {
802 next_state_
= STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE
;
803 if (!ShouldApplyProxyAuth())
805 HttpAuth::Target target
= HttpAuth::AUTH_PROXY
;
806 if (!auth_controllers_
[target
].get())
807 auth_controllers_
[target
] =
808 new HttpAuthController(target
,
810 session_
->http_auth_cache(),
811 session_
->http_auth_handler_factory());
812 return auth_controllers_
[target
]->MaybeGenerateAuthToken(request_
,
817 int HttpNetworkTransaction::DoGenerateProxyAuthTokenComplete(int rv
) {
818 DCHECK_NE(ERR_IO_PENDING
, rv
);
820 next_state_
= STATE_GENERATE_SERVER_AUTH_TOKEN
;
824 int HttpNetworkTransaction::DoGenerateServerAuthToken() {
825 next_state_
= STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE
;
826 HttpAuth::Target target
= HttpAuth::AUTH_SERVER
;
827 if (!auth_controllers_
[target
].get()) {
828 auth_controllers_
[target
] =
829 new HttpAuthController(target
,
831 session_
->http_auth_cache(),
832 session_
->http_auth_handler_factory());
833 if (request_
->load_flags
& LOAD_DO_NOT_USE_EMBEDDED_IDENTITY
)
834 auth_controllers_
[target
]->DisableEmbeddedIdentity();
836 if (!ShouldApplyServerAuth())
838 return auth_controllers_
[target
]->MaybeGenerateAuthToken(request_
,
843 int HttpNetworkTransaction::DoGenerateServerAuthTokenComplete(int rv
) {
844 DCHECK_NE(ERR_IO_PENDING
, rv
);
846 next_state_
= STATE_INIT_REQUEST_BODY
;
850 void HttpNetworkTransaction::BuildRequestHeaders(
851 bool using_http_proxy_without_tunnel
) {
852 request_headers_
.SetHeader(HttpRequestHeaders::kHost
,
853 GetHostAndOptionalPort(request_
->url
));
855 // For compat with HTTP/1.0 servers and proxies:
856 if (using_http_proxy_without_tunnel
) {
857 request_headers_
.SetHeader(HttpRequestHeaders::kProxyConnection
,
860 request_headers_
.SetHeader(HttpRequestHeaders::kConnection
, "keep-alive");
863 // Add a content length header?
864 if (request_
->upload_data_stream
) {
865 if (request_
->upload_data_stream
->is_chunked()) {
866 request_headers_
.SetHeader(
867 HttpRequestHeaders::kTransferEncoding
, "chunked");
869 request_headers_
.SetHeader(
870 HttpRequestHeaders::kContentLength
,
871 base::Uint64ToString(request_
->upload_data_stream
->size()));
873 } else if (request_
->method
== "POST" || request_
->method
== "PUT" ||
874 request_
->method
== "HEAD") {
875 // An empty POST/PUT request still needs a content length. As for HEAD,
876 // IE and Safari also add a content length header. Presumably it is to
877 // support sending a HEAD request to an URL that only expects to be sent a
878 // POST or some other method that normally would have a message body.
879 request_headers_
.SetHeader(HttpRequestHeaders::kContentLength
, "0");
882 // Honor load flags that impact proxy caches.
883 if (request_
->load_flags
& LOAD_BYPASS_CACHE
) {
884 request_headers_
.SetHeader(HttpRequestHeaders::kPragma
, "no-cache");
885 request_headers_
.SetHeader(HttpRequestHeaders::kCacheControl
, "no-cache");
886 } else if (request_
->load_flags
& LOAD_VALIDATE_CACHE
) {
887 request_headers_
.SetHeader(HttpRequestHeaders::kCacheControl
, "max-age=0");
890 if (ShouldApplyProxyAuth() && HaveAuth(HttpAuth::AUTH_PROXY
))
891 auth_controllers_
[HttpAuth::AUTH_PROXY
]->AddAuthorizationHeader(
893 if (ShouldApplyServerAuth() && HaveAuth(HttpAuth::AUTH_SERVER
))
894 auth_controllers_
[HttpAuth::AUTH_SERVER
]->AddAuthorizationHeader(
897 request_headers_
.MergeFrom(request_
->extra_headers
);
899 if (using_http_proxy_without_tunnel
&&
900 !before_proxy_headers_sent_callback_
.is_null())
901 before_proxy_headers_sent_callback_
.Run(proxy_info_
, &request_headers_
);
903 response_
.did_use_http_auth
=
904 request_headers_
.HasHeader(HttpRequestHeaders::kAuthorization
) ||
905 request_headers_
.HasHeader(HttpRequestHeaders::kProxyAuthorization
);
908 int HttpNetworkTransaction::DoInitRequestBody() {
909 next_state_
= STATE_INIT_REQUEST_BODY_COMPLETE
;
911 if (request_
->upload_data_stream
)
912 rv
= request_
->upload_data_stream
->Init(io_callback_
);
916 int HttpNetworkTransaction::DoInitRequestBodyComplete(int result
) {
918 next_state_
= STATE_BUILD_REQUEST
;
922 int HttpNetworkTransaction::DoBuildRequest() {
923 next_state_
= STATE_BUILD_REQUEST_COMPLETE
;
924 headers_valid_
= false;
926 // This is constructed lazily (instead of within our Start method), so that
927 // we have proxy info available.
928 if (request_headers_
.IsEmpty()) {
929 bool using_http_proxy_without_tunnel
= UsingHttpProxyWithoutTunnel();
930 BuildRequestHeaders(using_http_proxy_without_tunnel
);
936 int HttpNetworkTransaction::DoBuildRequestComplete(int result
) {
938 next_state_
= STATE_SEND_REQUEST
;
942 int HttpNetworkTransaction::DoSendRequest() {
943 send_start_time_
= base::TimeTicks::Now();
944 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
946 return stream_
->SendRequest(request_headers_
, &response_
, io_callback_
);
949 int HttpNetworkTransaction::DoSendRequestComplete(int result
) {
950 send_end_time_
= base::TimeTicks::Now();
952 return HandleIOError(result
);
953 response_
.network_accessed
= true;
954 next_state_
= STATE_READ_HEADERS
;
958 int HttpNetworkTransaction::DoReadHeaders() {
959 next_state_
= STATE_READ_HEADERS_COMPLETE
;
960 return stream_
->ReadResponseHeaders(io_callback_
);
963 int HttpNetworkTransaction::DoReadHeadersComplete(int result
) {
964 // We can get a certificate error or ERR_SSL_CLIENT_AUTH_CERT_NEEDED here
965 // due to SSL renegotiation.
966 if (IsCertificateError(result
)) {
967 // We don't handle a certificate error during SSL renegotiation, so we
968 // have to return an error that's not in the certificate error range
970 LOG(ERROR
) << "Got a server certificate with error " << result
971 << " during SSL renegotiation";
972 result
= ERR_CERT_ERROR_IN_SSL_RENEGOTIATION
;
973 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
974 // TODO(wtc): Need a test case for this code path!
975 DCHECK(stream_
.get());
976 DCHECK(IsSecureRequest());
977 response_
.cert_request_info
= new SSLCertRequestInfo
;
978 stream_
->GetSSLCertRequestInfo(response_
.cert_request_info
.get());
979 result
= HandleCertificateRequest(result
);
984 if (result
== ERR_HTTP_1_1_REQUIRED
||
985 result
== ERR_PROXY_HTTP_1_1_REQUIRED
) {
986 return HandleHttp11Required(result
);
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 ProcessAlternateProtocol(session_
, *response_
.headers
.get(),
1051 HostPortPair::FromURL(request_
->url
));
1053 int rv
= HandleAuthChallenge();
1057 if (IsSecureRequest())
1058 stream_
->GetSSLInfo(&response_
.ssl_info
);
1060 headers_valid_
= true;
1062 if (session_
->huffman_aggregator()) {
1063 session_
->huffman_aggregator()->AggregateTransactionCharacterCounts(
1066 proxy_info_
.proxy_server(),
1067 *response_
.headers
.get());
1072 int HttpNetworkTransaction::DoReadBody() {
1073 DCHECK(read_buf_
.get());
1074 DCHECK_GT(read_buf_len_
, 0);
1075 DCHECK(stream_
!= NULL
);
1077 next_state_
= STATE_READ_BODY_COMPLETE
;
1078 return stream_
->ReadResponseBody(
1079 read_buf_
.get(), read_buf_len_
, io_callback_
);
1082 int HttpNetworkTransaction::DoReadBodyComplete(int result
) {
1083 // We are done with the Read call.
1086 DCHECK_NE(ERR_IO_PENDING
, result
);
1090 bool keep_alive
= false;
1091 if (stream_
->IsResponseBodyComplete()) {
1092 // Note: Just because IsResponseBodyComplete is true, we're not
1093 // necessarily "done". We're only "done" when it is the last
1094 // read on this HttpNetworkTransaction, which will be signified
1095 // by a zero-length read.
1096 // TODO(mbelshe): The keepalive property is really a property of
1097 // the stream. No need to compute it here just to pass back
1098 // to the stream's Close function.
1099 // TODO(rtenneti): CanFindEndOfResponse should return false if there are no
1101 if (stream_
->CanFindEndOfResponse()) {
1102 HttpResponseHeaders
* headers
= GetResponseHeaders();
1104 keep_alive
= headers
->IsKeepAlive();
1108 // Clean up connection if we are done.
1110 stream_
->Close(!keep_alive
);
1111 // Note: we don't reset the stream here. We've closed it, but we still
1112 // need it around so that callers can call methods such as
1113 // GetUploadProgress() and have them be meaningful.
1114 // TODO(mbelshe): This means we closed the stream here, and we close it
1115 // again in ~HttpNetworkTransaction. Clean that up.
1117 // The next Read call will return 0 (EOF).
1120 // Clear these to avoid leaving around old state.
1127 int HttpNetworkTransaction::DoDrainBodyForAuthRestart() {
1128 // This method differs from DoReadBody only in the next_state_. So we just
1129 // call DoReadBody and override the next_state_. Perhaps there is a more
1130 // elegant way for these two methods to share code.
1131 int rv
= DoReadBody();
1132 DCHECK(next_state_
== STATE_READ_BODY_COMPLETE
);
1133 next_state_
= STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE
;
1137 // TODO(wtc): This method and the DoReadBodyComplete method are almost
1138 // the same. Figure out a good way for these two methods to share code.
1139 int HttpNetworkTransaction::DoDrainBodyForAuthRestartComplete(int result
) {
1140 // keep_alive defaults to true because the very reason we're draining the
1141 // response body is to reuse the connection for auth restart.
1142 bool done
= false, keep_alive
= true;
1144 // Error or closed connection while reading the socket.
1147 } else if (stream_
->IsResponseBodyComplete()) {
1152 DidDrainBodyForAuthRestart(keep_alive
);
1155 next_state_
= STATE_DRAIN_BODY_FOR_AUTH_RESTART
;
1161 int HttpNetworkTransaction::HandleCertificateRequest(int error
) {
1162 // There are two paths through which the server can request a certificate
1163 // from us. The first is during the initial handshake, the second is
1164 // during SSL renegotiation.
1166 // In both cases, we want to close the connection before proceeding.
1167 // We do this for two reasons:
1168 // First, we don't want to keep the connection to the server hung for a
1169 // long time while the user selects a certificate.
1170 // Second, even if we did keep the connection open, NSS has a bug where
1171 // restarting the handshake for ClientAuth is currently broken.
1172 DCHECK_EQ(error
, ERR_SSL_CLIENT_AUTH_CERT_NEEDED
);
1174 if (stream_
.get()) {
1175 // Since we already have a stream, we're being called as part of SSL
1177 DCHECK(!stream_request_
.get());
1178 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
1179 stream_
->Close(true);
1183 // The server is asking for a client certificate during the initial
1185 stream_request_
.reset();
1187 // If the user selected one of the certificates in client_certs or declined
1188 // to provide one for this server before, use the past decision
1190 scoped_refptr
<X509Certificate
> client_cert
;
1191 bool found_cached_cert
= session_
->ssl_client_auth_cache()->Lookup(
1192 response_
.cert_request_info
->host_and_port
, &client_cert
);
1193 if (!found_cached_cert
)
1196 // Check that the certificate selected is still a certificate the server
1197 // is likely to accept, based on the criteria supplied in the
1198 // CertificateRequest message.
1199 if (client_cert
.get()) {
1200 const std::vector
<std::string
>& cert_authorities
=
1201 response_
.cert_request_info
->cert_authorities
;
1203 bool cert_still_valid
= cert_authorities
.empty() ||
1204 client_cert
->IsIssuedByEncoded(cert_authorities
);
1205 if (!cert_still_valid
)
1209 // TODO(davidben): Add a unit test which covers this path; we need to be
1210 // able to send a legitimate certificate and also bypass/clear the
1211 // SSL session cache.
1212 SSLConfig
* ssl_config
= response_
.cert_request_info
->is_proxy
?
1213 &proxy_ssl_config_
: &server_ssl_config_
;
1214 ssl_config
->send_client_cert
= true;
1215 ssl_config
->client_cert
= client_cert
;
1216 next_state_
= STATE_CREATE_STREAM
;
1217 // Reset the other member variables.
1218 // Note: this is necessary only with SSL renegotiation.
1219 ResetStateForRestart();
1223 int HttpNetworkTransaction::HandleHttp11Required(int error
) {
1224 DCHECK(error
== ERR_HTTP_1_1_REQUIRED
||
1225 error
== ERR_PROXY_HTTP_1_1_REQUIRED
);
1227 if (error
== ERR_HTTP_1_1_REQUIRED
) {
1228 HttpServerProperties::ForceHTTP11(&server_ssl_config_
);
1230 HttpServerProperties::ForceHTTP11(&proxy_ssl_config_
);
1232 ResetConnectionAndRequestForResend();
1236 void HttpNetworkTransaction::HandleClientAuthError(int error
) {
1237 if (server_ssl_config_
.send_client_cert
&&
1238 (error
== ERR_SSL_PROTOCOL_ERROR
|| IsClientCertificateError(error
))) {
1239 session_
->ssl_client_auth_cache()->Remove(
1240 HostPortPair::FromURL(request_
->url
));
1244 // TODO(rch): This does not correctly handle errors when an SSL proxy is
1245 // being used, as all of the errors are handled as if they were generated
1246 // by the endpoint host, request_->url, rather than considering if they were
1247 // generated by the SSL proxy. http://crbug.com/69329
1248 int HttpNetworkTransaction::HandleSSLHandshakeError(int error
) {
1250 HandleClientAuthError(error
);
1252 bool should_fallback
= false;
1253 uint16 version_max
= server_ssl_config_
.version_max
;
1256 case ERR_CONNECTION_CLOSED
:
1257 case ERR_SSL_PROTOCOL_ERROR
:
1258 case ERR_SSL_VERSION_OR_CIPHER_MISMATCH
:
1259 if (version_max
>= SSL_PROTOCOL_VERSION_TLS1
&&
1260 version_max
> server_ssl_config_
.version_min
) {
1261 // This could be a TLS-intolerant server or a server that chose a
1262 // cipher suite defined only for higher protocol versions (such as
1263 // an SSL 3.0 server that chose a TLS-only cipher suite). Fall
1264 // back to the next lower version and retry.
1265 // NOTE: if the SSLClientSocket class doesn't support TLS 1.1,
1266 // specifying TLS 1.1 in version_max will result in a TLS 1.0
1267 // handshake, so falling back from TLS 1.1 to TLS 1.0 will simply
1268 // repeat the TLS 1.0 handshake. To avoid this problem, the default
1269 // version_max should match the maximum protocol version supported
1270 // by the SSLClientSocket class.
1273 // Fallback to the lower SSL version.
1274 // While SSL 3.0 fallback should be eliminated because of security
1275 // reasons, there is a high risk of breaking the servers if this is
1277 should_fallback
= true;
1280 case ERR_CONNECTION_RESET
:
1281 if (version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
&&
1282 version_max
> server_ssl_config_
.version_min
) {
1283 // Some network devices that inspect application-layer packets seem to
1284 // inject TCP reset packets to break the connections when they see TLS
1285 // 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
1287 // Only allow ERR_CONNECTION_RESET to trigger a fallback from TLS 1.1 or
1288 // 1.2. We don't lose much in this fallback because the explicit IV for
1289 // CBC mode in TLS 1.1 is approximated by record splitting in TLS
1290 // 1.0. The fallback will be more painful for TLS 1.2 when we have GCM
1293 // ERR_CONNECTION_RESET is a common network error, so we don't want it
1294 // to trigger a version fallback in general, especially the TLS 1.0 ->
1295 // SSL 3.0 fallback, which would drop TLS extensions.
1297 should_fallback
= true;
1300 case ERR_SSL_BAD_RECORD_MAC_ALERT
:
1301 if (version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
&&
1302 version_max
> server_ssl_config_
.version_min
) {
1303 // Some broken SSL devices negotiate TLS 1.0 when sent a TLS 1.1 or
1304 // 1.2 ClientHello, but then return a bad_record_mac alert. See
1305 // crbug.com/260358. In order to make the fallback as minimal as
1306 // possible, this fallback is only triggered for >= TLS 1.1.
1308 should_fallback
= true;
1311 case ERR_SSL_INAPPROPRIATE_FALLBACK
:
1312 // The server told us that we should not have fallen back. A buggy server
1313 // could trigger ERR_SSL_INAPPROPRIATE_FALLBACK with the initial
1314 // connection. |fallback_error_code_| is initialised to
1315 // ERR_SSL_INAPPROPRIATE_FALLBACK to catch this case.
1316 error
= fallback_error_code_
;
1320 if (should_fallback
) {
1322 NetLog::TYPE_SSL_VERSION_FALLBACK
,
1323 base::Bind(&NetLogSSLVersionFallbackCallback
,
1324 &request_
->url
, error
, server_ssl_config_
.version_max
,
1326 fallback_error_code_
= error
;
1327 server_ssl_config_
.version_max
= version_max
;
1328 server_ssl_config_
.version_fallback
= true;
1329 ResetConnectionAndRequestForResend();
1336 // This method determines whether it is safe to resend the request after an
1337 // IO error. It can only be called in response to request header or body
1338 // write errors or response header read errors. It should not be used in
1339 // other cases, such as a Connect error.
1340 int HttpNetworkTransaction::HandleIOError(int error
) {
1341 // Because the peer may request renegotiation with client authentication at
1342 // any time, check and handle client authentication errors.
1343 HandleClientAuthError(error
);
1346 // If we try to reuse a connection that the server is in the process of
1347 // closing, we may end up successfully writing out our request (or a
1348 // portion of our request) only to find a connection error when we try to
1349 // read from (or finish writing to) the socket.
1350 case ERR_CONNECTION_RESET
:
1351 case ERR_CONNECTION_CLOSED
:
1352 case ERR_CONNECTION_ABORTED
:
1353 // There can be a race between the socket pool checking checking whether a
1354 // socket is still connected, receiving the FIN, and sending/reading data
1355 // on a reused socket. If we receive the FIN between the connectedness
1356 // check and writing/reading from the socket, we may first learn the socket
1357 // is disconnected when we get a ERR_SOCKET_NOT_CONNECTED. This will most
1358 // likely happen when trying to retrieve its IP address.
1359 // See http://crbug.com/105824 for more details.
1360 case ERR_SOCKET_NOT_CONNECTED
:
1361 // If a socket is closed on its initial request, HttpStreamParser returns
1362 // ERR_EMPTY_RESPONSE. This may still be close/reuse race if the socket was
1363 // preconnected but failed to be used before the server timed it out.
1364 case ERR_EMPTY_RESPONSE
:
1365 if (ShouldResendRequest()) {
1366 net_log_
.AddEventWithNetErrorCode(
1367 NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR
, error
);
1368 ResetConnectionAndRequestForResend();
1372 case ERR_SPDY_PING_FAILED
:
1373 case ERR_SPDY_SERVER_REFUSED_STREAM
:
1374 case ERR_QUIC_HANDSHAKE_FAILED
:
1375 net_log_
.AddEventWithNetErrorCode(
1376 NetLog::TYPE_HTTP_TRANSACTION_RESTART_AFTER_ERROR
, error
);
1377 ResetConnectionAndRequestForResend();
1384 void HttpNetworkTransaction::ResetStateForRestart() {
1385 ResetStateForAuthRestart();
1387 total_received_bytes_
+= stream_
->GetTotalReceivedBytes();
1391 void HttpNetworkTransaction::ResetStateForAuthRestart() {
1392 send_start_time_
= base::TimeTicks();
1393 send_end_time_
= base::TimeTicks();
1395 pending_auth_target_
= HttpAuth::AUTH_NONE
;
1398 headers_valid_
= false;
1399 request_headers_
.Clear();
1400 response_
= HttpResponseInfo();
1401 establishing_tunnel_
= false;
1404 HttpResponseHeaders
* HttpNetworkTransaction::GetResponseHeaders() const {
1405 return response_
.headers
.get();
1408 bool HttpNetworkTransaction::ShouldResendRequest() const {
1409 bool connection_is_proven
= stream_
->IsConnectionReused();
1410 bool has_received_headers
= GetResponseHeaders() != NULL
;
1412 // NOTE: we resend a request only if we reused a keep-alive connection.
1413 // This automatically prevents an infinite resend loop because we'll run
1414 // out of the cached keep-alive connections eventually.
1415 if (connection_is_proven
&& !has_received_headers
)
1420 void HttpNetworkTransaction::ResetConnectionAndRequestForResend() {
1421 if (stream_
.get()) {
1422 stream_
->Close(true);
1426 // We need to clear request_headers_ because it contains the real request
1427 // headers, but we may need to resend the CONNECT request first to recreate
1429 request_headers_
.Clear();
1430 next_state_
= STATE_CREATE_STREAM
; // Resend the request.
1433 bool HttpNetworkTransaction::ShouldApplyProxyAuth() const {
1434 return UsingHttpProxyWithoutTunnel();
1437 bool HttpNetworkTransaction::ShouldApplyServerAuth() const {
1438 return !(request_
->load_flags
& LOAD_DO_NOT_SEND_AUTH_DATA
);
1441 int HttpNetworkTransaction::HandleAuthChallenge() {
1442 scoped_refptr
<HttpResponseHeaders
> headers(GetResponseHeaders());
1443 DCHECK(headers
.get());
1445 int status
= headers
->response_code();
1446 if (status
!= HTTP_UNAUTHORIZED
&&
1447 status
!= HTTP_PROXY_AUTHENTICATION_REQUIRED
)
1449 HttpAuth::Target target
= status
== HTTP_PROXY_AUTHENTICATION_REQUIRED
?
1450 HttpAuth::AUTH_PROXY
: HttpAuth::AUTH_SERVER
;
1451 if (target
== HttpAuth::AUTH_PROXY
&& proxy_info_
.is_direct())
1452 return ERR_UNEXPECTED_PROXY_AUTH
;
1454 // This case can trigger when an HTTPS server responds with a "Proxy
1455 // authentication required" status code through a non-authenticating
1457 if (!auth_controllers_
[target
].get())
1458 return ERR_UNEXPECTED_PROXY_AUTH
;
1460 int rv
= auth_controllers_
[target
]->HandleAuthChallenge(
1461 headers
, (request_
->load_flags
& LOAD_DO_NOT_SEND_AUTH_DATA
) != 0, false,
1463 if (auth_controllers_
[target
]->HaveAuthHandler())
1464 pending_auth_target_
= target
;
1466 scoped_refptr
<AuthChallengeInfo
> auth_info
=
1467 auth_controllers_
[target
]->auth_info();
1468 if (auth_info
.get())
1469 response_
.auth_challenge
= auth_info
;
1474 bool HttpNetworkTransaction::HaveAuth(HttpAuth::Target target
) const {
1475 return auth_controllers_
[target
].get() &&
1476 auth_controllers_
[target
]->HaveAuth();
1479 GURL
HttpNetworkTransaction::AuthURL(HttpAuth::Target target
) const {
1481 case HttpAuth::AUTH_PROXY
: {
1482 if (!proxy_info_
.proxy_server().is_valid() ||
1483 proxy_info_
.proxy_server().is_direct()) {
1484 return GURL(); // There is no proxy server.
1486 const char* scheme
= proxy_info_
.is_https() ? "https://" : "http://";
1487 return GURL(scheme
+
1488 proxy_info_
.proxy_server().host_port_pair().ToString());
1490 case HttpAuth::AUTH_SERVER
:
1491 if (ForWebSocketHandshake()) {
1492 const GURL
& url
= request_
->url
;
1493 url::Replacements
<char> ws_to_http
;
1494 if (url
.SchemeIs("ws")) {
1495 ws_to_http
.SetScheme("http", url::Component(0, 4));
1497 DCHECK(url
.SchemeIs("wss"));
1498 ws_to_http
.SetScheme("https", url::Component(0, 5));
1500 return url
.ReplaceComponents(ws_to_http
);
1502 return request_
->url
;
1508 bool HttpNetworkTransaction::ForWebSocketHandshake() const {
1509 return websocket_handshake_stream_base_create_helper_
&&
1510 request_
->url
.SchemeIsWSOrWSS();
1513 #define STATE_CASE(s) \
1515 description = base::StringPrintf("%s (0x%08X)", #s, s); \
1518 std::string
HttpNetworkTransaction::DescribeState(State state
) {
1519 std::string description
;
1521 STATE_CASE(STATE_NOTIFY_BEFORE_CREATE_STREAM
);
1522 STATE_CASE(STATE_CREATE_STREAM
);
1523 STATE_CASE(STATE_CREATE_STREAM_COMPLETE
);
1524 STATE_CASE(STATE_INIT_REQUEST_BODY
);
1525 STATE_CASE(STATE_INIT_REQUEST_BODY_COMPLETE
);
1526 STATE_CASE(STATE_BUILD_REQUEST
);
1527 STATE_CASE(STATE_BUILD_REQUEST_COMPLETE
);
1528 STATE_CASE(STATE_SEND_REQUEST
);
1529 STATE_CASE(STATE_SEND_REQUEST_COMPLETE
);
1530 STATE_CASE(STATE_READ_HEADERS
);
1531 STATE_CASE(STATE_READ_HEADERS_COMPLETE
);
1532 STATE_CASE(STATE_READ_BODY
);
1533 STATE_CASE(STATE_READ_BODY_COMPLETE
);
1534 STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART
);
1535 STATE_CASE(STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE
);
1536 STATE_CASE(STATE_NONE
);
1538 description
= base::StringPrintf("Unknown state 0x%08X (%u)", state
,