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_stream_factory_impl_job.h"
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/logging.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/values.h"
17 #include "build/build_config.h"
18 #include "net/base/connection_type_histograms.h"
19 #include "net/base/net_log.h"
20 #include "net/base/net_util.h"
21 #include "net/http/http_basic_stream.h"
22 #include "net/http/http_network_session.h"
23 #include "net/http/http_proxy_client_socket.h"
24 #include "net/http/http_proxy_client_socket_pool.h"
25 #include "net/http/http_request_info.h"
26 #include "net/http/http_server_properties.h"
27 #include "net/http/http_stream_factory.h"
28 #include "net/http/http_stream_factory_impl_request.h"
29 #include "net/quic/quic_http_stream.h"
30 #include "net/socket/client_socket_handle.h"
31 #include "net/socket/client_socket_pool.h"
32 #include "net/socket/client_socket_pool_manager.h"
33 #include "net/socket/socks_client_socket_pool.h"
34 #include "net/socket/ssl_client_socket.h"
35 #include "net/socket/ssl_client_socket_pool.h"
36 #include "net/spdy/spdy_http_stream.h"
37 #include "net/spdy/spdy_session.h"
38 #include "net/spdy/spdy_session_pool.h"
39 #include "net/ssl/ssl_cert_request_info.h"
43 // Returns parameters associated with the start of a HTTP stream job.
44 base::Value
* NetLogHttpStreamJobCallback(const GURL
* original_url
,
46 RequestPriority priority
,
47 NetLog::LogLevel
/* log_level */) {
48 base::DictionaryValue
* dict
= new base::DictionaryValue();
49 dict
->SetString("original_url", original_url
->GetOrigin().spec());
50 dict
->SetString("url", url
->GetOrigin().spec());
51 dict
->SetString("priority", RequestPriorityToString(priority
));
55 // Returns parameters associated with the Proto (with NPN negotiation) of a HTTP
57 base::Value
* NetLogHttpStreamProtoCallback(
58 const SSLClientSocket::NextProtoStatus status
,
59 const std::string
* proto
,
60 NetLog::LogLevel
/* log_level */) {
61 base::DictionaryValue
* dict
= new base::DictionaryValue();
63 dict
->SetString("next_proto_status",
64 SSLClientSocket::NextProtoStatusToString(status
));
65 dict
->SetString("proto", *proto
);
69 HttpStreamFactoryImpl::Job::Job(HttpStreamFactoryImpl
* stream_factory
,
70 HttpNetworkSession
* session
,
71 const HttpRequestInfo
& request_info
,
72 RequestPriority priority
,
73 const SSLConfig
& server_ssl_config
,
74 const SSLConfig
& proxy_ssl_config
,
77 request_info_(request_info
),
79 server_ssl_config_(server_ssl_config
),
80 proxy_ssl_config_(proxy_ssl_config
),
81 net_log_(BoundNetLog::Make(net_log
, NetLog::SOURCE_HTTP_STREAM_JOB
)),
82 io_callback_(base::Bind(&Job::OnIOComplete
, base::Unretained(this))),
83 connection_(new ClientSocketHandle
),
85 stream_factory_(stream_factory
),
86 next_state_(STATE_NONE
),
93 quic_request_(session_
->quic_stream_factory()),
94 using_existing_quic_session_(false),
95 spdy_certificate_error_(OK
),
96 establishing_tunnel_(false),
97 was_npn_negotiated_(false),
98 protocol_negotiated_(kProtoUnknown
),
100 spdy_session_direct_(false),
101 job_status_(STATUS_RUNNING
),
102 other_job_status_(STATUS_RUNNING
),
104 DCHECK(stream_factory
);
108 HttpStreamFactoryImpl::Job::~Job() {
109 net_log_
.EndEvent(NetLog::TYPE_HTTP_STREAM_JOB
);
111 // When we're in a partially constructed state, waiting for the user to
112 // provide certificate handling information or authentication, we can't reuse
113 // this stream at all.
114 if (next_state_
== STATE_WAITING_USER_ACTION
) {
115 connection_
->socket()->Disconnect();
120 session_
->proxy_service()->CancelPacRequest(pac_request_
);
122 // The stream could be in a partial state. It is not reusable.
123 if (stream_
.get() && next_state_
!= STATE_DONE
)
124 stream_
->Close(true /* not reusable */);
127 void HttpStreamFactoryImpl::Job::Start(Request
* request
) {
133 int HttpStreamFactoryImpl::Job::Preconnect(int num_streams
) {
134 DCHECK_GT(num_streams
, 0);
135 HostPortPair origin_server
=
136 HostPortPair(request_info_
.url
.HostNoBrackets(),
137 request_info_
.url
.EffectiveIntPort());
138 base::WeakPtr
<HttpServerProperties
> http_server_properties
=
139 session_
->http_server_properties();
140 if (http_server_properties
&&
141 http_server_properties
->SupportsSpdy(origin_server
)) {
144 num_streams_
= num_streams
;
146 return StartInternal();
149 int HttpStreamFactoryImpl::Job::RestartTunnelWithProxyAuth(
150 const AuthCredentials
& credentials
) {
151 DCHECK(establishing_tunnel_
);
152 next_state_
= STATE_RESTART_TUNNEL_AUTH
;
157 LoadState
HttpStreamFactoryImpl::Job::GetLoadState() const {
158 switch (next_state_
) {
159 case STATE_RESOLVE_PROXY_COMPLETE
:
160 return session_
->proxy_service()->GetLoadState(pac_request_
);
161 case STATE_INIT_CONNECTION_COMPLETE
:
162 case STATE_CREATE_STREAM_COMPLETE
:
163 return using_quic_
? LOAD_STATE_CONNECTING
: connection_
->GetLoadState();
165 return LOAD_STATE_IDLE
;
169 void HttpStreamFactoryImpl::Job::MarkAsAlternate(
170 const GURL
& original_url
,
171 AlternateProtocolInfo alternate
) {
172 DCHECK(!original_url_
.get());
173 original_url_
.reset(new GURL(original_url
));
174 if (alternate
.protocol
== QUIC
) {
175 DCHECK(session_
->params().enable_quic
);
180 void HttpStreamFactoryImpl::Job::WaitFor(Job
* job
) {
181 DCHECK_EQ(STATE_NONE
, next_state_
);
182 DCHECK_EQ(STATE_NONE
, job
->next_state_
);
183 DCHECK(!blocking_job_
);
184 DCHECK(!job
->waiting_job_
);
186 job
->waiting_job_
= this;
189 void HttpStreamFactoryImpl::Job::Resume(Job
* job
) {
190 DCHECK_EQ(blocking_job_
, job
);
191 blocking_job_
= NULL
;
193 // We know we're blocked if the next_state_ is STATE_WAIT_FOR_JOB_COMPLETE.
195 if (next_state_
== STATE_WAIT_FOR_JOB_COMPLETE
) {
196 base::MessageLoop::current()->PostTask(
198 base::Bind(&HttpStreamFactoryImpl::Job::OnIOComplete
,
199 ptr_factory_
.GetWeakPtr(), OK
));
203 void HttpStreamFactoryImpl::Job::Orphan(const Request
* request
) {
204 DCHECK_EQ(request_
, request
);
207 // We've been orphaned, but there's a job we're blocked on. Don't bother
208 // racing, just cancel ourself.
209 DCHECK(blocking_job_
->waiting_job_
);
210 blocking_job_
->waiting_job_
= NULL
;
211 blocking_job_
= NULL
;
212 if (stream_factory_
->for_websockets_
&&
213 connection_
&& connection_
->socket()) {
214 connection_
->socket()->Disconnect();
216 stream_factory_
->OnOrphanedJobComplete(this);
217 } else if (stream_factory_
->for_websockets_
) {
218 // We cancel this job because a WebSocketHandshakeStream can't be created
219 // without a WebSocketHandshakeStreamBase::CreateHelper which is stored in
220 // the Request class and isn't accessible from this job.
221 if (connection_
&& connection_
->socket()) {
222 connection_
->socket()->Disconnect();
224 stream_factory_
->OnOrphanedJobComplete(this);
228 void HttpStreamFactoryImpl::Job::SetPriority(RequestPriority priority
) {
229 priority_
= priority
;
230 // TODO(akalin): Propagate this to |connection_| and maybe the
234 bool HttpStreamFactoryImpl::Job::was_npn_negotiated() const {
235 return was_npn_negotiated_
;
238 NextProto
HttpStreamFactoryImpl::Job::protocol_negotiated() const {
239 return protocol_negotiated_
;
242 bool HttpStreamFactoryImpl::Job::using_spdy() const {
246 const SSLConfig
& HttpStreamFactoryImpl::Job::server_ssl_config() const {
247 return server_ssl_config_
;
250 const SSLConfig
& HttpStreamFactoryImpl::Job::proxy_ssl_config() const {
251 return proxy_ssl_config_
;
254 const ProxyInfo
& HttpStreamFactoryImpl::Job::proxy_info() const {
258 void HttpStreamFactoryImpl::Job::GetSSLInfo() {
260 DCHECK(!establishing_tunnel_
);
261 DCHECK(connection_
.get() && connection_
->socket());
262 SSLClientSocket
* ssl_socket
=
263 static_cast<SSLClientSocket
*>(connection_
->socket());
264 ssl_socket
->GetSSLInfo(&ssl_info_
);
267 SpdySessionKey
HttpStreamFactoryImpl::Job::GetSpdySessionKey() const {
268 // In the case that we're using an HTTPS proxy for an HTTP url,
269 // we look for a SPDY session *to* the proxy, instead of to the
271 PrivacyMode privacy_mode
= request_info_
.privacy_mode
;
272 if (IsHttpsProxyAndHttpUrl()) {
273 return SpdySessionKey(proxy_info_
.proxy_server().host_port_pair(),
274 ProxyServer::Direct(),
277 return SpdySessionKey(origin_
,
278 proxy_info_
.proxy_server(),
283 bool HttpStreamFactoryImpl::Job::CanUseExistingSpdySession() const {
284 // We need to make sure that if a spdy session was created for
285 // https://somehost/ that we don't use that session for http://somehost:443/.
286 // The only time we can use an existing session is if the request URL is
287 // https (the normal case) or if we're connection to a SPDY proxy, or
288 // if we're running with force_spdy_always_. crbug.com/133176
289 // TODO(ricea): Add "wss" back to this list when SPDY WebSocket support is
291 return request_info_
.url
.SchemeIs("https") ||
292 proxy_info_
.proxy_server().is_https() ||
293 session_
->params().force_spdy_always
;
296 void HttpStreamFactoryImpl::Job::OnStreamReadyCallback() {
297 DCHECK(stream_
.get());
298 DCHECK(!IsPreconnecting());
299 DCHECK(!stream_factory_
->for_websockets_
);
301 stream_factory_
->OnOrphanedJobComplete(this);
303 request_
->Complete(was_npn_negotiated(),
304 protocol_negotiated(),
307 request_
->OnStreamReady(this, server_ssl_config_
, proxy_info_
,
310 // |this| may be deleted after this call.
313 void HttpStreamFactoryImpl::Job::OnWebSocketHandshakeStreamReadyCallback() {
314 DCHECK(websocket_stream_
);
315 DCHECK(!IsPreconnecting());
316 DCHECK(stream_factory_
->for_websockets_
);
317 // An orphaned WebSocket job will be closed immediately and
319 DCHECK(!IsOrphaned());
320 request_
->Complete(was_npn_negotiated(),
321 protocol_negotiated(),
324 request_
->OnWebSocketHandshakeStreamReady(this,
327 websocket_stream_
.release());
328 // |this| may be deleted after this call.
331 void HttpStreamFactoryImpl::Job::OnNewSpdySessionReadyCallback() {
332 DCHECK(stream_
.get());
333 DCHECK(!IsPreconnecting());
334 DCHECK(using_spdy());
335 // Note: an event loop iteration has passed, so |new_spdy_session_| may be
336 // NULL at this point if the SpdySession closed immediately after creation.
337 base::WeakPtr
<SpdySession
> spdy_session
= new_spdy_session_
;
338 new_spdy_session_
.reset();
340 // TODO(jgraettinger): Notify the factory, and let that notify |request_|,
341 // rather than notifying |request_| directly.
344 stream_factory_
->OnNewSpdySessionReady(
345 spdy_session
, spdy_session_direct_
, server_ssl_config_
, proxy_info_
,
346 was_npn_negotiated(), protocol_negotiated(), using_spdy(), net_log_
);
348 stream_factory_
->OnOrphanedJobComplete(this);
350 request_
->OnNewSpdySessionReady(
351 this, stream_
.Pass(), spdy_session
, spdy_session_direct_
);
353 // |this| may be deleted after this call.
356 void HttpStreamFactoryImpl::Job::OnStreamFailedCallback(int result
) {
357 DCHECK(!IsPreconnecting());
359 stream_factory_
->OnOrphanedJobComplete(this);
361 request_
->OnStreamFailed(this, result
, server_ssl_config_
);
362 // |this| may be deleted after this call.
365 void HttpStreamFactoryImpl::Job::OnCertificateErrorCallback(
366 int result
, const SSLInfo
& ssl_info
) {
367 DCHECK(!IsPreconnecting());
369 stream_factory_
->OnOrphanedJobComplete(this);
371 request_
->OnCertificateError(this, result
, server_ssl_config_
, ssl_info
);
372 // |this| may be deleted after this call.
375 void HttpStreamFactoryImpl::Job::OnNeedsProxyAuthCallback(
376 const HttpResponseInfo
& response
,
377 HttpAuthController
* auth_controller
) {
378 DCHECK(!IsPreconnecting());
380 stream_factory_
->OnOrphanedJobComplete(this);
382 request_
->OnNeedsProxyAuth(
383 this, response
, server_ssl_config_
, proxy_info_
, auth_controller
);
384 // |this| may be deleted after this call.
387 void HttpStreamFactoryImpl::Job::OnNeedsClientAuthCallback(
388 SSLCertRequestInfo
* cert_info
) {
389 DCHECK(!IsPreconnecting());
391 stream_factory_
->OnOrphanedJobComplete(this);
393 request_
->OnNeedsClientAuth(this, server_ssl_config_
, cert_info
);
394 // |this| may be deleted after this call.
397 void HttpStreamFactoryImpl::Job::OnHttpsProxyTunnelResponseCallback(
398 const HttpResponseInfo
& response_info
,
399 HttpStream
* stream
) {
400 DCHECK(!IsPreconnecting());
402 stream_factory_
->OnOrphanedJobComplete(this);
404 request_
->OnHttpsProxyTunnelResponse(
405 this, response_info
, server_ssl_config_
, proxy_info_
, stream
);
406 // |this| may be deleted after this call.
409 void HttpStreamFactoryImpl::Job::OnPreconnectsComplete() {
411 if (new_spdy_session_
.get()) {
412 stream_factory_
->OnNewSpdySessionReady(new_spdy_session_
,
413 spdy_session_direct_
,
416 was_npn_negotiated(),
417 protocol_negotiated(),
421 stream_factory_
->OnPreconnectsComplete(this);
422 // |this| may be deleted after this call.
426 int HttpStreamFactoryImpl::Job::OnHostResolution(
427 SpdySessionPool
* spdy_session_pool
,
428 const SpdySessionKey
& spdy_session_key
,
429 const AddressList
& addresses
,
430 const BoundNetLog
& net_log
) {
431 // It is OK to dereference spdy_session_pool, because the
432 // ClientSocketPoolManager will be destroyed in the same callback that
433 // destroys the SpdySessionPool.
435 spdy_session_pool
->FindAvailableSession(spdy_session_key
, net_log
) ?
436 ERR_SPDY_SESSION_ALREADY_EXISTS
: OK
;
439 void HttpStreamFactoryImpl::Job::OnIOComplete(int result
) {
443 int HttpStreamFactoryImpl::Job::RunLoop(int result
) {
444 result
= DoLoop(result
);
446 if (result
== ERR_IO_PENDING
)
449 // If there was an error, we should have already resumed the |waiting_job_|,
451 DCHECK(result
== OK
|| waiting_job_
== NULL
);
453 if (IsPreconnecting()) {
454 base::MessageLoop::current()->PostTask(
456 base::Bind(&HttpStreamFactoryImpl::Job::OnPreconnectsComplete
,
457 ptr_factory_
.GetWeakPtr()));
458 return ERR_IO_PENDING
;
461 if (IsCertificateError(result
)) {
462 // Retrieve SSL information from the socket.
465 next_state_
= STATE_WAITING_USER_ACTION
;
466 base::MessageLoop::current()->PostTask(
468 base::Bind(&HttpStreamFactoryImpl::Job::OnCertificateErrorCallback
,
469 ptr_factory_
.GetWeakPtr(), result
, ssl_info_
));
470 return ERR_IO_PENDING
;
474 case ERR_PROXY_AUTH_REQUESTED
: {
475 UMA_HISTOGRAM_BOOLEAN("Net.ProxyAuthRequested.HasConnection",
476 connection_
.get() != NULL
);
477 if (!connection_
.get())
478 return ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION
;
479 CHECK(connection_
->socket());
480 CHECK(establishing_tunnel_
);
482 next_state_
= STATE_WAITING_USER_ACTION
;
483 ProxyClientSocket
* proxy_socket
=
484 static_cast<ProxyClientSocket
*>(connection_
->socket());
485 base::MessageLoop::current()->PostTask(
487 base::Bind(&Job::OnNeedsProxyAuthCallback
, ptr_factory_
.GetWeakPtr(),
488 *proxy_socket
->GetConnectResponseInfo(),
489 proxy_socket
->GetAuthController()));
490 return ERR_IO_PENDING
;
493 case ERR_SSL_CLIENT_AUTH_CERT_NEEDED
:
494 base::MessageLoop::current()->PostTask(
496 base::Bind(&Job::OnNeedsClientAuthCallback
, ptr_factory_
.GetWeakPtr(),
497 connection_
->ssl_error_response_info().cert_request_info
));
498 return ERR_IO_PENDING
;
500 case ERR_HTTPS_PROXY_TUNNEL_RESPONSE
: {
501 DCHECK(connection_
.get());
502 DCHECK(connection_
->socket());
503 DCHECK(establishing_tunnel_
);
505 ProxyClientSocket
* proxy_socket
=
506 static_cast<ProxyClientSocket
*>(connection_
->socket());
507 base::MessageLoop::current()->PostTask(
509 base::Bind(&Job::OnHttpsProxyTunnelResponseCallback
,
510 ptr_factory_
.GetWeakPtr(),
511 *proxy_socket
->GetConnectResponseInfo(),
512 proxy_socket
->CreateConnectResponseStream()));
513 return ERR_IO_PENDING
;
517 job_status_
= STATUS_SUCCEEDED
;
518 MaybeMarkAlternateProtocolBroken();
519 next_state_
= STATE_DONE
;
520 if (new_spdy_session_
.get()) {
521 base::MessageLoop::current()->PostTask(
523 base::Bind(&Job::OnNewSpdySessionReadyCallback
,
524 ptr_factory_
.GetWeakPtr()));
525 } else if (stream_factory_
->for_websockets_
) {
526 DCHECK(websocket_stream_
);
527 base::MessageLoop::current()->PostTask(
529 base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback
,
530 ptr_factory_
.GetWeakPtr()));
532 DCHECK(stream_
.get());
533 base::MessageLoop::current()->PostTask(
535 base::Bind(&Job::OnStreamReadyCallback
, ptr_factory_
.GetWeakPtr()));
537 return ERR_IO_PENDING
;
540 if (job_status_
!= STATUS_BROKEN
) {
541 DCHECK_EQ(STATUS_RUNNING
, job_status_
);
542 job_status_
= STATUS_FAILED
;
543 MaybeMarkAlternateProtocolBroken();
545 base::MessageLoop::current()->PostTask(
547 base::Bind(&Job::OnStreamFailedCallback
, ptr_factory_
.GetWeakPtr(),
549 return ERR_IO_PENDING
;
553 int HttpStreamFactoryImpl::Job::DoLoop(int result
) {
554 DCHECK_NE(next_state_
, STATE_NONE
);
557 State state
= next_state_
;
558 next_state_
= STATE_NONE
;
564 case STATE_RESOLVE_PROXY
:
566 rv
= DoResolveProxy();
568 case STATE_RESOLVE_PROXY_COMPLETE
:
569 rv
= DoResolveProxyComplete(rv
);
571 case STATE_WAIT_FOR_JOB
:
575 case STATE_WAIT_FOR_JOB_COMPLETE
:
576 rv
= DoWaitForJobComplete(rv
);
578 case STATE_INIT_CONNECTION
:
580 rv
= DoInitConnection();
582 case STATE_INIT_CONNECTION_COMPLETE
:
583 rv
= DoInitConnectionComplete(rv
);
585 case STATE_WAITING_USER_ACTION
:
586 rv
= DoWaitingUserAction(rv
);
588 case STATE_RESTART_TUNNEL_AUTH
:
590 rv
= DoRestartTunnelAuth();
592 case STATE_RESTART_TUNNEL_AUTH_COMPLETE
:
593 rv
= DoRestartTunnelAuthComplete(rv
);
595 case STATE_CREATE_STREAM
:
597 rv
= DoCreateStream();
599 case STATE_CREATE_STREAM_COMPLETE
:
600 rv
= DoCreateStreamComplete(rv
);
603 NOTREACHED() << "bad state";
607 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
611 int HttpStreamFactoryImpl::Job::StartInternal() {
612 CHECK_EQ(STATE_NONE
, next_state_
);
613 next_state_
= STATE_START
;
614 int rv
= RunLoop(OK
);
615 DCHECK_EQ(ERR_IO_PENDING
, rv
);
619 int HttpStreamFactoryImpl::Job::DoStart() {
620 int port
= request_info_
.url
.EffectiveIntPort();
621 origin_
= HostPortPair(request_info_
.url
.HostNoBrackets(), port
);
622 origin_url_
= stream_factory_
->ApplyHostMappingRules(
623 request_info_
.url
, &origin_
);
625 net_log_
.BeginEvent(NetLog::TYPE_HTTP_STREAM_JOB
,
626 base::Bind(&NetLogHttpStreamJobCallback
,
627 &request_info_
.url
, &origin_url_
,
630 // Don't connect to restricted ports.
631 bool is_port_allowed
= IsPortAllowedByDefault(port
);
632 if (request_info_
.url
.SchemeIs("ftp")) {
633 // Never share connection with other jobs for FTP requests.
634 DCHECK(!waiting_job_
);
636 is_port_allowed
= IsPortAllowedByFtp(port
);
638 if (!is_port_allowed
&& !IsPortAllowedByOverride(port
)) {
640 waiting_job_
->Resume(this);
643 return ERR_UNSAFE_PORT
;
646 next_state_
= STATE_RESOLVE_PROXY
;
650 int HttpStreamFactoryImpl::Job::DoResolveProxy() {
651 DCHECK(!pac_request_
);
654 next_state_
= STATE_RESOLVE_PROXY_COMPLETE
;
656 if (request_info_
.load_flags
& LOAD_BYPASS_PROXY
) {
657 proxy_info_
.UseDirect();
661 return session_
->proxy_service()->ResolveProxy(
662 request_info_
.url
, request_info_
.load_flags
, &proxy_info_
, io_callback_
,
663 &pac_request_
, session_
->network_delegate(), net_log_
);
666 int HttpStreamFactoryImpl::Job::DoResolveProxyComplete(int result
) {
670 // Remove unsupported proxies from the list.
671 proxy_info_
.RemoveProxiesWithoutScheme(
672 ProxyServer::SCHEME_DIRECT
| ProxyServer::SCHEME_QUIC
|
673 ProxyServer::SCHEME_HTTP
| ProxyServer::SCHEME_HTTPS
|
674 ProxyServer::SCHEME_SOCKS4
| ProxyServer::SCHEME_SOCKS5
);
676 if (proxy_info_
.is_empty()) {
677 // No proxies/direct to choose from. This happens when we don't support
678 // any of the proxies in the returned list.
679 result
= ERR_NO_SUPPORTED_PROXIES
;
680 } else if (using_quic_
&&
681 (!proxy_info_
.is_quic() && !proxy_info_
.is_direct())) {
682 // QUIC can not be spoken to non-QUIC proxies. This error should not be
683 // user visible, because the non-alternate job should be resumed.
684 result
= ERR_NO_SUPPORTED_PROXIES
;
690 waiting_job_
->Resume(this);
697 next_state_
= STATE_WAIT_FOR_JOB
;
699 next_state_
= STATE_INIT_CONNECTION
;
703 bool HttpStreamFactoryImpl::Job::ShouldForceSpdySSL() const {
704 bool rv
= session_
->params().force_spdy_always
&&
705 session_
->params().force_spdy_over_ssl
;
706 return rv
&& !session_
->HasSpdyExclusion(origin_
);
709 bool HttpStreamFactoryImpl::Job::ShouldForceSpdyWithoutSSL() const {
710 bool rv
= session_
->params().force_spdy_always
&&
711 !session_
->params().force_spdy_over_ssl
;
712 return rv
&& !session_
->HasSpdyExclusion(origin_
);
715 bool HttpStreamFactoryImpl::Job::ShouldForceQuic() const {
716 return session_
->params().enable_quic
&&
717 session_
->params().origin_to_force_quic_on
.Equals(origin_
) &&
718 proxy_info_
.is_direct();
721 int HttpStreamFactoryImpl::Job::DoWaitForJob() {
722 DCHECK(blocking_job_
);
723 next_state_
= STATE_WAIT_FOR_JOB_COMPLETE
;
724 return ERR_IO_PENDING
;
727 int HttpStreamFactoryImpl::Job::DoWaitForJobComplete(int result
) {
728 DCHECK(!blocking_job_
);
729 DCHECK_EQ(OK
, result
);
730 next_state_
= STATE_INIT_CONNECTION
;
734 int HttpStreamFactoryImpl::Job::DoInitConnection() {
735 DCHECK(!blocking_job_
);
736 DCHECK(!connection_
->is_initialized());
737 DCHECK(proxy_info_
.proxy_server().is_valid());
738 next_state_
= STATE_INIT_CONNECTION_COMPLETE
;
740 using_ssl_
= request_info_
.url
.SchemeIs("https") ||
741 request_info_
.url
.SchemeIs("wss") || ShouldForceSpdySSL();
744 if (ShouldForceQuic())
747 if (proxy_info_
.is_quic())
751 DCHECK(session_
->params().enable_quic
);
752 if (proxy_info_
.is_quic() && !request_info_
.url
.SchemeIs("http")) {
754 // TODO(rch): support QUIC proxies for HTTPS urls.
755 return ERR_NOT_IMPLEMENTED
;
757 HostPortPair destination
= proxy_info_
.is_quic() ?
758 proxy_info_
.proxy_server().host_port_pair() : origin_
;
759 next_state_
= STATE_INIT_CONNECTION_COMPLETE
;
760 bool secure_quic
= using_ssl_
|| proxy_info_
.is_quic();
761 int rv
= quic_request_
.Request(
762 destination
, secure_quic
, request_info_
.privacy_mode
,
763 request_info_
.method
, net_log_
, io_callback_
);
765 using_existing_quic_session_
= true;
767 // OK, there's no available QUIC session. Let |waiting_job_| resume
770 waiting_job_
->Resume(this);
777 // Check first if we have a spdy session for this group. If so, then go
778 // straight to using that.
779 SpdySessionKey spdy_session_key
= GetSpdySessionKey();
780 base::WeakPtr
<SpdySession
> spdy_session
=
781 session_
->spdy_session_pool()->FindAvailableSession(
782 spdy_session_key
, net_log_
);
783 if (spdy_session
&& CanUseExistingSpdySession()) {
784 // If we're preconnecting, but we already have a SpdySession, we don't
785 // actually need to preconnect any sockets, so we're done.
786 if (IsPreconnecting())
789 next_state_
= STATE_CREATE_STREAM
;
790 existing_spdy_session_
= spdy_session
;
792 } else if (request_
&& !request_
->HasSpdySessionKey() &&
793 (using_ssl_
|| ShouldForceSpdyWithoutSSL())) {
794 // Update the spdy session key for the request that launched this job.
795 request_
->SetSpdySessionKey(spdy_session_key
);
798 // OK, there's no available SPDY session. Let |waiting_job_| resume if it's
802 waiting_job_
->Resume(this);
806 if (proxy_info_
.is_http() || proxy_info_
.is_https())
807 establishing_tunnel_
= using_ssl_
;
809 bool want_spdy_over_npn
= original_url_
!= NULL
;
811 if (proxy_info_
.is_https()) {
812 InitSSLConfig(proxy_info_
.proxy_server().host_port_pair(),
814 true /* is a proxy server */);
815 // Disable revocation checking for HTTPS proxies since the revocation
816 // requests are probably going to need to go through the proxy too.
817 proxy_ssl_config_
.rev_checking_enabled
= false;
820 InitSSLConfig(origin_
, &server_ssl_config_
,
821 false /* not a proxy server */);
824 if (IsPreconnecting()) {
825 DCHECK(!stream_factory_
->for_websockets_
);
826 return PreconnectSocketsForHttpRequest(
828 request_info_
.extra_headers
,
829 request_info_
.load_flags
,
833 ShouldForceSpdySSL(),
837 request_info_
.privacy_mode
,
842 // If we can't use a SPDY session, don't both checking for one after
843 // the hostname is resolved.
844 OnHostResolutionCallback resolution_callback
= CanUseExistingSpdySession() ?
845 base::Bind(&Job::OnHostResolution
, session_
->spdy_session_pool(),
846 GetSpdySessionKey()) :
847 OnHostResolutionCallback();
848 if (stream_factory_
->for_websockets_
) {
849 // TODO(ricea): Re-enable NPN when WebSockets over SPDY is supported.
850 SSLConfig websocket_server_ssl_config
= server_ssl_config_
;
851 websocket_server_ssl_config
.next_protos
.clear();
852 return InitSocketHandleForWebSocketRequest(
853 origin_url_
, request_info_
.extra_headers
, request_info_
.load_flags
,
854 priority_
, session_
, proxy_info_
, ShouldForceSpdySSL(),
855 want_spdy_over_npn
, websocket_server_ssl_config
, proxy_ssl_config_
,
856 request_info_
.privacy_mode
, net_log_
,
857 connection_
.get(), resolution_callback
, io_callback_
);
860 return InitSocketHandleForHttpRequest(
861 origin_url_
, request_info_
.extra_headers
, request_info_
.load_flags
,
862 priority_
, session_
, proxy_info_
, ShouldForceSpdySSL(),
863 want_spdy_over_npn
, server_ssl_config_
, proxy_ssl_config_
,
864 request_info_
.privacy_mode
, net_log_
,
865 connection_
.get(), resolution_callback
, io_callback_
);
868 int HttpStreamFactoryImpl::Job::DoInitConnectionComplete(int result
) {
869 if (IsPreconnecting()) {
872 DCHECK_EQ(OK
, result
);
876 if (result
== ERR_SPDY_SESSION_ALREADY_EXISTS
) {
877 // We found a SPDY connection after resolving the host. This is
878 // probably an IP pooled connection.
879 SpdySessionKey spdy_session_key
= GetSpdySessionKey();
880 existing_spdy_session_
=
881 session_
->spdy_session_pool()->FindAvailableSession(
882 spdy_session_key
, net_log_
);
883 if (existing_spdy_session_
) {
885 next_state_
= STATE_CREATE_STREAM
;
887 // It is possible that the spdy session no longer exists.
888 ReturnToStateInitConnection(true /* close connection */);
893 // TODO(willchan): Make this a bit more exact. Maybe there are recoverable
894 // errors, such as ignoring certificate errors for Alternate-Protocol.
895 if (result
< 0 && waiting_job_
) {
896 waiting_job_
->Resume(this);
900 // |result| may be the result of any of the stacked pools. The following
901 // logic is used when determining how to interpret an error.
903 // and connection_->socket() != NULL, then the SSL handshake ran and it
904 // is a potentially recoverable error.
905 // and connection_->socket == NULL and connection_->is_ssl_error() is true,
906 // then the SSL handshake ran with an unrecoverable error.
907 // otherwise, the error came from one of the other pools.
908 bool ssl_started
= using_ssl_
&& (result
== OK
|| connection_
->socket() ||
909 connection_
->is_ssl_error());
911 if (ssl_started
&& (result
== OK
|| IsCertificateError(result
))) {
912 if (using_quic_
&& result
== OK
) {
913 was_npn_negotiated_
= true;
914 NextProto protocol_negotiated
=
915 SSLClientSocket::NextProtoFromString("quic/1+spdy/3");
916 protocol_negotiated_
= protocol_negotiated
;
918 SSLClientSocket
* ssl_socket
=
919 static_cast<SSLClientSocket
*>(connection_
->socket());
920 if (ssl_socket
->WasNpnNegotiated()) {
921 was_npn_negotiated_
= true;
923 SSLClientSocket::NextProtoStatus status
=
924 ssl_socket
->GetNextProto(&proto
);
925 NextProto protocol_negotiated
=
926 SSLClientSocket::NextProtoFromString(proto
);
927 protocol_negotiated_
= protocol_negotiated
;
929 NetLog::TYPE_HTTP_STREAM_REQUEST_PROTO
,
930 base::Bind(&NetLogHttpStreamProtoCallback
,
932 if (ssl_socket
->was_spdy_negotiated())
935 if (ShouldForceSpdySSL())
938 } else if (proxy_info_
.is_https() && connection_
->socket() &&
940 ProxyClientSocket
* proxy_socket
=
941 static_cast<ProxyClientSocket
*>(connection_
->socket());
942 if (proxy_socket
->IsUsingSpdy()) {
943 was_npn_negotiated_
= true;
944 protocol_negotiated_
= proxy_socket
->GetProtocolNegotiated();
949 // We may be using spdy without SSL
950 if (ShouldForceSpdyWithoutSSL())
953 if (result
== ERR_PROXY_AUTH_REQUESTED
||
954 result
== ERR_HTTPS_PROXY_TUNNEL_RESPONSE
) {
955 DCHECK(!ssl_started
);
956 // Other state (i.e. |using_ssl_|) suggests that |connection_| will have an
957 // SSL socket, but there was an error before that could happen. This
958 // puts the in progress HttpProxy socket into |connection_| in order to
959 // complete the auth (or read the response body). The tunnel restart code
960 // is careful to remove it before returning control to the rest of this
962 connection_
.reset(connection_
->release_pending_http_proxy_connection());
966 if (!ssl_started
&& result
< 0 && original_url_
.get()) {
967 job_status_
= STATUS_BROKEN
;
968 MaybeMarkAlternateProtocolBroken();
974 job_status_
= STATUS_BROKEN
;
975 MaybeMarkAlternateProtocolBroken();
978 stream_
= quic_request_
.ReleaseStream();
979 next_state_
= STATE_NONE
;
983 if (result
< 0 && !ssl_started
)
984 return ReconsiderProxyAfterError(result
);
985 establishing_tunnel_
= false;
987 if (connection_
->socket()) {
988 LogHttpConnectedMetrics(*connection_
);
990 // We officially have a new connection. Record the type.
991 if (!connection_
->is_reused()) {
992 ConnectionType type
= using_spdy_
? CONNECTION_SPDY
: CONNECTION_HTTP
;
993 UpdateConnectionTypeHistograms(type
);
997 // Handle SSL errors below.
1000 if (IsCertificateError(result
)) {
1001 if (using_spdy_
&& original_url_
.get() &&
1002 original_url_
->SchemeIs("http")) {
1003 // We ignore certificate errors for http over spdy.
1004 spdy_certificate_error_
= result
;
1007 result
= HandleCertificateError(result
);
1008 if (result
== OK
&& !connection_
->socket()->IsConnectedAndIdle()) {
1009 ReturnToStateInitConnection(true /* close connection */);
1018 next_state_
= STATE_CREATE_STREAM
;
1022 int HttpStreamFactoryImpl::Job::DoWaitingUserAction(int result
) {
1023 // This state indicates that the stream request is in a partially
1024 // completed state, and we've called back to the delegate for more
1027 // We're always waiting here for the delegate to call us back.
1028 return ERR_IO_PENDING
;
1031 int HttpStreamFactoryImpl::Job::SetSpdyHttpStream(
1032 base::WeakPtr
<SpdySession
> session
, bool direct
) {
1033 // TODO(ricea): Restore the code for WebSockets over SPDY once it's
1035 if (stream_factory_
->for_websockets_
)
1036 return ERR_NOT_IMPLEMENTED
;
1038 // TODO(willchan): Delete this code, because eventually, the
1039 // HttpStreamFactoryImpl will be creating all the SpdyHttpStreams, since it
1040 // will know when SpdySessions become available.
1042 bool use_relative_url
= direct
|| request_info_
.url
.SchemeIs("https");
1043 stream_
.reset(new SpdyHttpStream(session
, use_relative_url
));
1047 int HttpStreamFactoryImpl::Job::DoCreateStream() {
1048 DCHECK(connection_
->socket() || existing_spdy_session_
.get() || using_quic_
);
1050 next_state_
= STATE_CREATE_STREAM_COMPLETE
;
1052 // We only set the socket motivation if we're the first to use
1053 // this socket. Is there a race for two SPDY requests? We really
1054 // need to plumb this through to the connect level.
1055 if (connection_
->socket() && !connection_
->is_reused())
1056 SetSocketMotivation();
1059 // We may get ftp scheme when fetching ftp resources through proxy.
1060 bool using_proxy
= (proxy_info_
.is_http() || proxy_info_
.is_https()) &&
1061 (request_info_
.url
.SchemeIs("http") ||
1062 request_info_
.url
.SchemeIs("ftp"));
1063 if (stream_factory_
->for_websockets_
) {
1065 DCHECK(request_
->websocket_handshake_stream_create_helper());
1066 websocket_stream_
.reset(
1067 request_
->websocket_handshake_stream_create_helper()
1068 ->CreateBasicStream(connection_
.Pass(), using_proxy
));
1070 stream_
.reset(new HttpBasicStream(connection_
.release(), using_proxy
));
1075 CHECK(!stream_
.get());
1078 const ProxyServer
& proxy_server
= proxy_info_
.proxy_server();
1079 PrivacyMode privacy_mode
= request_info_
.privacy_mode
;
1080 if (IsHttpsProxyAndHttpUrl())
1083 if (existing_spdy_session_
.get()) {
1084 // We picked up an existing session, so we don't need our socket.
1085 if (connection_
->socket())
1086 connection_
->socket()->Disconnect();
1087 connection_
->Reset();
1089 int set_result
= SetSpdyHttpStream(existing_spdy_session_
, direct
);
1090 existing_spdy_session_
.reset();
1094 SpdySessionKey
spdy_session_key(origin_
, proxy_server
, privacy_mode
);
1095 if (IsHttpsProxyAndHttpUrl()) {
1096 // If we don't have a direct SPDY session, and we're using an HTTPS
1097 // proxy, then we might have a SPDY session to the proxy.
1098 // We never use privacy mode for connection to proxy server.
1099 spdy_session_key
= SpdySessionKey(proxy_server
.host_port_pair(),
1100 ProxyServer::Direct(),
1101 PRIVACY_MODE_DISABLED
);
1104 SpdySessionPool
* spdy_pool
= session_
->spdy_session_pool();
1105 base::WeakPtr
<SpdySession
> spdy_session
=
1106 spdy_pool
->FindAvailableSession(spdy_session_key
, net_log_
);
1109 return SetSpdyHttpStream(spdy_session
, direct
);
1113 spdy_pool
->CreateAvailableSessionFromSocket(spdy_session_key
,
1116 spdy_certificate_error_
,
1118 if (!spdy_session
->HasAcceptableTransportSecurity()) {
1119 spdy_session
->CloseSessionOnError(
1120 ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY
, "");
1121 return ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY
;
1124 new_spdy_session_
= spdy_session
;
1125 spdy_session_direct_
= direct
;
1126 const HostPortPair
& host_port_pair
= spdy_session_key
.host_port_pair();
1127 base::WeakPtr
<HttpServerProperties
> http_server_properties
=
1128 session_
->http_server_properties();
1129 if (http_server_properties
)
1130 http_server_properties
->SetSupportsSpdy(host_port_pair
, true);
1132 // Create a SpdyHttpStream attached to the session;
1133 // OnNewSpdySessionReadyCallback is not called until an event loop
1134 // iteration later, so if the SpdySession is closed between then, allow
1135 // reuse state from the underlying socket, sampled by SpdyHttpStream,
1136 // bubble up to the request.
1137 return SetSpdyHttpStream(new_spdy_session_
, spdy_session_direct_
);
1140 int HttpStreamFactoryImpl::Job::DoCreateStreamComplete(int result
) {
1144 session_
->proxy_service()->ReportSuccess(proxy_info_
,
1145 session_
->network_delegate());
1146 next_state_
= STATE_NONE
;
1150 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuth() {
1151 next_state_
= STATE_RESTART_TUNNEL_AUTH_COMPLETE
;
1152 ProxyClientSocket
* proxy_socket
=
1153 static_cast<ProxyClientSocket
*>(connection_
->socket());
1154 return proxy_socket
->RestartWithAuth(io_callback_
);
1157 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete(int result
) {
1158 if (result
== ERR_PROXY_AUTH_REQUESTED
)
1162 // Now that we've got the HttpProxyClientSocket connected. We have
1163 // to release it as an idle socket into the pool and start the connection
1164 // process from the beginning. Trying to pass it in with the
1165 // SSLSocketParams might cause a deadlock since params are dispatched
1166 // interchangeably. This request won't necessarily get this http proxy
1167 // socket, but there will be forward progress.
1168 establishing_tunnel_
= false;
1169 ReturnToStateInitConnection(false /* do not close connection */);
1173 return ReconsiderProxyAfterError(result
);
1176 void HttpStreamFactoryImpl::Job::ReturnToStateInitConnection(
1177 bool close_connection
) {
1178 if (close_connection
&& connection_
->socket())
1179 connection_
->socket()->Disconnect();
1180 connection_
->Reset();
1183 request_
->RemoveRequestFromSpdySessionRequestMap();
1185 next_state_
= STATE_INIT_CONNECTION
;
1188 void HttpStreamFactoryImpl::Job::SetSocketMotivation() {
1189 if (request_info_
.motivation
== HttpRequestInfo::PRECONNECT_MOTIVATED
)
1190 connection_
->socket()->SetSubresourceSpeculation();
1191 else if (request_info_
.motivation
== HttpRequestInfo::OMNIBOX_MOTIVATED
)
1192 connection_
->socket()->SetOmniboxSpeculation();
1193 // TODO(mbelshe): Add other motivations (like EARLY_LOAD_MOTIVATED).
1196 bool HttpStreamFactoryImpl::Job::IsHttpsProxyAndHttpUrl() const {
1197 if (!proxy_info_
.is_https())
1199 if (original_url_
.get()) {
1200 // We currently only support Alternate-Protocol where the original scheme
1202 DCHECK(original_url_
->SchemeIs("http"));
1203 return original_url_
->SchemeIs("http");
1205 return request_info_
.url
.SchemeIs("http");
1208 // Sets several fields of ssl_config for the given origin_server based on the
1209 // proxy info and other factors.
1210 void HttpStreamFactoryImpl::Job::InitSSLConfig(
1211 const HostPortPair
& origin_server
,
1212 SSLConfig
* ssl_config
,
1213 bool is_proxy
) const {
1214 if (proxy_info_
.is_https() && ssl_config
->send_client_cert
) {
1215 // When connecting through an HTTPS proxy, disable TLS False Start so
1216 // that client authentication errors can be distinguished between those
1217 // originating from the proxy server (ERR_PROXY_CONNECTION_FAILED) and
1218 // those originating from the endpoint (ERR_SSL_PROTOCOL_ERROR /
1219 // ERR_BAD_SSL_CLIENT_AUTH_CERT).
1220 // TODO(rch): This assumes that the HTTPS proxy will only request a
1221 // client certificate during the initial handshake.
1222 // http://crbug.com/59292
1223 ssl_config
->false_start_enabled
= false;
1227 FALLBACK_NONE
= 0, // SSL version fallback did not occur.
1228 FALLBACK_SSL3
= 1, // Fell back to SSL 3.0.
1229 FALLBACK_TLS1
= 2, // Fell back to TLS 1.0.
1230 FALLBACK_TLS1_1
= 3, // Fell back to TLS 1.1.
1234 int fallback
= FALLBACK_NONE
;
1235 if (ssl_config
->version_fallback
) {
1236 switch (ssl_config
->version_max
) {
1237 case SSL_PROTOCOL_VERSION_SSL3
:
1238 fallback
= FALLBACK_SSL3
;
1240 case SSL_PROTOCOL_VERSION_TLS1
:
1241 fallback
= FALLBACK_TLS1
;
1243 case SSL_PROTOCOL_VERSION_TLS1_1
:
1244 fallback
= FALLBACK_TLS1_1
;
1248 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback",
1249 fallback
, FALLBACK_MAX
);
1251 // We also wish to measure the amount of fallback connections for a host that
1252 // we know implements TLS up to 1.2. Ideally there would be no fallback here
1253 // but high numbers of SSLv3 would suggest that SSLv3 fallback is being
1254 // caused by network middleware rather than buggy HTTPS servers.
1255 const std::string
& host
= origin_server
.host();
1257 host
.size() >= 10 &&
1258 host
.compare(host
.size() - 10, 10, "google.com") == 0 &&
1259 (host
.size() == 10 || host
[host
.size()-11] == '.')) {
1260 UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback",
1261 fallback
, FALLBACK_MAX
);
1264 if (request_info_
.load_flags
& LOAD_VERIFY_EV_CERT
)
1265 ssl_config
->verify_ev_cert
= true;
1267 // Disable Channel ID if privacy mode is enabled.
1268 if (request_info_
.privacy_mode
== PRIVACY_MODE_ENABLED
)
1269 ssl_config
->channel_id_enabled
= false;
1273 int HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError(int error
) {
1274 DCHECK(!pac_request_
);
1277 // A failure to resolve the hostname or any error related to establishing a
1278 // TCP connection could be grounds for trying a new proxy configuration.
1280 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1281 // to proxy servers. The hostname in those URLs might fail to resolve if we
1282 // are still using a non-proxy config. We need to check if a proxy config
1283 // now exists that corresponds to a proxy server that could load the URL.
1286 case ERR_PROXY_CONNECTION_FAILED
:
1287 case ERR_NAME_NOT_RESOLVED
:
1288 case ERR_INTERNET_DISCONNECTED
:
1289 case ERR_ADDRESS_UNREACHABLE
:
1290 case ERR_CONNECTION_CLOSED
:
1291 case ERR_CONNECTION_TIMED_OUT
:
1292 case ERR_CONNECTION_RESET
:
1293 case ERR_CONNECTION_REFUSED
:
1294 case ERR_CONNECTION_ABORTED
:
1296 case ERR_TUNNEL_CONNECTION_FAILED
:
1297 case ERR_SOCKS_CONNECTION_FAILED
:
1298 // This can happen in the case of trying to talk to a proxy using SSL, and
1299 // ending up talking to a captive portal that supports SSL instead.
1300 case ERR_PROXY_CERTIFICATE_INVALID
:
1301 // This can happen when trying to talk SSL to a non-SSL server (Like a
1303 case ERR_SSL_PROTOCOL_ERROR
:
1305 case ERR_SOCKS_CONNECTION_HOST_UNREACHABLE
:
1306 // Remap the SOCKS-specific "host unreachable" error to a more
1307 // generic error code (this way consumers like the link doctor
1308 // know to substitute their error page).
1310 // Note that if the host resolving was done by the SOCKS5 proxy, we can't
1311 // differentiate between a proxy-side "host not found" versus a proxy-side
1312 // "address unreachable" error, and will report both of these failures as
1313 // ERR_ADDRESS_UNREACHABLE.
1314 return ERR_ADDRESS_UNREACHABLE
;
1319 if (request_info_
.load_flags
& LOAD_BYPASS_PROXY
) {
1323 if (proxy_info_
.is_https() && proxy_ssl_config_
.send_client_cert
) {
1324 session_
->ssl_client_auth_cache()->Remove(
1325 proxy_info_
.proxy_server().host_port_pair());
1328 int rv
= session_
->proxy_service()->ReconsiderProxyAfterError(
1329 request_info_
.url
, request_info_
.load_flags
, error
, &proxy_info_
,
1330 io_callback_
, &pac_request_
, session_
->network_delegate(), net_log_
);
1331 if (rv
== OK
|| rv
== ERR_IO_PENDING
) {
1332 // If the error was during connection setup, there is no socket to
1334 if (connection_
->socket())
1335 connection_
->socket()->Disconnect();
1336 connection_
->Reset();
1338 request_
->RemoveRequestFromSpdySessionRequestMap();
1339 next_state_
= STATE_RESOLVE_PROXY_COMPLETE
;
1341 // If ReconsiderProxyAfterError() failed synchronously, it means
1342 // there was nothing left to fall-back to, so fail the transaction
1343 // with the last connection error we got.
1344 // TODO(eroman): This is a confusing contract, make it more obvious.
1351 int HttpStreamFactoryImpl::Job::HandleCertificateError(int error
) {
1353 DCHECK(IsCertificateError(error
));
1355 SSLClientSocket
* ssl_socket
=
1356 static_cast<SSLClientSocket
*>(connection_
->socket());
1357 ssl_socket
->GetSSLInfo(&ssl_info_
);
1359 // Add the bad certificate to the set of allowed certificates in the
1360 // SSL config object. This data structure will be consulted after calling
1361 // RestartIgnoringLastError(). And the user will be asked interactively
1362 // before RestartIgnoringLastError() is ever called.
1363 SSLConfig::CertAndStatus bad_cert
;
1365 // |ssl_info_.cert| may be NULL if we failed to create
1366 // X509Certificate for whatever reason, but normally it shouldn't
1367 // happen, unless this code is used inside sandbox.
1368 if (ssl_info_
.cert
.get() == NULL
||
1369 !X509Certificate::GetDEREncoded(ssl_info_
.cert
->os_cert_handle(),
1370 &bad_cert
.der_cert
)) {
1373 bad_cert
.cert_status
= ssl_info_
.cert_status
;
1374 server_ssl_config_
.allowed_bad_certs
.push_back(bad_cert
);
1376 int load_flags
= request_info_
.load_flags
;
1377 if (session_
->params().ignore_certificate_errors
)
1378 load_flags
|= LOAD_IGNORE_ALL_CERT_ERRORS
;
1379 if (ssl_socket
->IgnoreCertError(error
, load_flags
))
1384 void HttpStreamFactoryImpl::Job::SwitchToSpdyMode() {
1385 if (HttpStreamFactory::spdy_enabled())
1390 void HttpStreamFactoryImpl::Job::LogHttpConnectedMetrics(
1391 const ClientSocketHandle
& handle
) {
1392 UMA_HISTOGRAM_ENUMERATION("Net.HttpSocketType", handle
.reuse_type(),
1393 ClientSocketHandle::NUM_TYPES
);
1395 switch (handle
.reuse_type()) {
1396 case ClientSocketHandle::UNUSED
:
1397 UMA_HISTOGRAM_CUSTOM_TIMES("Net.HttpConnectionLatency",
1398 handle
.setup_time(),
1399 base::TimeDelta::FromMilliseconds(1),
1400 base::TimeDelta::FromMinutes(10),
1403 case ClientSocketHandle::UNUSED_IDLE
:
1404 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_UnusedSocket",
1406 base::TimeDelta::FromMilliseconds(1),
1407 base::TimeDelta::FromMinutes(6),
1410 case ClientSocketHandle::REUSED_IDLE
:
1411 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_ReusedSocket",
1413 base::TimeDelta::FromMilliseconds(1),
1414 base::TimeDelta::FromMinutes(6),
1423 bool HttpStreamFactoryImpl::Job::IsPreconnecting() const {
1424 DCHECK_GE(num_streams_
, 0);
1425 return num_streams_
> 0;
1428 bool HttpStreamFactoryImpl::Job::IsOrphaned() const {
1429 return !IsPreconnecting() && !request_
;
1432 void HttpStreamFactoryImpl::Job::ReportJobSuccededForRequest() {
1433 net::AlternateProtocolExperiment alternate_protocol_experiment
=
1434 ALTERNATE_PROTOCOL_NOT_PART_OF_EXPERIMENT
;
1435 base::WeakPtr
<HttpServerProperties
> http_server_properties
=
1436 session_
->http_server_properties();
1437 if (http_server_properties
) {
1438 alternate_protocol_experiment
=
1439 http_server_properties
->GetAlternateProtocolExperiment();
1441 if (using_existing_quic_session_
) {
1442 // If an existing session was used, then no TCP connection was
1444 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_NO_RACE
,
1445 alternate_protocol_experiment
);
1446 } else if (original_url_
) {
1447 // This job was the alternate protocol job, and hence won the race.
1448 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_WON_RACE
,
1449 alternate_protocol_experiment
);
1451 // This job was the normal job, and hence the alternate protocol job lost
1453 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_LOST_RACE
,
1454 alternate_protocol_experiment
);
1458 void HttpStreamFactoryImpl::Job::MarkOtherJobComplete(const Job
& job
) {
1459 DCHECK_EQ(STATUS_RUNNING
, other_job_status_
);
1460 other_job_status_
= job
.job_status_
;
1461 MaybeMarkAlternateProtocolBroken();
1464 void HttpStreamFactoryImpl::Job::MaybeMarkAlternateProtocolBroken() {
1465 if (job_status_
== STATUS_RUNNING
|| other_job_status_
== STATUS_RUNNING
)
1468 bool is_alternate_protocol_job
= original_url_
.get() != NULL
;
1469 if (is_alternate_protocol_job
) {
1470 if (job_status_
== STATUS_BROKEN
&& other_job_status_
== STATUS_SUCCEEDED
) {
1471 HistogramBrokenAlternateProtocolLocation(
1472 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_ALT
);
1473 session_
->http_server_properties()->SetBrokenAlternateProtocol(
1474 HostPortPair::FromURL(*original_url_
));
1479 if (job_status_
== STATUS_SUCCEEDED
&& other_job_status_
== STATUS_BROKEN
) {
1480 HistogramBrokenAlternateProtocolLocation(
1481 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_MAIN
);
1482 session_
->http_server_properties()->SetBrokenAlternateProtocol(
1483 HostPortPair::FromURL(request_info_
.url
));