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_pipelined_connection.h"
24 #include "net/http/http_pipelined_host.h"
25 #include "net/http/http_pipelined_host_pool.h"
26 #include "net/http/http_pipelined_stream.h"
27 #include "net/http/http_proxy_client_socket.h"
28 #include "net/http/http_proxy_client_socket_pool.h"
29 #include "net/http/http_request_info.h"
30 #include "net/http/http_server_properties.h"
31 #include "net/http/http_stream_factory.h"
32 #include "net/http/http_stream_factory_impl_request.h"
33 #include "net/quic/quic_http_stream.h"
34 #include "net/socket/client_socket_handle.h"
35 #include "net/socket/client_socket_pool.h"
36 #include "net/socket/client_socket_pool_manager.h"
37 #include "net/socket/socks_client_socket_pool.h"
38 #include "net/socket/ssl_client_socket.h"
39 #include "net/socket/ssl_client_socket_pool.h"
40 #include "net/spdy/spdy_http_stream.h"
41 #include "net/spdy/spdy_session.h"
42 #include "net/spdy/spdy_session_pool.h"
43 #include "net/ssl/ssl_cert_request_info.h"
47 // Returns parameters associated with the start of a HTTP stream job.
48 base::Value
* NetLogHttpStreamJobCallback(const GURL
* original_url
,
50 RequestPriority priority
,
51 NetLog::LogLevel
/* log_level */) {
52 base::DictionaryValue
* dict
= new base::DictionaryValue();
53 dict
->SetString("original_url", original_url
->GetOrigin().spec());
54 dict
->SetString("url", url
->GetOrigin().spec());
55 dict
->SetString("priority", RequestPriorityToString(priority
));
59 // Returns parameters associated with the Proto (with NPN negotiation) of a HTTP
61 base::Value
* NetLogHttpStreamProtoCallback(
62 const SSLClientSocket::NextProtoStatus status
,
63 const std::string
* proto
,
64 const std::string
* server_protos
,
65 NetLog::LogLevel
/* log_level */) {
66 base::DictionaryValue
* dict
= new base::DictionaryValue();
68 dict
->SetString("next_proto_status",
69 SSLClientSocket::NextProtoStatusToString(status
));
70 dict
->SetString("proto", *proto
);
71 dict
->SetString("server_protos",
72 SSLClientSocket::ServerProtosToString(*server_protos
));
76 HttpStreamFactoryImpl::Job::Job(HttpStreamFactoryImpl
* stream_factory
,
77 HttpNetworkSession
* session
,
78 const HttpRequestInfo
& request_info
,
79 RequestPriority priority
,
80 const SSLConfig
& server_ssl_config
,
81 const SSLConfig
& proxy_ssl_config
,
84 request_info_(request_info
),
86 server_ssl_config_(server_ssl_config
),
87 proxy_ssl_config_(proxy_ssl_config
),
88 net_log_(BoundNetLog::Make(net_log
, NetLog::SOURCE_HTTP_STREAM_JOB
)),
89 io_callback_(base::Bind(&Job::OnIOComplete
, base::Unretained(this))),
90 connection_(new ClientSocketHandle
),
92 stream_factory_(stream_factory
),
93 next_state_(STATE_NONE
),
100 quic_request_(session_
->quic_stream_factory()),
101 using_existing_quic_session_(false),
102 force_spdy_always_(HttpStreamFactory::force_spdy_always()),
103 force_spdy_over_ssl_(HttpStreamFactory::force_spdy_over_ssl()),
104 spdy_certificate_error_(OK
),
105 establishing_tunnel_(false),
106 was_npn_negotiated_(false),
107 protocol_negotiated_(kProtoUnknown
),
109 spdy_session_direct_(false),
110 existing_available_pipeline_(false),
112 DCHECK(stream_factory
);
116 HttpStreamFactoryImpl::Job::~Job() {
117 net_log_
.EndEvent(NetLog::TYPE_HTTP_STREAM_JOB
);
119 // When we're in a partially constructed state, waiting for the user to
120 // provide certificate handling information or authentication, we can't reuse
121 // this stream at all.
122 if (next_state_
== STATE_WAITING_USER_ACTION
) {
123 connection_
->socket()->Disconnect();
128 session_
->proxy_service()->CancelPacRequest(pac_request_
);
130 // The stream could be in a partial state. It is not reusable.
131 if (stream_
.get() && next_state_
!= STATE_DONE
)
132 stream_
->Close(true /* not reusable */);
135 void HttpStreamFactoryImpl::Job::Start(Request
* request
) {
141 int HttpStreamFactoryImpl::Job::Preconnect(int num_streams
) {
142 DCHECK_GT(num_streams
, 0);
143 HostPortPair origin_server
=
144 HostPortPair(request_info_
.url
.HostNoBrackets(),
145 request_info_
.url
.EffectiveIntPort());
146 base::WeakPtr
<HttpServerProperties
> http_server_properties
=
147 session_
->http_server_properties();
148 if (http_server_properties
&&
149 http_server_properties
->SupportsSpdy(origin_server
)) {
152 num_streams_
= num_streams
;
154 return StartInternal();
157 int HttpStreamFactoryImpl::Job::RestartTunnelWithProxyAuth(
158 const AuthCredentials
& credentials
) {
159 DCHECK(establishing_tunnel_
);
160 next_state_
= STATE_RESTART_TUNNEL_AUTH
;
165 LoadState
HttpStreamFactoryImpl::Job::GetLoadState() const {
166 switch (next_state_
) {
167 case STATE_RESOLVE_PROXY_COMPLETE
:
168 return session_
->proxy_service()->GetLoadState(pac_request_
);
169 case STATE_INIT_CONNECTION_COMPLETE
:
170 case STATE_CREATE_STREAM_COMPLETE
:
171 return using_quic_
? LOAD_STATE_CONNECTING
: connection_
->GetLoadState();
173 return LOAD_STATE_IDLE
;
177 void HttpStreamFactoryImpl::Job::MarkAsAlternate(
178 const GURL
& original_url
,
179 PortAlternateProtocolPair alternate
) {
180 DCHECK(!original_url_
.get());
181 original_url_
.reset(new GURL(original_url
));
182 if (alternate
.protocol
== QUIC
) {
183 DCHECK(session_
->params().enable_quic
);
188 void HttpStreamFactoryImpl::Job::WaitFor(Job
* job
) {
189 DCHECK_EQ(STATE_NONE
, next_state_
);
190 DCHECK_EQ(STATE_NONE
, job
->next_state_
);
191 DCHECK(!blocking_job_
);
192 DCHECK(!job
->waiting_job_
);
194 job
->waiting_job_
= this;
197 void HttpStreamFactoryImpl::Job::Resume(Job
* job
) {
198 DCHECK_EQ(blocking_job_
, job
);
199 blocking_job_
= NULL
;
201 // We know we're blocked if the next_state_ is STATE_WAIT_FOR_JOB_COMPLETE.
203 if (next_state_
== STATE_WAIT_FOR_JOB_COMPLETE
) {
204 base::MessageLoop::current()->PostTask(
206 base::Bind(&HttpStreamFactoryImpl::Job::OnIOComplete
,
207 ptr_factory_
.GetWeakPtr(), OK
));
211 void HttpStreamFactoryImpl::Job::Orphan(const Request
* request
) {
212 DCHECK_EQ(request_
, request
);
215 // We've been orphaned, but there's a job we're blocked on. Don't bother
216 // racing, just cancel ourself.
217 DCHECK(blocking_job_
->waiting_job_
);
218 blocking_job_
->waiting_job_
= NULL
;
219 blocking_job_
= NULL
;
220 if (stream_factory_
->for_websockets_
&&
221 connection_
&& connection_
->socket())
222 connection_
->socket()->Disconnect();
223 stream_factory_
->OnOrphanedJobComplete(this);
224 } else if (stream_factory_
->for_websockets_
) {
225 // We cancel this job because a WebSocketHandshakeStream can't be created
226 // without a WebSocketHandshakeStreamBase::CreateHelper which is stored in
227 // the Request class and isn't accessible from this job.
228 if (connection_
&& connection_
->socket())
229 connection_
->socket()->Disconnect();
230 stream_factory_
->OnOrphanedJobComplete(this);
234 void HttpStreamFactoryImpl::Job::SetPriority(RequestPriority priority
) {
235 priority_
= priority
;
236 // TODO(akalin): Propagate this to |connection_| and maybe the
240 bool HttpStreamFactoryImpl::Job::was_npn_negotiated() const {
241 return was_npn_negotiated_
;
244 NextProto
HttpStreamFactoryImpl::Job::protocol_negotiated() const {
245 return protocol_negotiated_
;
248 bool HttpStreamFactoryImpl::Job::using_spdy() const {
252 const SSLConfig
& HttpStreamFactoryImpl::Job::server_ssl_config() const {
253 return server_ssl_config_
;
256 const SSLConfig
& HttpStreamFactoryImpl::Job::proxy_ssl_config() const {
257 return proxy_ssl_config_
;
260 const ProxyInfo
& HttpStreamFactoryImpl::Job::proxy_info() const {
264 void HttpStreamFactoryImpl::Job::GetSSLInfo() {
266 DCHECK(!establishing_tunnel_
);
267 DCHECK(connection_
.get() && connection_
->socket());
268 SSLClientSocket
* ssl_socket
=
269 static_cast<SSLClientSocket
*>(connection_
->socket());
270 ssl_socket
->GetSSLInfo(&ssl_info_
);
273 SpdySessionKey
HttpStreamFactoryImpl::Job::GetSpdySessionKey() const {
274 // In the case that we're using an HTTPS proxy for an HTTP url,
275 // we look for a SPDY session *to* the proxy, instead of to the
277 PrivacyMode privacy_mode
= request_info_
.privacy_mode
;
278 if (IsHttpsProxyAndHttpUrl()) {
279 return SpdySessionKey(proxy_info_
.proxy_server().host_port_pair(),
280 ProxyServer::Direct(),
283 return SpdySessionKey(origin_
,
284 proxy_info_
.proxy_server(),
289 bool HttpStreamFactoryImpl::Job::CanUseExistingSpdySession() const {
290 // We need to make sure that if a spdy session was created for
291 // https://somehost/ that we don't use that session for http://somehost:443/.
292 // The only time we can use an existing session is if the request URL is
293 // https (the normal case) or if we're connection to a SPDY proxy, or
294 // if we're running with force_spdy_always_. crbug.com/133176
295 // TODO(ricea): Add "wss" back to this list when SPDY WebSocket support is
297 return request_info_
.url
.SchemeIs("https") ||
298 proxy_info_
.proxy_server().is_https() ||
302 void HttpStreamFactoryImpl::Job::OnStreamReadyCallback() {
303 DCHECK(stream_
.get());
304 DCHECK(!IsPreconnecting());
305 DCHECK(!stream_factory_
->for_websockets_
);
307 stream_factory_
->OnOrphanedJobComplete(this);
309 request_
->Complete(was_npn_negotiated(),
310 protocol_negotiated(),
313 request_
->OnStreamReady(this, server_ssl_config_
, proxy_info_
,
316 // |this| may be deleted after this call.
319 void HttpStreamFactoryImpl::Job::OnWebSocketHandshakeStreamReadyCallback() {
320 DCHECK(websocket_stream_
);
321 DCHECK(!IsPreconnecting());
322 DCHECK(stream_factory_
->for_websockets_
);
323 // An orphaned WebSocket job will be closed immediately and
325 DCHECK(!IsOrphaned());
326 request_
->Complete(was_npn_negotiated(),
327 protocol_negotiated(),
330 request_
->OnWebSocketHandshakeStreamReady(this,
333 websocket_stream_
.release());
334 // |this| may be deleted after this call.
337 void HttpStreamFactoryImpl::Job::OnNewSpdySessionReadyCallback() {
338 DCHECK(stream_
.get());
339 DCHECK(!IsPreconnecting());
340 DCHECK(using_spdy());
341 // Note: an event loop iteration has passed, so |new_spdy_session_| may be
342 // NULL at this point if the SpdySession closed immediately after creation.
343 base::WeakPtr
<SpdySession
> spdy_session
= new_spdy_session_
;
344 new_spdy_session_
.reset();
347 stream_factory_
->OnNewSpdySessionReady(
348 spdy_session
, spdy_session_direct_
, server_ssl_config_
, proxy_info_
,
349 was_npn_negotiated(), protocol_negotiated(), using_spdy(), net_log_
);
351 stream_factory_
->OnOrphanedJobComplete(this);
353 request_
->OnNewSpdySessionReady(
354 this, stream_
.Pass(), spdy_session
, spdy_session_direct_
);
356 // |this| may be deleted after this call.
359 void HttpStreamFactoryImpl::Job::OnStreamFailedCallback(int result
) {
360 DCHECK(!IsPreconnecting());
362 stream_factory_
->OnOrphanedJobComplete(this);
364 request_
->OnStreamFailed(this, result
, server_ssl_config_
);
365 // |this| may be deleted after this call.
368 void HttpStreamFactoryImpl::Job::OnCertificateErrorCallback(
369 int result
, const SSLInfo
& ssl_info
) {
370 DCHECK(!IsPreconnecting());
372 stream_factory_
->OnOrphanedJobComplete(this);
374 request_
->OnCertificateError(this, result
, server_ssl_config_
, ssl_info
);
375 // |this| may be deleted after this call.
378 void HttpStreamFactoryImpl::Job::OnNeedsProxyAuthCallback(
379 const HttpResponseInfo
& response
,
380 HttpAuthController
* auth_controller
) {
381 DCHECK(!IsPreconnecting());
383 stream_factory_
->OnOrphanedJobComplete(this);
385 request_
->OnNeedsProxyAuth(
386 this, response
, server_ssl_config_
, proxy_info_
, auth_controller
);
387 // |this| may be deleted after this call.
390 void HttpStreamFactoryImpl::Job::OnNeedsClientAuthCallback(
391 SSLCertRequestInfo
* cert_info
) {
392 DCHECK(!IsPreconnecting());
394 stream_factory_
->OnOrphanedJobComplete(this);
396 request_
->OnNeedsClientAuth(this, server_ssl_config_
, cert_info
);
397 // |this| may be deleted after this call.
400 void HttpStreamFactoryImpl::Job::OnHttpsProxyTunnelResponseCallback(
401 const HttpResponseInfo
& response_info
,
402 HttpStream
* stream
) {
403 DCHECK(!IsPreconnecting());
405 stream_factory_
->OnOrphanedJobComplete(this);
407 request_
->OnHttpsProxyTunnelResponse(
408 this, response_info
, server_ssl_config_
, proxy_info_
, stream
);
409 // |this| may be deleted after this call.
412 void HttpStreamFactoryImpl::Job::OnPreconnectsComplete() {
414 if (new_spdy_session_
.get()) {
415 stream_factory_
->OnNewSpdySessionReady(new_spdy_session_
,
416 spdy_session_direct_
,
419 was_npn_negotiated(),
420 protocol_negotiated(),
424 stream_factory_
->OnPreconnectsComplete(this);
425 // |this| may be deleted after this call.
429 int HttpStreamFactoryImpl::Job::OnHostResolution(
430 SpdySessionPool
* spdy_session_pool
,
431 const SpdySessionKey
& spdy_session_key
,
432 const AddressList
& addresses
,
433 const BoundNetLog
& net_log
) {
434 // It is OK to dereference spdy_session_pool, because the
435 // ClientSocketPoolManager will be destroyed in the same callback that
436 // destroys the SpdySessionPool.
438 spdy_session_pool
->FindAvailableSession(spdy_session_key
, net_log
) ?
439 ERR_SPDY_SESSION_ALREADY_EXISTS
: OK
;
442 void HttpStreamFactoryImpl::Job::OnIOComplete(int result
) {
446 int HttpStreamFactoryImpl::Job::RunLoop(int result
) {
447 result
= DoLoop(result
);
449 if (result
== ERR_IO_PENDING
)
452 // If there was an error, we should have already resumed the |waiting_job_|,
454 DCHECK(result
== OK
|| waiting_job_
== NULL
);
456 if (IsPreconnecting()) {
457 base::MessageLoop::current()->PostTask(
459 base::Bind(&HttpStreamFactoryImpl::Job::OnPreconnectsComplete
,
460 ptr_factory_
.GetWeakPtr()));
461 return ERR_IO_PENDING
;
464 if (IsCertificateError(result
)) {
465 // Retrieve SSL information from the socket.
468 next_state_
= STATE_WAITING_USER_ACTION
;
469 base::MessageLoop::current()->PostTask(
471 base::Bind(&HttpStreamFactoryImpl::Job::OnCertificateErrorCallback
,
472 ptr_factory_
.GetWeakPtr(), result
, ssl_info_
));
473 return ERR_IO_PENDING
;
477 case ERR_PROXY_AUTH_REQUESTED
: {
478 DCHECK(connection_
.get());
479 DCHECK(connection_
->socket());
480 DCHECK(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 next_state_
= STATE_DONE
;
518 if (new_spdy_session_
.get()) {
519 base::MessageLoop::current()->PostTask(
521 base::Bind(&Job::OnNewSpdySessionReadyCallback
,
522 ptr_factory_
.GetWeakPtr()));
523 } else if (stream_factory_
->for_websockets_
) {
524 DCHECK(websocket_stream_
);
525 base::MessageLoop::current()->PostTask(
527 base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback
,
528 ptr_factory_
.GetWeakPtr()));
530 DCHECK(stream_
.get());
531 base::MessageLoop::current()->PostTask(
533 base::Bind(&Job::OnStreamReadyCallback
, ptr_factory_
.GetWeakPtr()));
535 return ERR_IO_PENDING
;
538 base::MessageLoop::current()->PostTask(
540 base::Bind(&Job::OnStreamFailedCallback
, ptr_factory_
.GetWeakPtr(),
542 return ERR_IO_PENDING
;
546 int HttpStreamFactoryImpl::Job::DoLoop(int result
) {
547 DCHECK_NE(next_state_
, STATE_NONE
);
550 State state
= next_state_
;
551 next_state_
= STATE_NONE
;
557 case STATE_RESOLVE_PROXY
:
559 rv
= DoResolveProxy();
561 case STATE_RESOLVE_PROXY_COMPLETE
:
562 rv
= DoResolveProxyComplete(rv
);
564 case STATE_WAIT_FOR_JOB
:
568 case STATE_WAIT_FOR_JOB_COMPLETE
:
569 rv
= DoWaitForJobComplete(rv
);
571 case STATE_INIT_CONNECTION
:
573 rv
= DoInitConnection();
575 case STATE_INIT_CONNECTION_COMPLETE
:
576 rv
= DoInitConnectionComplete(rv
);
578 case STATE_WAITING_USER_ACTION
:
579 rv
= DoWaitingUserAction(rv
);
581 case STATE_RESTART_TUNNEL_AUTH
:
583 rv
= DoRestartTunnelAuth();
585 case STATE_RESTART_TUNNEL_AUTH_COMPLETE
:
586 rv
= DoRestartTunnelAuthComplete(rv
);
588 case STATE_CREATE_STREAM
:
590 rv
= DoCreateStream();
592 case STATE_CREATE_STREAM_COMPLETE
:
593 rv
= DoCreateStreamComplete(rv
);
596 NOTREACHED() << "bad state";
600 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
604 int HttpStreamFactoryImpl::Job::StartInternal() {
605 CHECK_EQ(STATE_NONE
, next_state_
);
606 next_state_
= STATE_START
;
607 int rv
= RunLoop(OK
);
608 DCHECK_EQ(ERR_IO_PENDING
, rv
);
612 int HttpStreamFactoryImpl::Job::DoStart() {
613 int port
= request_info_
.url
.EffectiveIntPort();
614 origin_
= HostPortPair(request_info_
.url
.HostNoBrackets(), port
);
615 origin_url_
= stream_factory_
->ApplyHostMappingRules(
616 request_info_
.url
, &origin_
);
617 http_pipelining_key_
.reset(new HttpPipelinedHost::Key(origin_
));
619 net_log_
.BeginEvent(NetLog::TYPE_HTTP_STREAM_JOB
,
620 base::Bind(&NetLogHttpStreamJobCallback
,
621 &request_info_
.url
, &origin_url_
,
624 // Don't connect to restricted ports.
625 bool is_port_allowed
= IsPortAllowedByDefault(port
);
626 if (request_info_
.url
.SchemeIs("ftp")) {
627 // Never share connection with other jobs for FTP requests.
628 DCHECK(!waiting_job_
);
630 is_port_allowed
= IsPortAllowedByFtp(port
);
632 if (!is_port_allowed
&& !IsPortAllowedByOverride(port
)) {
634 waiting_job_
->Resume(this);
637 return ERR_UNSAFE_PORT
;
640 next_state_
= STATE_RESOLVE_PROXY
;
644 int HttpStreamFactoryImpl::Job::DoResolveProxy() {
645 DCHECK(!pac_request_
);
647 next_state_
= STATE_RESOLVE_PROXY_COMPLETE
;
649 if (request_info_
.load_flags
& LOAD_BYPASS_PROXY
) {
650 proxy_info_
.UseDirect();
654 return session_
->proxy_service()->ResolveProxy(
655 request_info_
.url
, &proxy_info_
, io_callback_
, &pac_request_
, net_log_
);
658 int HttpStreamFactoryImpl::Job::DoResolveProxyComplete(int result
) {
662 // Remove unsupported proxies from the list.
663 proxy_info_
.RemoveProxiesWithoutScheme(
664 ProxyServer::SCHEME_DIRECT
| ProxyServer::SCHEME_QUIC
|
665 ProxyServer::SCHEME_HTTP
| ProxyServer::SCHEME_HTTPS
|
666 ProxyServer::SCHEME_SOCKS4
| ProxyServer::SCHEME_SOCKS5
);
668 if (proxy_info_
.is_empty()) {
669 // No proxies/direct to choose from. This happens when we don't support
670 // any of the proxies in the returned list.
671 result
= ERR_NO_SUPPORTED_PROXIES
;
672 } else if (using_quic_
&&
673 (!proxy_info_
.is_quic() && !proxy_info_
.is_direct())) {
674 // QUIC can not be spoken to non-QUIC proxies. This error should not be
675 // user visible, because the non-alternate job should be resumed.
676 result
= ERR_NO_SUPPORTED_PROXIES
;
682 waiting_job_
->Resume(this);
689 next_state_
= STATE_WAIT_FOR_JOB
;
691 next_state_
= STATE_INIT_CONNECTION
;
695 bool HttpStreamFactoryImpl::Job::ShouldForceSpdySSL() const {
696 bool rv
= force_spdy_always_
&& force_spdy_over_ssl_
;
697 return rv
&& !HttpStreamFactory::HasSpdyExclusion(origin_
);
700 bool HttpStreamFactoryImpl::Job::ShouldForceSpdyWithoutSSL() const {
701 bool rv
= force_spdy_always_
&& !force_spdy_over_ssl_
;
702 return rv
&& !HttpStreamFactory::HasSpdyExclusion(origin_
);
705 bool HttpStreamFactoryImpl::Job::ShouldForceQuic() const {
706 return session_
->params().enable_quic
&&
707 session_
->params().origin_to_force_quic_on
.Equals(origin_
) &&
708 proxy_info_
.is_direct();
711 int HttpStreamFactoryImpl::Job::DoWaitForJob() {
712 DCHECK(blocking_job_
);
713 next_state_
= STATE_WAIT_FOR_JOB_COMPLETE
;
714 return ERR_IO_PENDING
;
717 int HttpStreamFactoryImpl::Job::DoWaitForJobComplete(int result
) {
718 DCHECK(!blocking_job_
);
719 DCHECK_EQ(OK
, result
);
720 next_state_
= STATE_INIT_CONNECTION
;
724 int HttpStreamFactoryImpl::Job::DoInitConnection() {
725 DCHECK(!blocking_job_
);
726 DCHECK(!connection_
->is_initialized());
727 DCHECK(proxy_info_
.proxy_server().is_valid());
728 next_state_
= STATE_INIT_CONNECTION_COMPLETE
;
730 using_ssl_
= request_info_
.url
.SchemeIs("https") ||
731 request_info_
.url
.SchemeIs("wss") || ShouldForceSpdySSL();
734 if (ShouldForceQuic())
737 if (proxy_info_
.is_quic())
741 DCHECK(session_
->params().enable_quic
);
742 if (proxy_info_
.is_quic() && !request_info_
.url
.SchemeIs("http")) {
744 // TODO(rch): support QUIC proxies for HTTPS urls.
745 return ERR_NOT_IMPLEMENTED
;
747 HostPortPair destination
= proxy_info_
.is_quic() ?
748 proxy_info_
.proxy_server().host_port_pair() : origin_
;
749 next_state_
= STATE_INIT_CONNECTION_COMPLETE
;
750 bool secure_quic
= using_ssl_
|| proxy_info_
.is_quic();
751 int rv
= quic_request_
.Request(
752 destination
, secure_quic
, request_info_
.privacy_mode
,
753 request_info_
.method
, net_log_
, io_callback_
);
755 using_existing_quic_session_
= true;
757 // OK, there's no available QUIC session. Let |waiting_job_| resume
760 waiting_job_
->Resume(this);
767 // Check first if we have a spdy session for this group. If so, then go
768 // straight to using that.
769 SpdySessionKey spdy_session_key
= GetSpdySessionKey();
770 base::WeakPtr
<SpdySession
> spdy_session
=
771 session_
->spdy_session_pool()->FindAvailableSession(
772 spdy_session_key
, net_log_
);
773 if (spdy_session
&& CanUseExistingSpdySession()) {
774 // If we're preconnecting, but we already have a SpdySession, we don't
775 // actually need to preconnect any sockets, so we're done.
776 if (IsPreconnecting())
779 next_state_
= STATE_CREATE_STREAM
;
780 existing_spdy_session_
= spdy_session
;
782 } else if (request_
&& (using_ssl_
|| ShouldForceSpdyWithoutSSL())) {
783 // Update the spdy session key for the request that launched this job.
784 request_
->SetSpdySessionKey(spdy_session_key
);
785 } else if (IsRequestEligibleForPipelining()) {
786 // TODO(simonjam): With pipelining, we might be better off using fewer
787 // connections and thus should make fewer preconnections. Explore
788 // preconnecting fewer than the requested num_connections.
790 // Separate note: A forced pipeline is always available if one exists for
791 // this key. This is different than normal pipelines, which may be
792 // unavailable or unusable. So, there is no need to worry about a race
793 // between when a pipeline becomes available and when this job blocks.
794 existing_available_pipeline_
= stream_factory_
->http_pipelined_host_pool_
.
795 IsExistingPipelineAvailableForKey(*http_pipelining_key_
.get());
796 if (existing_available_pipeline_
) {
799 bool was_new_key
= request_
->SetHttpPipeliningKey(
800 *http_pipelining_key_
.get());
801 if (!was_new_key
&& session_
->force_http_pipelining()) {
802 return ERR_IO_PENDING
;
807 // OK, there's no available SPDY session. Let |waiting_job_| resume if it's
811 waiting_job_
->Resume(this);
815 if (proxy_info_
.is_http() || proxy_info_
.is_https())
816 establishing_tunnel_
= using_ssl_
;
818 bool want_spdy_over_npn
= original_url_
!= NULL
;
820 if (proxy_info_
.is_https()) {
821 InitSSLConfig(proxy_info_
.proxy_server().host_port_pair(),
823 true /* is a proxy server */);
824 // Disable revocation checking for HTTPS proxies since the revocation
825 // requests are probably going to need to go through the proxy too.
826 proxy_ssl_config_
.rev_checking_enabled
= false;
829 InitSSLConfig(origin_
, &server_ssl_config_
,
830 false /* not a proxy server */);
833 if (IsPreconnecting()) {
834 DCHECK(!stream_factory_
->for_websockets_
);
835 return PreconnectSocketsForHttpRequest(
837 request_info_
.extra_headers
,
838 request_info_
.load_flags
,
842 ShouldForceSpdySSL(),
846 request_info_
.privacy_mode
,
850 // If we can't use a SPDY session, don't both checking for one after
851 // the hostname is resolved.
852 OnHostResolutionCallback resolution_callback
= CanUseExistingSpdySession() ?
853 base::Bind(&Job::OnHostResolution
, session_
->spdy_session_pool(),
854 GetSpdySessionKey()) :
855 OnHostResolutionCallback();
856 if (stream_factory_
->for_websockets_
) {
857 // TODO(ricea): Re-enable NPN when WebSockets over SPDY is supported.
858 SSLConfig websocket_server_ssl_config
= server_ssl_config_
;
859 websocket_server_ssl_config
.next_protos
.clear();
860 return InitSocketHandleForWebSocketRequest(
861 origin_url_
, request_info_
.extra_headers
, request_info_
.load_flags
,
862 priority_
, session_
, proxy_info_
, ShouldForceSpdySSL(),
863 want_spdy_over_npn
, websocket_server_ssl_config
, proxy_ssl_config_
,
864 request_info_
.privacy_mode
, net_log_
,
865 connection_
.get(), resolution_callback
, io_callback_
);
867 return InitSocketHandleForHttpRequest(
868 origin_url_
, request_info_
.extra_headers
, request_info_
.load_flags
,
869 priority_
, session_
, proxy_info_
, ShouldForceSpdySSL(),
870 want_spdy_over_npn
, server_ssl_config_
, proxy_ssl_config_
,
871 request_info_
.privacy_mode
, net_log_
,
872 connection_
.get(), resolution_callback
, io_callback_
);
876 int HttpStreamFactoryImpl::Job::DoInitConnectionComplete(int result
) {
877 if (IsPreconnecting()) {
880 DCHECK_EQ(OK
, result
);
884 if (result
== ERR_SPDY_SESSION_ALREADY_EXISTS
) {
885 // We found a SPDY connection after resolving the host. This is
886 // probably an IP pooled connection.
887 SpdySessionKey spdy_session_key
= GetSpdySessionKey();
888 existing_spdy_session_
=
889 session_
->spdy_session_pool()->FindAvailableSession(
890 spdy_session_key
, net_log_
);
891 if (existing_spdy_session_
) {
893 next_state_
= STATE_CREATE_STREAM
;
895 // It is possible that the spdy session no longer exists.
896 ReturnToStateInitConnection(true /* close connection */);
901 // TODO(willchan): Make this a bit more exact. Maybe there are recoverable
902 // errors, such as ignoring certificate errors for Alternate-Protocol.
903 if (result
< 0 && waiting_job_
) {
904 waiting_job_
->Resume(this);
908 if (result
< 0 && session_
->force_http_pipelining()) {
909 stream_factory_
->AbortPipelinedRequestsWithKey(
910 this, *http_pipelining_key_
.get(), result
, server_ssl_config_
);
913 // |result| may be the result of any of the stacked pools. The following
914 // logic is used when determining how to interpret an error.
916 // and connection_->socket() != NULL, then the SSL handshake ran and it
917 // is a potentially recoverable error.
918 // and connection_->socket == NULL and connection_->is_ssl_error() is true,
919 // then the SSL handshake ran with an unrecoverable error.
920 // otherwise, the error came from one of the other pools.
921 bool ssl_started
= using_ssl_
&& (result
== OK
|| connection_
->socket() ||
922 connection_
->is_ssl_error());
924 if (ssl_started
&& (result
== OK
|| IsCertificateError(result
))) {
925 if (using_quic_
&& result
== OK
) {
926 was_npn_negotiated_
= true;
927 NextProto protocol_negotiated
=
928 SSLClientSocket::NextProtoFromString("quic/1+spdy/3");
929 protocol_negotiated_
= protocol_negotiated
;
931 SSLClientSocket
* ssl_socket
=
932 static_cast<SSLClientSocket
*>(connection_
->socket());
933 if (ssl_socket
->WasNpnNegotiated()) {
934 was_npn_negotiated_
= true;
936 std::string server_protos
;
937 SSLClientSocket::NextProtoStatus status
=
938 ssl_socket
->GetNextProto(&proto
, &server_protos
);
939 NextProto protocol_negotiated
=
940 SSLClientSocket::NextProtoFromString(proto
);
941 protocol_negotiated_
= protocol_negotiated
;
943 NetLog::TYPE_HTTP_STREAM_REQUEST_PROTO
,
944 base::Bind(&NetLogHttpStreamProtoCallback
,
945 status
, &proto
, &server_protos
));
946 if (ssl_socket
->was_spdy_negotiated())
949 if (ShouldForceSpdySSL())
952 } else if (proxy_info_
.is_https() && connection_
->socket() &&
954 ProxyClientSocket
* proxy_socket
=
955 static_cast<ProxyClientSocket
*>(connection_
->socket());
956 if (proxy_socket
->IsUsingSpdy()) {
957 was_npn_negotiated_
= true;
958 protocol_negotiated_
= proxy_socket
->GetProtocolNegotiated();
963 // We may be using spdy without SSL
964 if (ShouldForceSpdyWithoutSSL())
967 if (result
== ERR_PROXY_AUTH_REQUESTED
||
968 result
== ERR_HTTPS_PROXY_TUNNEL_RESPONSE
) {
969 DCHECK(!ssl_started
);
970 // Other state (i.e. |using_ssl_|) suggests that |connection_| will have an
971 // SSL socket, but there was an error before that could happen. This
972 // puts the in progress HttpProxy socket into |connection_| in order to
973 // complete the auth (or read the response body). The tunnel restart code
974 // is careful to remove it before returning control to the rest of this
976 connection_
.reset(connection_
->release_pending_http_proxy_connection());
983 stream_
= quic_request_
.ReleaseStream();
984 next_state_
= STATE_NONE
;
988 if (!ssl_started
&& result
< 0 && original_url_
.get()) {
989 HistogramBrokenAlternateProtocolLocation(
990 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB
);
991 // Mark the alternate protocol as broken and fallback.
992 session_
->http_server_properties()->SetBrokenAlternateProtocol(
993 HostPortPair::FromURL(*original_url_
));
997 if (result
< 0 && !ssl_started
)
998 return ReconsiderProxyAfterError(result
);
999 establishing_tunnel_
= false;
1001 if (connection_
->socket()) {
1002 LogHttpConnectedMetrics(*connection_
);
1004 // We officially have a new connection. Record the type.
1005 if (!connection_
->is_reused()) {
1006 ConnectionType type
= using_spdy_
? CONNECTION_SPDY
: CONNECTION_HTTP
;
1007 UpdateConnectionTypeHistograms(type
);
1011 // Handle SSL errors below.
1013 DCHECK(ssl_started
);
1014 if (IsCertificateError(result
)) {
1015 if (using_spdy_
&& original_url_
.get() &&
1016 original_url_
->SchemeIs("http")) {
1017 // We ignore certificate errors for http over spdy.
1018 spdy_certificate_error_
= result
;
1021 result
= HandleCertificateError(result
);
1022 if (result
== OK
&& !connection_
->socket()->IsConnectedAndIdle()) {
1023 ReturnToStateInitConnection(true /* close connection */);
1032 next_state_
= STATE_CREATE_STREAM
;
1036 int HttpStreamFactoryImpl::Job::DoWaitingUserAction(int result
) {
1037 // This state indicates that the stream request is in a partially
1038 // completed state, and we've called back to the delegate for more
1041 // We're always waiting here for the delegate to call us back.
1042 return ERR_IO_PENDING
;
1045 int HttpStreamFactoryImpl::Job::DoCreateStream() {
1046 DCHECK(connection_
->socket() || existing_spdy_session_
.get() ||
1047 existing_available_pipeline_
|| using_quic_
);
1049 next_state_
= STATE_CREATE_STREAM_COMPLETE
;
1051 // We only set the socket motivation if we're the first to use
1052 // this socket. Is there a race for two SPDY requests? We really
1053 // need to plumb this through to the connect level.
1054 if (connection_
->socket() && !connection_
->is_reused())
1055 SetSocketMotivation();
1058 // We may get ftp scheme when fetching ftp resources through proxy.
1059 bool using_proxy
= (proxy_info_
.is_http() || proxy_info_
.is_https()) &&
1060 (request_info_
.url
.SchemeIs("http") ||
1061 request_info_
.url
.SchemeIs("ftp"));
1062 if (stream_factory_
->http_pipelined_host_pool_
.
1063 IsExistingPipelineAvailableForKey(*http_pipelining_key_
.get())) {
1064 DCHECK(!stream_factory_
->for_websockets_
);
1065 stream_
.reset(stream_factory_
->http_pipelined_host_pool_
.
1066 CreateStreamOnExistingPipeline(
1067 *http_pipelining_key_
.get()));
1068 CHECK(stream_
.get());
1069 } else if (stream_factory_
->for_websockets_
) {
1071 DCHECK(request_
->websocket_handshake_stream_create_helper());
1072 websocket_stream_
.reset(
1073 request_
->websocket_handshake_stream_create_helper()
1074 ->CreateBasicStream(connection_
.Pass(), using_proxy
));
1075 } else if (!using_proxy
&& IsRequestEligibleForPipelining()) {
1076 // TODO(simonjam): Support proxies.
1078 stream_factory_
->http_pipelined_host_pool_
.CreateStreamOnNewPipeline(
1079 *http_pipelining_key_
.get(),
1080 connection_
.release(),
1084 was_npn_negotiated_
,
1085 protocol_negotiated_
));
1086 CHECK(stream_
.get());
1088 stream_
.reset(new HttpBasicStream(connection_
.release(), using_proxy
));
1093 CHECK(!stream_
.get());
1096 const ProxyServer
& proxy_server
= proxy_info_
.proxy_server();
1097 PrivacyMode privacy_mode
= request_info_
.privacy_mode
;
1098 SpdySessionKey
spdy_session_key(origin_
, proxy_server
, privacy_mode
);
1099 if (IsHttpsProxyAndHttpUrl()) {
1100 // If we don't have a direct SPDY session, and we're using an HTTPS
1101 // proxy, then we might have a SPDY session to the proxy.
1102 // We never use privacy mode for connection to proxy server.
1103 spdy_session_key
= SpdySessionKey(proxy_server
.host_port_pair(),
1104 ProxyServer::Direct(),
1105 PRIVACY_MODE_DISABLED
);
1109 base::WeakPtr
<SpdySession
> spdy_session
;
1110 if (existing_spdy_session_
.get()) {
1111 // We picked up an existing session, so we don't need our socket.
1112 if (connection_
->socket())
1113 connection_
->socket()->Disconnect();
1114 connection_
->Reset();
1115 std::swap(spdy_session
, existing_spdy_session_
);
1117 SpdySessionPool
* spdy_pool
= session_
->spdy_session_pool();
1118 spdy_session
= spdy_pool
->FindAvailableSession(spdy_session_key
, net_log_
);
1119 if (!spdy_session
) {
1121 spdy_pool
->CreateAvailableSessionFromSocket(spdy_session_key
,
1124 spdy_certificate_error_
,
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);
1131 spdy_session_direct_
= direct
;
1133 // Create a SpdyHttpStream attached to the session;
1134 // OnNewSpdySessionReadyCallback is not called until an event loop
1135 // iteration later, so if the SpdySession is closed between then, allow
1136 // reuse state from the underlying socket, sampled by SpdyHttpStream,
1137 // bubble up to the request.
1138 bool use_relative_url
= direct
|| request_info_
.url
.SchemeIs("https");
1139 stream_
.reset(new SpdyHttpStream(new_spdy_session_
, use_relative_url
));
1146 return ERR_CONNECTION_CLOSED
;
1148 // TODO(willchan): Delete this code, because eventually, the
1149 // HttpStreamFactoryImpl will be creating all the SpdyHttpStreams, since it
1150 // will know when SpdySessions become available.
1152 if (stream_factory_
->for_websockets_
) {
1153 // TODO(ricea): Restore this code when WebSockets over SPDY is implemented.
1156 bool use_relative_url
= direct
|| request_info_
.url
.SchemeIs("https");
1157 stream_
.reset(new SpdyHttpStream(spdy_session
, use_relative_url
));
1162 int HttpStreamFactoryImpl::Job::DoCreateStreamComplete(int result
) {
1166 session_
->proxy_service()->ReportSuccess(proxy_info_
);
1167 next_state_
= STATE_NONE
;
1171 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuth() {
1172 next_state_
= STATE_RESTART_TUNNEL_AUTH_COMPLETE
;
1173 ProxyClientSocket
* proxy_socket
=
1174 static_cast<ProxyClientSocket
*>(connection_
->socket());
1175 return proxy_socket
->RestartWithAuth(io_callback_
);
1178 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete(int result
) {
1179 if (result
== ERR_PROXY_AUTH_REQUESTED
)
1183 // Now that we've got the HttpProxyClientSocket connected. We have
1184 // to release it as an idle socket into the pool and start the connection
1185 // process from the beginning. Trying to pass it in with the
1186 // SSLSocketParams might cause a deadlock since params are dispatched
1187 // interchangeably. This request won't necessarily get this http proxy
1188 // socket, but there will be forward progress.
1189 establishing_tunnel_
= false;
1190 ReturnToStateInitConnection(false /* do not close connection */);
1194 return ReconsiderProxyAfterError(result
);
1197 void HttpStreamFactoryImpl::Job::ReturnToStateInitConnection(
1198 bool close_connection
) {
1199 if (close_connection
&& connection_
->socket())
1200 connection_
->socket()->Disconnect();
1201 connection_
->Reset();
1204 request_
->RemoveRequestFromSpdySessionRequestMap();
1205 request_
->RemoveRequestFromHttpPipeliningRequestMap();
1208 next_state_
= STATE_INIT_CONNECTION
;
1211 void HttpStreamFactoryImpl::Job::SetSocketMotivation() {
1212 if (request_info_
.motivation
== HttpRequestInfo::PRECONNECT_MOTIVATED
)
1213 connection_
->socket()->SetSubresourceSpeculation();
1214 else if (request_info_
.motivation
== HttpRequestInfo::OMNIBOX_MOTIVATED
)
1215 connection_
->socket()->SetOmniboxSpeculation();
1216 // TODO(mbelshe): Add other motivations (like EARLY_LOAD_MOTIVATED).
1219 bool HttpStreamFactoryImpl::Job::IsHttpsProxyAndHttpUrl() const {
1220 if (!proxy_info_
.is_https())
1222 if (original_url_
.get()) {
1223 // We currently only support Alternate-Protocol where the original scheme
1225 DCHECK(original_url_
->SchemeIs("http"));
1226 return original_url_
->SchemeIs("http");
1228 return request_info_
.url
.SchemeIs("http");
1231 // Sets several fields of ssl_config for the given origin_server based on the
1232 // proxy info and other factors.
1233 void HttpStreamFactoryImpl::Job::InitSSLConfig(
1234 const HostPortPair
& origin_server
,
1235 SSLConfig
* ssl_config
,
1236 bool is_proxy
) const {
1237 if (proxy_info_
.is_https() && ssl_config
->send_client_cert
) {
1238 // When connecting through an HTTPS proxy, disable TLS False Start so
1239 // that client authentication errors can be distinguished between those
1240 // originating from the proxy server (ERR_PROXY_CONNECTION_FAILED) and
1241 // those originating from the endpoint (ERR_SSL_PROTOCOL_ERROR /
1242 // ERR_BAD_SSL_CLIENT_AUTH_CERT).
1243 // TODO(rch): This assumes that the HTTPS proxy will only request a
1244 // client certificate during the initial handshake.
1245 // http://crbug.com/59292
1246 ssl_config
->false_start_enabled
= false;
1250 FALLBACK_NONE
= 0, // SSL version fallback did not occur.
1251 FALLBACK_SSL3
= 1, // Fell back to SSL 3.0.
1252 FALLBACK_TLS1
= 2, // Fell back to TLS 1.0.
1253 FALLBACK_TLS1_1
= 3, // Fell back to TLS 1.1.
1257 int fallback
= FALLBACK_NONE
;
1258 if (ssl_config
->version_fallback
) {
1259 switch (ssl_config
->version_max
) {
1260 case SSL_PROTOCOL_VERSION_SSL3
:
1261 fallback
= FALLBACK_SSL3
;
1263 case SSL_PROTOCOL_VERSION_TLS1
:
1264 fallback
= FALLBACK_TLS1
;
1266 case SSL_PROTOCOL_VERSION_TLS1_1
:
1267 fallback
= FALLBACK_TLS1_1
;
1271 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback",
1272 fallback
, FALLBACK_MAX
);
1274 // We also wish to measure the amount of fallback connections for a host that
1275 // we know implements TLS up to 1.2. Ideally there would be no fallback here
1276 // but high numbers of SSLv3 would suggest that SSLv3 fallback is being
1277 // caused by network middleware rather than buggy HTTPS servers.
1278 const std::string
& host
= origin_server
.host();
1280 host
.size() >= 10 &&
1281 host
.compare(host
.size() - 10, 10, "google.com") == 0 &&
1282 (host
.size() == 10 || host
[host
.size()-11] == '.')) {
1283 UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback",
1284 fallback
, FALLBACK_MAX
);
1287 if (request_info_
.load_flags
& LOAD_VERIFY_EV_CERT
)
1288 ssl_config
->verify_ev_cert
= true;
1290 // Disable Channel ID if privacy mode is enabled.
1291 if (request_info_
.privacy_mode
== PRIVACY_MODE_ENABLED
)
1292 ssl_config
->channel_id_enabled
= false;
1296 int HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError(int error
) {
1297 DCHECK(!pac_request_
);
1299 // A failure to resolve the hostname or any error related to establishing a
1300 // TCP connection could be grounds for trying a new proxy configuration.
1302 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1303 // to proxy servers. The hostname in those URLs might fail to resolve if we
1304 // are still using a non-proxy config. We need to check if a proxy config
1305 // now exists that corresponds to a proxy server that could load the URL.
1308 case ERR_PROXY_CONNECTION_FAILED
:
1309 case ERR_NAME_NOT_RESOLVED
:
1310 case ERR_INTERNET_DISCONNECTED
:
1311 case ERR_ADDRESS_UNREACHABLE
:
1312 case ERR_CONNECTION_CLOSED
:
1313 case ERR_CONNECTION_TIMED_OUT
:
1314 case ERR_CONNECTION_RESET
:
1315 case ERR_CONNECTION_REFUSED
:
1316 case ERR_CONNECTION_ABORTED
:
1318 case ERR_TUNNEL_CONNECTION_FAILED
:
1319 case ERR_SOCKS_CONNECTION_FAILED
:
1320 // This can happen in the case of trying to talk to a proxy using SSL, and
1321 // ending up talking to a captive portal that supports SSL instead.
1322 case ERR_PROXY_CERTIFICATE_INVALID
:
1323 // This can happen when trying to talk SSL to a non-SSL server (Like a
1325 case ERR_SSL_PROTOCOL_ERROR
:
1327 case ERR_SOCKS_CONNECTION_HOST_UNREACHABLE
:
1328 // Remap the SOCKS-specific "host unreachable" error to a more
1329 // generic error code (this way consumers like the link doctor
1330 // know to substitute their error page).
1332 // Note that if the host resolving was done by the SOCKS5 proxy, we can't
1333 // differentiate between a proxy-side "host not found" versus a proxy-side
1334 // "address unreachable" error, and will report both of these failures as
1335 // ERR_ADDRESS_UNREACHABLE.
1336 return ERR_ADDRESS_UNREACHABLE
;
1341 if (request_info_
.load_flags
& LOAD_BYPASS_PROXY
) {
1345 if (proxy_info_
.is_https() && proxy_ssl_config_
.send_client_cert
) {
1346 session_
->ssl_client_auth_cache()->Remove(
1347 proxy_info_
.proxy_server().host_port_pair());
1350 int rv
= session_
->proxy_service()->ReconsiderProxyAfterError(
1351 request_info_
.url
, &proxy_info_
, io_callback_
, &pac_request_
, net_log_
);
1352 if (rv
== OK
|| rv
== ERR_IO_PENDING
) {
1353 // If the error was during connection setup, there is no socket to
1355 if (connection_
->socket())
1356 connection_
->socket()->Disconnect();
1357 connection_
->Reset();
1359 request_
->RemoveRequestFromSpdySessionRequestMap();
1360 request_
->RemoveRequestFromHttpPipeliningRequestMap();
1362 next_state_
= STATE_RESOLVE_PROXY_COMPLETE
;
1364 // If ReconsiderProxyAfterError() failed synchronously, it means
1365 // there was nothing left to fall-back to, so fail the transaction
1366 // with the last connection error we got.
1367 // TODO(eroman): This is a confusing contract, make it more obvious.
1374 int HttpStreamFactoryImpl::Job::HandleCertificateError(int error
) {
1376 DCHECK(IsCertificateError(error
));
1378 SSLClientSocket
* ssl_socket
=
1379 static_cast<SSLClientSocket
*>(connection_
->socket());
1380 ssl_socket
->GetSSLInfo(&ssl_info_
);
1382 // Add the bad certificate to the set of allowed certificates in the
1383 // SSL config object. This data structure will be consulted after calling
1384 // RestartIgnoringLastError(). And the user will be asked interactively
1385 // before RestartIgnoringLastError() is ever called.
1386 SSLConfig::CertAndStatus bad_cert
;
1388 // |ssl_info_.cert| may be NULL if we failed to create
1389 // X509Certificate for whatever reason, but normally it shouldn't
1390 // happen, unless this code is used inside sandbox.
1391 if (ssl_info_
.cert
.get() == NULL
||
1392 !X509Certificate::GetDEREncoded(ssl_info_
.cert
->os_cert_handle(),
1393 &bad_cert
.der_cert
)) {
1396 bad_cert
.cert_status
= ssl_info_
.cert_status
;
1397 server_ssl_config_
.allowed_bad_certs
.push_back(bad_cert
);
1399 int load_flags
= request_info_
.load_flags
;
1400 if (session_
->params().ignore_certificate_errors
)
1401 load_flags
|= LOAD_IGNORE_ALL_CERT_ERRORS
;
1402 if (ssl_socket
->IgnoreCertError(error
, load_flags
))
1407 void HttpStreamFactoryImpl::Job::SwitchToSpdyMode() {
1408 if (HttpStreamFactory::spdy_enabled())
1413 void HttpStreamFactoryImpl::Job::LogHttpConnectedMetrics(
1414 const ClientSocketHandle
& handle
) {
1415 UMA_HISTOGRAM_ENUMERATION("Net.HttpSocketType", handle
.reuse_type(),
1416 ClientSocketHandle::NUM_TYPES
);
1418 switch (handle
.reuse_type()) {
1419 case ClientSocketHandle::UNUSED
:
1420 UMA_HISTOGRAM_CUSTOM_TIMES("Net.HttpConnectionLatency",
1421 handle
.setup_time(),
1422 base::TimeDelta::FromMilliseconds(1),
1423 base::TimeDelta::FromMinutes(10),
1426 case ClientSocketHandle::UNUSED_IDLE
:
1427 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_UnusedSocket",
1429 base::TimeDelta::FromMilliseconds(1),
1430 base::TimeDelta::FromMinutes(6),
1433 case ClientSocketHandle::REUSED_IDLE
:
1434 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_ReusedSocket",
1436 base::TimeDelta::FromMilliseconds(1),
1437 base::TimeDelta::FromMinutes(6),
1446 bool HttpStreamFactoryImpl::Job::IsPreconnecting() const {
1447 DCHECK_GE(num_streams_
, 0);
1448 return num_streams_
> 0;
1451 bool HttpStreamFactoryImpl::Job::IsOrphaned() const {
1452 return !IsPreconnecting() && !request_
;
1455 void HttpStreamFactoryImpl::Job::ReportJobSuccededForRequest() {
1456 if (using_existing_quic_session_
) {
1457 // If an existing session was used, then no TCP connection was
1459 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_NO_RACE
);
1460 } else if (original_url_
) {
1461 // This job was the alternate protocol job, and hence won the race.
1462 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_WON_RACE
);
1464 // This job was the normal job, and hence the alternate protocol job lost
1466 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_LOST_RACE
);
1470 bool HttpStreamFactoryImpl::Job::IsRequestEligibleForPipelining() {
1471 if (IsPreconnecting() || !request_
) {
1474 if (stream_factory_
->for_websockets_
) {
1477 if (session_
->force_http_pipelining()) {
1480 if (!session_
->params().http_pipelining_enabled
) {
1486 if (request_info_
.method
!= "GET" && request_info_
.method
!= "HEAD") {
1489 if (request_info_
.load_flags
&
1490 (net::LOAD_MAIN_FRAME
| net::LOAD_SUB_FRAME
| net::LOAD_PREFETCH
|
1491 net::LOAD_IS_DOWNLOAD
)) {
1492 // Avoid pipelining resources that may be streamed for a long time.
1495 return stream_factory_
->http_pipelined_host_pool_
.IsKeyEligibleForPipelining(
1496 *http_pipelining_key_
.get());