Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / net / http / http_network_transaction.cc
blob29967723d4b1a1b7a6eec19cedb8044247672746
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/http/http_network_transaction.h"
7 #include <set>
8 #include <vector>
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/compiler_specific.h"
13 #include "base/format_macros.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/metrics/field_trial.h"
16 #include "base/metrics/histogram_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"
63 #include "url/gurl.h"
64 #include "url/url_canon.h"
66 namespace net {
68 namespace {
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".
82 return;
85 if (!headers.HasHeader(kAlternateProtocolHeader))
86 return;
88 std::vector<std::string> alternate_protocol_values;
89 void* iter = NULL;
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,
103 http_host_port_pair,
104 *session);
107 scoped_ptr<base::Value> NetLogSSLVersionFallbackCallback(
108 const GURL* url,
109 int net_error,
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);
120 return dict.Pass();
123 scoped_ptr<base::Value> NetLogSSLCipherFallbackCallback(
124 const GURL* url,
125 int net_error,
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);
130 return dict.Pass();
133 } // namespace
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))),
142 session_(session),
143 request_(NULL),
144 priority_(priority),
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),
149 request_headers_(),
150 read_buf_len_(0),
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() {
161 if (stream_.get()) {
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
164 // and pass it in.
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 */);
170 } else {
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) {
184 net_log_ = 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;
200 int rv = DoLoop(OK);
201 if (rv == ERR_IO_PENDING)
202 callback_ = callback;
203 return rv;
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;
214 int rv = DoLoop(OK);
215 if (rv == ERR_IO_PENDING)
216 callback_ = callback;
217 return rv;
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;
238 int rv = DoLoop(OK);
239 if (rv == ERR_IO_PENDING)
240 callback_ = callback;
241 return rv;
244 int HttpNetworkTransaction::RestartWithAuth(
245 const AuthCredentials& credentials, const CompletionCallback& callback) {
246 HttpAuth::Target target = pending_auth_target_;
247 if (target == HttpAuth::AUTH_NONE) {
248 NOTREACHED();
249 return ERR_UNEXPECTED;
251 pending_auth_target_ = HttpAuth::AUTH_NONE;
253 auth_controllers_[target]->ResetAuth(credentials);
255 DCHECK(callback_.is_null());
257 int rv = OK;
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);
266 } else {
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);
271 rv = DoLoop(OK);
274 if (rv == ERR_IO_PENDING)
275 callback_ = callback;
276 return rv;
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
288 // it first.
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;
293 return;
295 keep_alive = true;
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());
306 if (stream_.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();
316 if (!new_stream) {
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;
322 } else {
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) {
341 DCHECK(buf);
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;
368 read_buf_ = buf;
369 read_buf_len_ = buf_len;
371 next_state_ = next_state;
372 int rv = DoLoop(OK);
373 if (rv == ERR_IO_PENDING)
374 callback_ = callback;
375 return rv;
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_;
384 return true;
387 int64 HttpNetworkTransaction::GetTotalReceivedBytes() const {
388 int64 total_received_bytes = total_received_bytes_;
389 if (stream_)
390 total_received_bytes += stream_->GetTotalReceivedBytes();
391 return total_received_bytes;
394 void HttpNetworkTransaction::DoneReading() {}
396 const HttpResponseInfo* HttpNetworkTransaction::GetResponseInfo() const {
397 return &response_;
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;
416 default:
417 return LOAD_STATE_IDLE;
421 UploadProgress HttpNetworkTransaction::GetUploadProgress() const {
422 if (!stream_.get())
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))
434 return false;
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_;
441 return true;
444 void HttpNetworkTransaction::SetPriority(RequestPriority priority) {
445 priority_ = priority;
446 if (stream_request_)
447 stream_request_->SetPriority(priority);
448 if (stream_)
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);
469 return DoLoop(OK);
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());
478 if (stream_)
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();
490 OnIOComplete(OK);
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(
514 int result,
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;
552 DoCallback(OK);
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;
578 if (stream_)
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_;
606 callback_.Reset();
607 c.Run(rv);
610 void HttpNetworkTransaction::OnIOComplete(int result) {
611 int rv = DoLoop(result);
612 if (rv != ERR_IO_PENDING)
613 DoCallback(rv);
616 int HttpNetworkTransaction::DoLoop(int result) {
617 DCHECK(next_state_ != STATE_NONE);
619 int rv = result;
620 do {
621 State state = next_state_;
622 next_state_ = STATE_NONE;
623 switch (state) {
624 case STATE_NOTIFY_BEFORE_CREATE_STREAM:
625 DCHECK_EQ(OK, rv);
626 rv = DoNotifyBeforeCreateStream();
627 break;
628 case STATE_CREATE_STREAM:
629 DCHECK_EQ(OK, rv);
630 rv = DoCreateStream();
631 break;
632 case STATE_CREATE_STREAM_COMPLETE:
633 rv = DoCreateStreamComplete(rv);
634 break;
635 case STATE_INIT_STREAM:
636 DCHECK_EQ(OK, rv);
637 rv = DoInitStream();
638 break;
639 case STATE_INIT_STREAM_COMPLETE:
640 rv = DoInitStreamComplete(rv);
641 break;
642 case STATE_GENERATE_PROXY_AUTH_TOKEN:
643 DCHECK_EQ(OK, rv);
644 rv = DoGenerateProxyAuthToken();
645 break;
646 case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE:
647 rv = DoGenerateProxyAuthTokenComplete(rv);
648 break;
649 case STATE_GENERATE_SERVER_AUTH_TOKEN:
650 DCHECK_EQ(OK, rv);
651 rv = DoGenerateServerAuthToken();
652 break;
653 case STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE:
654 rv = DoGenerateServerAuthTokenComplete(rv);
655 break;
656 case STATE_INIT_REQUEST_BODY:
657 DCHECK_EQ(OK, rv);
658 rv = DoInitRequestBody();
659 break;
660 case STATE_INIT_REQUEST_BODY_COMPLETE:
661 rv = DoInitRequestBodyComplete(rv);
662 break;
663 case STATE_BUILD_REQUEST:
664 DCHECK_EQ(OK, rv);
665 net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST);
666 rv = DoBuildRequest();
667 break;
668 case STATE_BUILD_REQUEST_COMPLETE:
669 rv = DoBuildRequestComplete(rv);
670 break;
671 case STATE_SEND_REQUEST:
672 DCHECK_EQ(OK, rv);
673 rv = DoSendRequest();
674 break;
675 case STATE_SEND_REQUEST_COMPLETE:
676 rv = DoSendRequestComplete(rv);
677 net_log_.EndEventWithNetErrorCode(
678 NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST, rv);
679 break;
680 case STATE_READ_HEADERS:
681 DCHECK_EQ(OK, rv);
682 net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS);
683 rv = DoReadHeaders();
684 break;
685 case STATE_READ_HEADERS_COMPLETE:
686 rv = DoReadHeadersComplete(rv);
687 net_log_.EndEventWithNetErrorCode(
688 NetLog::TYPE_HTTP_TRANSACTION_READ_HEADERS, rv);
689 break;
690 case STATE_READ_BODY:
691 DCHECK_EQ(OK, rv);
692 net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_READ_BODY);
693 rv = DoReadBody();
694 break;
695 case STATE_READ_BODY_COMPLETE:
696 rv = DoReadBodyComplete(rv);
697 net_log_.EndEventWithNetErrorCode(
698 NetLog::TYPE_HTTP_TRANSACTION_READ_BODY, rv);
699 break;
700 case STATE_DRAIN_BODY_FOR_AUTH_RESTART:
701 DCHECK_EQ(OK, rv);
702 net_log_.BeginEvent(
703 NetLog::TYPE_HTTP_TRANSACTION_DRAIN_BODY_FOR_AUTH_RESTART);
704 rv = DoDrainBodyForAuthRestart();
705 break;
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);
710 break;
711 default:
712 NOTREACHED() << "bad state";
713 rv = ERR_FAILED;
714 break;
716 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
718 return rv;
721 int HttpNetworkTransaction::DoNotifyBeforeCreateStream() {
722 next_state_ = STATE_CREATE_STREAM;
723 bool defer = false;
724 if (!before_network_start_callback_.is_null())
725 before_network_start_callback_.Run(&defer);
726 if (!defer)
727 return OK;
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(
744 *request_,
745 priority_,
746 server_ssl_config_,
747 proxy_ssl_config_,
748 this,
749 websocket_handshake_stream_base_create_helper_,
750 net_log_));
751 } else {
752 stream_request_.reset(
753 session_->http_stream_factory()->RequestStream(
754 *request_,
755 priority_,
756 server_ssl_config_,
757 proxy_ssl_config_,
758 this,
759 net_log_));
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);
776 if (result == OK) {
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;
784 return OK;
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();
796 return result;
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) {
806 if (result == OK) {
807 next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN;
808 } else {
809 if (result < 0)
810 result = HandleIOError(result);
812 // The stream initialization failed, so this stream will never be useful.
813 if (stream_)
814 total_received_bytes_ += stream_->GetTotalReceivedBytes();
815 stream_.reset();
818 return result;
821 int HttpNetworkTransaction::DoGenerateProxyAuthToken() {
822 next_state_ = STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE;
823 if (!ShouldApplyProxyAuth())
824 return OK;
825 HttpAuth::Target target = HttpAuth::AUTH_PROXY;
826 if (!auth_controllers_[target].get())
827 auth_controllers_[target] =
828 new HttpAuthController(target,
829 AuthURL(target),
830 session_->http_auth_cache(),
831 session_->http_auth_handler_factory());
832 return auth_controllers_[target]->MaybeGenerateAuthToken(request_,
833 io_callback_,
834 net_log_);
837 int HttpNetworkTransaction::DoGenerateProxyAuthTokenComplete(int rv) {
838 DCHECK_NE(ERR_IO_PENDING, rv);
839 if (rv == OK)
840 next_state_ = STATE_GENERATE_SERVER_AUTH_TOKEN;
841 return rv;
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,
850 AuthURL(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())
857 return OK;
858 return auth_controllers_[target]->MaybeGenerateAuthToken(request_,
859 io_callback_,
860 net_log_);
863 int HttpNetworkTransaction::DoGenerateServerAuthTokenComplete(int rv) {
864 DCHECK_NE(ERR_IO_PENDING, rv);
865 if (rv == OK)
866 next_state_ = STATE_INIT_REQUEST_BODY;
867 return rv;
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,
878 "keep-alive");
879 } else {
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");
888 } else {
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(
913 &request_headers_);
914 if (ShouldApplyServerAuth() && HaveAuth(HttpAuth::AUTH_SERVER))
915 auth_controllers_[HttpAuth::AUTH_SERVER]->AddAuthorizationHeader(
916 &request_headers_);
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;
931 int rv = OK;
932 if (request_->upload_data_stream)
933 rv = request_->upload_data_stream->Init(io_callback_);
934 return rv;
937 int HttpNetworkTransaction::DoInitRequestBodyComplete(int result) {
938 if (result == OK)
939 next_state_ = STATE_BUILD_REQUEST;
940 return result;
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);
954 return OK;
957 int HttpNetworkTransaction::DoBuildRequestComplete(int result) {
958 if (result == OK)
959 next_state_ = STATE_SEND_REQUEST;
960 return result;
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();
977 if (result < 0)
978 return HandleIOError(result);
979 next_state_ = STATE_READ_HEADERS;
980 return OK;
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
994 // (-2xx).
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);
1005 if (result == OK)
1006 return 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())
1022 result = OK;
1024 if (result < 0)
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();
1040 return OK;
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);
1050 net_log_.AddEvent(
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;
1072 return OK;
1075 ProcessAlternativeServices(session_, *response_.headers.get(),
1076 HostPortPair::FromURL(request_->url));
1078 int rv = HandleAuthChallenge();
1079 if (rv != OK)
1080 return rv;
1082 if (IsSecureRequest())
1083 stream_->GetSSLInfo(&response_.ssl_info);
1085 headers_valid_ = true;
1086 return OK;
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.
1101 bool done = false;
1102 if (result <= 0) {
1103 DCHECK_NE(ERR_IO_PENDING, result);
1104 done = true;
1107 // Clean up connection if we are done.
1108 if (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.
1116 bool keep_alive =
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.
1130 read_buf_ = NULL;
1131 read_buf_len_ = 0;
1133 return result;
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;
1143 return rv;
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;
1152 if (result < 0) {
1153 // Error or closed connection while reading the socket.
1154 done = true;
1155 keep_alive = false;
1156 } else if (stream_->IsResponseBodyComplete()) {
1157 done = true;
1160 if (done) {
1161 DidDrainBodyForAuthRestart(keep_alive);
1162 } else {
1163 // Keep draining.
1164 next_state_ = STATE_DRAIN_BODY_FOR_AUTH_RESTART;
1167 return OK;
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
1185 // renegotiation.
1186 DCHECK(!stream_request_.get());
1187 total_received_bytes_ += stream_->GetTotalReceivedBytes();
1188 stream_->Close(true);
1189 stream_.reset();
1192 // The server is asking for a client certificate during the initial
1193 // handshake.
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
1198 // automatically.
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)
1203 return error;
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)
1215 return error;
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();
1229 return OK;
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_);
1238 } else {
1239 HttpServerProperties::ForceHTTP11(&proxy_ssl_config_);
1241 ResetConnectionAndRequestForResend();
1242 return OK;
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) {
1258 DCHECK(request_);
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
1264 // removed.
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)) {
1268 net_log_.AddEvent(
1269 NetLog::TYPE_SSL_CIPHER_FALLBACK,
1270 base::Bind(&NetLogSSLCipherFallbackCallback, &request_->url, error));
1271 server_ssl_config_.enable_deprecated_cipher_suites = true;
1272 ResetConnectionAndRequestForResend();
1273 return OK;
1276 bool should_fallback = false;
1277 uint16 version_max = server_ssl_config_.version_max;
1279 switch (error) {
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.
1295 version_max--;
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
1300 // done in general.
1301 should_fallback = true;
1303 break;
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
1315 // support.
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.
1320 version_max--;
1321 should_fallback = true;
1323 break;
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.
1331 version_max--;
1332 should_fallback = true;
1334 break;
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_;
1341 break;
1344 if (should_fallback) {
1345 net_log_.AddEvent(
1346 NetLog::TYPE_SSL_VERSION_FALLBACK,
1347 base::Bind(&NetLogSSLVersionFallbackCallback, &request_->url, error,
1348 server_ssl_failure_state_, server_ssl_config_.version_max,
1349 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();
1355 error = OK;
1358 return error;
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);
1370 switch (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();
1394 error = OK;
1396 break;
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();
1403 error = OK;
1404 break;
1406 return error;
1409 void HttpNetworkTransaction::ResetStateForRestart() {
1410 ResetStateForAuthRestart();
1411 if (stream_)
1412 total_received_bytes_ += stream_->GetTotalReceivedBytes();
1413 stream_.reset();
1416 void HttpNetworkTransaction::ResetStateForAuthRestart() {
1417 send_start_time_ = base::TimeTicks();
1418 send_end_time_ = base::TimeTicks();
1420 pending_auth_target_ = HttpAuth::AUTH_NONE;
1421 read_buf_ = NULL;
1422 read_buf_len_ = 0;
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)
1431 return;
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] == '.');
1437 if (is_google) {
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);
1448 if (result != OK)
1449 return;
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.
1457 FALLBACK_MAX,
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;
1465 break;
1466 case SSL_PROTOCOL_VERSION_TLS1_1:
1467 fallback = FALLBACK_TLS1_1;
1468 break;
1469 default:
1470 NOTREACHED();
1473 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback2", fallback,
1474 FALLBACK_MAX);
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.
1479 if (is_google) {
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)
1509 return true;
1510 return false;
1513 void HttpNetworkTransaction::ResetConnectionAndRequestForResend() {
1514 if (stream_.get()) {
1515 stream_->Close(true);
1516 stream_.reset();
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
1521 // the SSL tunnel.
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)
1541 return OK;
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
1549 // proxy.
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,
1555 net_log_);
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;
1564 return rv;
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 {
1573 switch (target) {
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));
1589 } else {
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;
1596 default:
1597 return GURL();
1601 bool HttpNetworkTransaction::ForWebSocketHandshake() const {
1602 return websocket_handshake_stream_base_create_helper_ &&
1603 request_->url.SchemeIsWSOrWSS();
1606 #define STATE_CASE(s) \
1607 case s: \
1608 description = base::StringPrintf("%s (0x%08X)", #s, s); \
1609 break
1611 std::string HttpNetworkTransaction::DescribeState(State state) {
1612 std::string description;
1613 switch (state) {
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);
1630 default:
1631 description = base::StringPrintf("Unknown state 0x%08X (%u)", state,
1632 state);
1633 break;
1635 return description;
1638 #undef STATE_CASE
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);
1650 } // namespace net